Repository navigation
Expand file tree
/
Copy pathorchestrator.js
More file actions
1326 lines (1211 loc) · 44.3 KB
/
Copy pathorchestrator.js
File metadata and controls
1326 lines (1211 loc) · 44.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"use strict";
const AcpClient = require("./acp-client");
const crypto = require("crypto");
const fs = require("fs");
const path = require("path");
const { RateLimiterRegistry } = require("./rate-limiter");
const { Semaphore } = require("./concurrency");
const {
effectivePolicyForAgent,
maskClientCapabilities,
assertAllowedClientRequest,
classifyClientMethod,
classifyPermissionRequest,
filterPromptContentForCapabilities,
} = require("./policy");
const {
writeManifest,
writeInputPrompt,
writeRoundReports,
writeReviewerPrompt,
writeReviewerReport,
writeApprovedPlan,
writeApprovedPlanIndex,
} = require("./artifact-store");
const { redact } = require("./redact");
const {
MAX_TURNS,
AGENT_GROUPS,
WORKFLOW,
MCP_SERVERS,
AGENT_TIMEOUT_MS,
MAX_RETRIES,
RETRY_DELAY_MS,
HEARTBEAT_MS,
MAX_RETRY_AFTER_MS,
RETRYABLE_PATTERNS,
MAX_LINE_BYTES,
MAX_OUTPUT_BYTES,
REVIEWER_AGENT_CHARS,
RATE_LIMITS,
PROBE_TIMEOUT_MS,
DEBUG_LOG,
} = require("./config");
const rateLimiter = new RateLimiterRegistry(RATE_LIMITS);
const log = (...args) =>
process.stderr.write("[orchestrator] " + args.join(" ") + "\n");
const debugLog = DEBUG_LOG
? (msg) => process.stderr.write(`[orchestrator] [debug] ${msg}\n`)
: null;
if (debugLog)
debugLog(
"debug logging enabled — full ACP frames + sub-agent stderr will be mirrored to stderr",
);
// ─── Error classification ─────────────────────────────────────────────────────
const RETRYABLE = RETRYABLE_PATTERNS.map((p) => new RegExp(p, "i"));
function isRetryable(err) {
const msg = err?.message || String(err);
return RETRYABLE.some((re) => re.test(msg));
}
function retryAfterMs(err) {
const m = (err?.message || "").match(/retry.{0,10}?(\d+)\s*s/i);
if (!m) return null;
const ms = parseInt(m[1], 10) * 1000;
if (!Number.isFinite(ms) || ms < 0) return null;
return Math.min(ms, MAX_RETRY_AFTER_MS);
}
function extractHttpStatus(msg) {
const m = String(msg || "").match(/\b([45]\d{2})\b/);
return m ? parseInt(m[1], 10) : null;
}
// Heuristic: a stderr line is treated as a provider error if it contains a 4xx/5xx
// HTTP status code together with vocabulary that strongly implies an HTTP/API failure.
// This keeps ordinary debug noise out while catching the common provider error formats.
const PROVIDER_ERROR_CONTEXT_RE =
/\b(error|err|fail|exception|unavailable|gateway|timeout|forbidden|unauthorized|api|http|status|request|response|overloaded|rate.?limit|too\s+many|server|service)\b/i;
function detectProviderError(line) {
const code = extractHttpStatus(line);
if (!code) return null;
if (!PROVIDER_ERROR_CONTEXT_RE.test(line)) return null;
return code;
}
function truncateLine(line, max = 240) {
const s = String(line).trim();
return s.length <= max ? s : s.slice(0, max) + "…";
}
async function sleepInterruptible(ms, isCancelled) {
const end = performance.now() + ms;
while (performance.now() < end) {
if (isCancelled?.()) throw new Error("CANCELLED");
await new Promise((r) =>
setTimeout(r, Math.max(0, Math.min(100, end - performance.now()))),
);
}
}
// ─── Prompt utilities ─────────────────────────────────────────────────────────
const DECISION_RE = /^[\s>*#`]*(APPROVED|QUESTIONS)\b[ \t]*:?[ \t]*/im;
const INJECT_RE = /^([ \t>*#`]*)(APPROVED|QUESTIONS)\b([ \t]*:?)/gim;
function parseReviewerDecision(text) {
const raw = String(text || "");
const match = DECISION_RE.exec(raw);
if (!match) {
return { kind: null, body: raw.trim() };
}
return {
kind: match[1].toLowerCase(),
body: raw.slice(match.index + match[0].length).trim(),
prefix: raw.slice(0, match.index).trim(),
};
}
function sanitizeForReviewer(text) {
return String(text || "").replace(INJECT_RE, "$1$2_BY_AGENT$3");
}
function taskToText(task) {
const blocks = Array.isArray(task)
? task
: [{ type: "text", text: String(task || "") }];
return blocks
.map((b) => b.text || "")
.join("\n")
.trim();
}
function taskNonTextBlocks(task) {
if (!Array.isArray(task)) return [];
return task.filter((block) => block?.type !== "text");
}
function appendTextBlock(blocks, text) {
return [
...(Array.isArray(blocks)
? blocks
: [{ type: "text", text: String(blocks || "") }]),
{ type: "text", text },
];
}
function truncateForReviewer(text) {
if (!REVIEWER_AGENT_CHARS || text.length <= REVIEWER_AGENT_CHARS)
return text;
return (
text.slice(0, REVIEWER_AGENT_CHARS) +
"\n...[TRUNCATED BY ORCHESTRATOR]..."
);
}
function escapeForReviewerReport(value) {
return String(value || "")
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">");
}
function phaseInstruction(group) {
if (group.strategy === "parallel_reports") {
return [
"You are running in the ORCHESTRATOR PARALLEL REPORTS PHASE.",
"",
"Do not modify files. Do not run write, edit, install, migration, or destructive commands.",
"Inspect/read only and produce an independent Markdown report.",
"",
"Use this structure:",
"1. Recommendation",
"2. Rationale",
"3. Risks / edge cases",
"4. Concrete implementation steps",
"5. Tests to add or update",
"6. Open questions / assumptions",
].join("\n");
}
return "";
}
function withPhaseInstruction(task, group) {
const text = phaseInstruction(group);
if (!text) return task;
return [
{ type: "text", text },
...(Array.isArray(task)
? task
: [{ type: "text", text: String(task || "") }]),
];
}
// ─── Group / workflow helpers ─────────────────────────────────────────────────
const GROUP_DIRECTIVE_RE =
/^[ \t]*@orchestrator[ \t]+(?:group|mode)[ \t]*:[ \t]*([A-Za-z0-9_.-]+)[ \t]*$/im;
function firstTextDirectiveLine(task) {
const blocks = Array.isArray(task)
? task
: [{ type: "text", text: String(task || "") }];
const firstTextIndex = blocks.findIndex(
(block) => typeof block?.text === "string",
);
if (firstTextIndex === -1) return null;
const lines = blocks[firstTextIndex].text.split(/\r?\n/);
const lineIndex = lines.findIndex((line) => line.trim() !== "");
if (lineIndex === -1) return null;
return {
blockIndex: firstTextIndex,
lineIndex,
line: lines[lineIndex],
lines,
};
}
function slashGroupLineRe(groupNames) {
const escaped = groupNames
.map((name) => String(name).replace(/[.*+?^${}()|[\]\\]/g, "\\$&"))
.join("|");
if (!escaped) return null;
return new RegExp(`^[ \\t]*/(${escaped})(?:[ \\t]+(.*))?[ \\t]*$`, "im");
}
function requestedGroupName(task, groupNames = Object.keys(AGENT_GROUPS)) {
const first = firstTextDirectiveLine(task);
if (!first) return null;
const slashRe = slashGroupLineRe(groupNames);
const m =
first.line.match(GROUP_DIRECTIVE_RE) ||
(slashRe ? first.line.match(slashRe) : null);
return m ? m[1] : null;
}
function stripGroupDirective(task, groupNames = Object.keys(AGENT_GROUPS)) {
const slashRe = slashGroupLineRe(groupNames);
const blocks = Array.isArray(task)
? task
: [{ type: "text", text: String(task || "") }];
const first = firstTextDirectiveLine(blocks);
if (!first) return blocks;
const groupDirective = first.line.match(GROUP_DIRECTIVE_RE);
const slashDirective = slashRe ? first.line.match(slashRe) : null;
if (!groupDirective && !slashDirective) return blocks;
return blocks.map((block, index) => {
if (index !== first.blockIndex || typeof block.text !== "string")
return block;
const lines = block.text.split(/\r?\n/);
const slashInput = slashDirective?.[2]?.trim();
if (slashInput) lines[first.lineIndex] = slashInput;
else lines.splice(first.lineIndex, 1);
return { ...block, text: lines.join("\n").trim() };
});
}
function nextGroupName(current) {
const idx = WORKFLOW.indexOf(current);
if (idx === -1 || idx >= WORKFLOW.length - 1) return null;
return WORKFLOW[idx + 1];
}
// Find the latest approved-plan.md for a group under the artifact dir.
// Used to auto-prepend the plan to code-phase prompts.
function realInside(parentReal, childReal) {
return (
childReal === parentReal || childReal.startsWith(parentReal + path.sep)
);
}
function resolveArtifactRootForRead(workDir, artifactDir) {
if (path.isAbsolute(artifactDir)) {
throw new Error(
`artifactDir must be workspace-relative: ${artifactDir}`,
);
}
const workspaceReal = fs.realpathSync(workDir);
const root = path.resolve(workDir, artifactDir);
if (!fs.existsSync(root)) return null;
const rootReal = fs.realpathSync(root);
if (!realInside(workspaceReal, rootReal)) {
throw new Error(
`artifactDir resolves outside workspace through symlink: ${artifactDir}`,
);
}
return { root, rootReal, workspaceReal };
}
function readApprovedPlanFileWithinRoot(resolvedRoot, file) {
if (!resolvedRoot || !fs.existsSync(file)) return null;
const targetReal = fs.realpathSync(file);
if (!realInside(resolvedRoot.rootReal, targetReal)) {
throw new Error(
`approved plan resolves outside artifact root: ${file}`,
);
}
return fs.readFileSync(file, "utf8");
}
function readApprovedPlanFile(workDir, artifactDir, file) {
const resolvedRoot = resolveArtifactRootForRead(workDir, artifactDir);
return readApprovedPlanFileWithinRoot(resolvedRoot, file);
}
function splitMarkdownFrontmatter(text) {
const raw = String(text || "");
const m = raw.match(/^---\n([\s\S]*?)\n---\n\n?([\s\S]*)$/);
if (!m) return { meta: {}, body: raw };
const meta = {};
for (const line of m[1].split(/\r?\n/)) {
const idx = line.indexOf(":");
if (idx === -1) continue;
const key = line.slice(0, idx).trim();
const value = line.slice(idx + 1).trim();
if (!key) continue;
try {
meta[key] = JSON.parse(value);
} catch {
meta[key] = value;
}
}
return { meta, body: m[2] };
}
function approvedPlanHash(text) {
return crypto
.createHash("sha256")
.update(String(text || "").replace(/\n$/, ""))
.digest("hex");
}
function readApprovedPlan(workDir, artifactDir, file, expectedSha256 = null) {
const raw = readApprovedPlanFile(workDir, artifactDir, file);
if (!raw) return null;
const plan = splitMarkdownFrontmatter(raw);
const sha256 = expectedSha256 || plan.meta.sha256;
if (!sha256) {
throw new Error(`approved plan has no sha256 metadata: ${file}`);
}
const actual = approvedPlanHash(plan.body);
if (actual !== sha256) {
throw new Error(`approved plan hash mismatch: ${file}`);
}
return { ...plan, raw, sha256 };
}
function isExpectedScanRace(err) {
const code = err?.code;
return code === "ENOENT" || code === "ENOTDIR";
}
function findLatestApprovedPlan(workDir, artifactDir, groupName, onWarning) {
let resolvedRoot;
try {
resolvedRoot = resolveArtifactRootForRead(workDir, artifactDir);
} catch (err) {
if (!isExpectedScanRace(err)) {
onWarning?.(
`approved-plan scan failed for ${artifactDir}: ${err.message}`,
);
}
return null;
}
if (!resolvedRoot) return null;
const root = resolvedRoot.root;
let latest = null;
let latestMtime = 0;
let entries;
try {
entries = fs.readdirSync(root);
} catch (err) {
if (!isExpectedScanRace(err)) {
onWarning?.(`approved-plan scan failed at ${root}: ${err.message}`);
}
return null;
}
for (const runDir of entries) {
if (!runDir.startsWith("orch-")) continue;
const candidate = path.join(root, runDir, "approved-plan.md");
try {
if (!fs.existsSync(candidate)) continue;
const text = readApprovedPlanFileWithinRoot(
resolvedRoot,
candidate,
);
const { meta } = splitMarkdownFrontmatter(text);
if (groupName && meta.group !== groupName) continue;
const stat = fs.statSync(candidate);
if (stat.mtimeMs > latestMtime) {
latestMtime = stat.mtimeMs;
latest = candidate;
}
} catch (err) {
if (isExpectedScanRace(err)) continue;
onWarning?.(
`approved-plan candidate skipped (${path.relative(root, candidate)}): ${err.message}`,
);
}
}
return latest;
}
// ─── Health probe ─────────────────────────────────────────────────────────────
async function probeAgent(
agentCfg,
workDir,
notifyZed,
registerClient,
isCancelled,
) {
if (isCancelled?.()) throw new Error("CANCELLED");
const client = new AcpClient(agentCfg, workDir, {
maxLineBytes: MAX_LINE_BYTES,
maxOutputBytes: MAX_OUTPUT_BYTES,
debugLog,
});
const unregister = registerClient?.(client);
try {
await client.probe(PROBE_TIMEOUT_MS);
return true;
} catch (err) {
if (isCancelled?.()) throw new Error("CANCELLED");
notifyZed?.(
`> **${agentCfg.name}** — probe failed: ${redact(err.message)} (will skip)\n`,
);
return false;
} finally {
unregister?.();
}
}
function filterMcpServersForCapabilities(servers, agentCapabilities = {}) {
const caps = agentCapabilities.mcpCapabilities || {};
const kept = [];
const dropped = [];
for (const server of servers || []) {
const normalized = normalizeMcpServerForChild(server);
if (!normalized) {
if (server) dropped.push(server.name || server.type || "unknown");
} else if (isStdioMcpServer(server)) {
kept.push(normalized);
} else if (server.type === "http" && caps.http) {
kept.push(normalized);
} else if (server.type === "sse" && caps.sse) {
kept.push(normalized);
} else if (server) {
dropped.push(server.name || server.type || "unknown");
}
}
return { kept, dropped };
}
function isStdioMcpServer(server) {
return Boolean(
server &&
(server.type === "stdio" ||
(!server.type && typeof server.command === "string")),
);
}
function normalizeMcpServerForChild(server) {
if (isStdioMcpServer(server)) {
return {
name: server.name,
command: server.command,
args: Array.isArray(server.args) ? server.args : [],
env: Array.isArray(server.env) ? server.env : [],
};
}
if (server?.type === "http") {
return {
type: "http",
name: server.name,
url: server.url,
headers: Array.isArray(server.headers) ? server.headers : [],
};
}
if (server?.type === "sse") {
return {
type: "sse",
name: server.name,
url: server.url,
headers: Array.isArray(server.headers) ? server.headers : [],
};
}
return null;
}
// ─── Single agent run ─────────────────────────────────────────────────────────
async function runAgent(
agentCfg,
workDir,
promptContent,
mcpServers = MCP_SERVERS,
onRateLimit,
registerClient,
onHeartbeat,
isCancelled,
onChildRequest,
policy,
onWarning,
zedClientCapabilities,
onProviderError,
) {
const rateLimitKey = rateLimiter.keyFor(agentCfg);
await rateLimiter.acquire(
agentCfg,
(waitMs) => onRateLimit?.(waitMs, rateLimitKey),
isCancelled,
);
const totalTimeoutMs = agentCfg.agentTimeoutMs ?? AGENT_TIMEOUT_MS;
const heartbeatMs = agentCfg.heartbeatMs ?? HEARTBEAT_MS;
// Single wall-clock budget for init + session/new + prompt so that a child
// hanging in initialize cannot exceed the configured agentTimeoutMs.
const deadline = performance.now() + totalTimeoutMs;
const remaining = (phase) => {
const left = deadline - performance.now();
if (left <= 0) {
const err = new Error(
`TIMEOUT:${totalTimeoutMs}ms — ${agentCfg.name} exceeded agentTimeoutMs before ${phase}`,
);
throw err;
}
return Math.ceil(left);
};
// Throttle provider-error notifications: at most one per (code) every 3s,
// so a flood of repeated 503s from a flaky proxy doesn't drown the chat.
const lastNotifiedByCode = new Map();
const onStderrLine = onProviderError
? (line) => {
const code = detectProviderError(line);
if (!code) return;
const now = Date.now();
const last = lastNotifiedByCode.get(code) || 0;
if (now - last < 3000) return;
lastNotifiedByCode.set(code, now);
onProviderError(code, redact(truncateLine(line)));
}
: null;
const client = new AcpClient(agentCfg, workDir, {
maxLineBytes: MAX_LINE_BYTES,
maxOutputBytes: MAX_OUTPUT_BYTES,
onRequest: onChildRequest,
onStderrLine,
debugLog,
});
const unregister = registerClient?.(client);
let heartbeat = null;
if (heartbeatMs > 0 && onHeartbeat) {
const t0 = performance.now();
heartbeat = setInterval(
() => onHeartbeat(Math.round((performance.now() - t0) / 1000)),
heartbeatMs,
);
}
try {
const initResult = await client.init(
maskClientCapabilities(zedClientCapabilities || {}, policy),
remaining("initialize"),
);
const agentCapabilities =
initResult?.agentCapabilities || initResult?.capabilities || {};
const filtered = filterPromptContentForCapabilities(
promptContent,
agentCapabilities,
);
if (filtered.dropped.length) {
onWarning?.(
`${agentCfg.name} does not advertise support for prompt block(s): ${filtered.dropped.join(", ")}. Those blocks were not sent to this child.`,
);
}
const mcpFiltered =
policy?.mcp === false
? {
kept: [],
dropped: (mcpServers || []).map(
(server) => server.name || server.type || "unknown",
),
}
: filterMcpServersForCapabilities(
mcpServers,
agentCapabilities,
);
if (mcpFiltered.dropped.length) {
onWarning?.(
`${agentCfg.name} does not advertise support for MCP server(s): ${mcpFiltered.dropped.join(", ")}. Those servers were not sent to this child.`,
);
}
const sid = await client.newSession(
workDir,
mcpFiltered.kept,
remaining("session/new"),
);
return await client.prompt(
sid,
filtered.content,
remaining("session/prompt"),
);
} finally {
if (heartbeat) clearInterval(heartbeat);
client.kill();
unregister?.();
}
}
// ─── Retry wrapper ────────────────────────────────────────────────────────────
async function runAgentWithRetry(
agentCfg,
workDir,
promptContent,
mcpServers,
onRetry,
onRateLimit,
registerClient,
isCancelled,
onHeartbeat,
onChildRequest,
policy,
onWarning,
zedClientCapabilities,
retryState,
onProviderError,
) {
const maxRetries = agentCfg.maxRetries ?? MAX_RETRIES;
const baseDelay = agentCfg.retryDelayMs ?? RETRY_DELAY_MS;
for (let attempt = 0; attempt <= maxRetries; attempt++) {
if (isCancelled?.()) throw new Error("CANCELLED");
try {
return await runAgent(
agentCfg,
workDir,
promptContent,
mcpServers,
onRateLimit,
registerClient,
onHeartbeat,
isCancelled,
onChildRequest,
policy,
onWarning,
zedClientCapabilities,
onProviderError,
);
} catch (err) {
if (isCancelled?.()) throw new Error("CANCELLED");
const retriable = isRetryable(err);
const last = attempt >= maxRetries;
if (!retriable || last || retryState?.hadSideEffect) throw err;
const suggested = retryAfterMs(err);
const delay = suggested ?? baseDelay * Math.pow(2, attempt);
onRetry(agentCfg.name, attempt + 1, maxRetries, err.message, delay);
await sleepInterruptible(delay, isCancelled);
}
}
}
// ─── Orchestration loop ───────────────────────────────────────────────────────
async function orchestrate(
sessionId,
runId,
promptId,
task,
workDir,
group,
ctx,
sessionMcpServers,
notifyText,
zedClientCapabilities,
) {
let taskText = taskToText(task);
let questions = null;
const isCancelled = () => ctx.cancelled;
const groupMaxTurns = group.maxTurns ?? MAX_TURNS;
const semaphore = new Semaphore(group.concurrency);
// In single_writer mode only launch the designated writer
const subAgents =
group.strategy === "single_writer"
? [
group.subAgents.find((a) => a.name === group.writer) ||
group.subAgents[0],
]
: group.subAgents;
const reviewer = group.reviewer;
const mcpServers = mergeMcpServers(sessionMcpServers, MCP_SERVERS);
const artifactDir = group.artifactDir || ".plan/orchestrator";
await writeManifest(workDir, artifactDir, runId, {
sessionId,
runId,
promptId,
group: group.name,
strategy: group.strategy,
createdAt: new Date().toISOString(),
workDir,
agents: subAgents.map((a) => a.name),
reviewer: reviewer.name,
});
const proxyChildRequest = (agentCfg, policy, retryState) => (msg) => {
if (isCancelled()) {
const err = new Error("CANCELLED");
err.code = -32000;
throw err;
}
assertAllowedClientRequest(msg, policy, agentCfg.name);
const kind = classifyClientMethod(msg?.method);
const permissionKind =
kind === "permission" ? classifyPermissionRequest(msg?.params) : null;
if (
kind === "write" ||
kind === "fs_unknown" ||
kind === "terminal" ||
(kind === "permission" && permissionKind !== "read")
) {
if (retryState) retryState.hadSideEffect = true;
}
return ctx.rpcToZed(
msg.method,
rewriteSessionId(msg.params, sessionId),
);
};
// For code group: auto-attach the latest approved plan from plan group
if (group.strategy === "single_writer" && group.attachApprovedPlanFrom) {
const sourceGroup = group.attachApprovedPlanFrom;
let planMeta = ctx.latestApprovedPlans?.[sourceGroup] || null;
let planFile = planMeta?.path || null;
let fromCurrentSession = Boolean(planFile);
if (!planFile) {
planFile = findLatestApprovedPlan(
workDir,
artifactDir,
sourceGroup,
(warning) =>
notifyText(sessionId, `> Warning: ${redact(warning)}\n`),
);
planMeta = null;
}
if (planFile) {
try {
const plan = readApprovedPlan(
workDir,
artifactDir,
planFile,
planMeta?.sha256 || null,
);
const alreadyMentioned =
taskToText(task).includes("approved-plan");
if (!alreadyMentioned) {
if (!fromCurrentSession) {
notifyText(
sessionId,
`> Warning: using latest approved plan found on disk, not a plan from this live session.\n`,
);
}
task = appendTextBlock(
task,
`\n## Approved plan (from ${path.relative(workDir, planFile)})\n\n${plan.body.replace(/\n$/, "")}`,
);
taskText = taskToText(task);
notifyText(
sessionId,
`> Attached approved plan from ${path.relative(workDir, planFile)}\n`,
);
}
} catch (err) {
notifyText(
sessionId,
`> Warning: approved plan could not be attached: ${redact(err.message)}\n`,
);
}
}
}
await writeInputPrompt(
workDir,
artifactDir,
runId,
redact(taskToText(task)),
{
sessionId,
promptId,
group: group.name,
},
);
for (let turn = 1; turn <= groupMaxTurns; turn++) {
if (isCancelled())
return { text: "**Cancelled by user.**", approved: false };
notifyText(
sessionId,
`\n---\n## Round ${turn} / ${groupMaxTurns}\nGroup: ${group.name}\n`,
);
const instructedTask = withPhaseInstruction(task, group);
const subPrompt = questions
? appendTextBlock(
instructedTask,
`## Open questions - address ALL of them\n${questions}`,
)
: instructedTask;
notifyText(
sessionId,
group.strategy === "single_writer"
? `Running writer agent: ${subAgents[0].name}\n`
: `Running ${subAgents.length} sub-agent(s) in parallel (concurrency cap: ${group.concurrency})...\n`,
);
// Health-probe on round 1 only; skip dead agents
let activeAgents = subAgents;
if (PROBE_TIMEOUT_MS > 0 && turn === 1 && subAgents.length > 1) {
const registerProbe = (client) => {
ctx.clients.add(client);
return () => ctx.clients.delete(client);
};
const probeSettled = await Promise.allSettled(
subAgents.map(async (cfg) => {
return semaphore.run(async () => {
const rateLimitKey = rateLimiter.keyFor(cfg);
await rateLimiter.acquire(
cfg,
(waitMs) => {
notifyText(
sessionId,
`> **${cfg.name}** — probe rate limit (${rateLimitKey}): waiting ${Math.round(waitMs / 1000)}s, ${rateLimiter.available(rateLimitKey)} tokens left\n`,
);
},
isCancelled,
);
return probeAgent(
cfg,
workDir,
(txt) => notifyText(sessionId, txt),
registerProbe,
isCancelled,
);
}, isCancelled);
}),
);
if (isCancelled())
return { text: "**Cancelled by user.**", approved: false };
activeAgents = probeSettled
.map((s, i) =>
s.status === "fulfilled" && s.value === true
? subAgents[i]
: null,
)
.filter(Boolean);
if (!activeAgents.length) {
return {
approved: false,
text: "**All agents failed the startup health probe.**",
};
}
if (activeAgents.length < subAgents.length) {
notifyText(
sessionId,
`> ${subAgents.length - activeAgents.length} agent(s) skipped (failed health probe). Running ${activeAgents.length} agent(s).\n`,
);
}
}
const settled = await Promise.allSettled(
activeAgents.map((cfg) => {
const policy = effectivePolicyForAgent(
group,
cfg,
group.strategy === "single_writer" ? "writer" : "subagent",
);
// Writers are never retried: they may have already mutated files directly on disk
// even without any observable ACP-proxied side effect.
const retryState = {
hadSideEffect: group.strategy === "single_writer",
};
return semaphore.run(
() =>
runAgentWithRetry(
cfg,
workDir,
subPrompt,
mcpServers,
(name, attempt, max, errMsg, delayMs) => {
notifyText(
sessionId,
`> **${cfg.name}** — attempt ${attempt}/${max} failed (${redact(errMsg)}). Retrying in ${Math.round(delayMs / 1000)}s...\n`,
);
},
(waitMs, rateLimitKey) => {
notifyText(
sessionId,
`> **${cfg.name}** — rate limit (${rateLimitKey}): waiting ${Math.round(waitMs / 1000)}s, ${rateLimiter.available(rateLimitKey)} tokens left\n`,
);
},
(client) => {
ctx.clients.add(client);
return () => ctx.clients.delete(client);
},
isCancelled,
(elapsedSec) => {
notifyText(
sessionId,
`> **${cfg.name}** — still working (${elapsedSec}s elapsed)\n`,
);
},
proxyChildRequest(cfg, policy, retryState),
policy,
(warning) =>
notifyText(
sessionId,
`> **${cfg.name}** — ${warning}\n`,
),
zedClientCapabilities,
retryState,
(code, line) => {
notifyText(
sessionId,
`> **${cfg.name}** — provider HTTP ${code}: ${line}\n`,
);
},
),
isCancelled,
);
}),
);
const subResults = settled.map((s, i) => {
const name = activeAgents[i].name;
if (s.status === "rejected") {
return {
name,
result: null,
usage: null,
error: redact(s.reason?.message || String(s.reason)),
fatal: !isRetryable(s.reason),
};
}
const outcome = s.value || {};
const text = redact(outcome?.text ?? outcome);
const stopReason = outcome?.stopReason || null;
return {
name,
result: text,
usage: outcome?.usage ?? null,
stopReason,
error:
stopReason && stopReason !== "end_turn"
? `Agent stopped with ${stopReason}${text ? " after partial output" : ""}`
: null,
};
});
await writeRoundReports(
workDir,
artifactDir,
runId,
group.name,
turn,
subResults,
{ sessionId, promptId },
);
if (isCancelled())