-
-
Notifications
You must be signed in to change notification settings - Fork 132
Expand file tree
/
Copy pathcoordinator.ts
More file actions
2658 lines (2448 loc) · 99.5 KB
/
Copy pathcoordinator.ts
File metadata and controls
2658 lines (2448 loc) · 99.5 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
// Main-process coordinator for managing sub-agent tasks.
// Manages task lifecycle independently of the SolidJS renderer,
// using existing backend primitives (pty, git, tasks).
import { randomUUID, randomBytes } from 'crypto';
import { execFile } from 'child_process';
import { promisify } from 'util';
import { unlinkSync, readFileSync, existsSync } from 'fs';
import {
readFile as fsReadFile,
writeFile as fsWriteFile,
unlink as fsUnlink,
access as fsAccess,
mkdir as fsMkdir,
} from 'fs/promises';
import { join, dirname } from 'path';
import os from 'os';
import { getSubTaskMcpConfigPath } from './config.js';
import { buildMcpLaunchArgs } from './agent-args.js';
import { validateBranchName } from './validation.js';
import { atomicWriteFileSync, atomicWriteFile } from './atomic.js';
import { ReplayCache } from './replay-cache.js';
import {
detectPreambleFiles,
filterDiffSections,
buildNormalizedPreambleFileDiff,
stripPreambleFromBranch,
} from './preamble.js';
const execAsync = promisify(execFile);
import type { BrowserWindow } from 'electron';
import { createTask as createBackendTask, deleteTask } from '../ipc/tasks.js';
import { getAgentByBackend, getSkipPermissionsArgs } from '../ipc/agents.js';
import { isAgentBackend } from './agent-backends.js';
import {
spawnAgent,
writeToAgent,
killAgent,
subscribeToAgent,
unsubscribeFromAgent,
getAgentScrollback,
onPtyEvent,
} from '../ipc/pty.js';
import {
getChangedFiles,
getAllFileDiffs,
getDiffBaseSha,
mergeTask as gitMergeTask,
} from '../ipc/git.js';
import {
stripAnsi,
chunkContainsAgentPrompt,
getAgentPromptReadiness,
AGENT_READY_TAIL_CHARS,
} from './prompt-detect.js';
import { SUB_TASK_PREAMBLE } from './sub-task-preamble.js';
import { info as logInfo, warn as logWarn } from '../log.js';
import type {
CoordinatedTask,
PendingNotification,
CoordinatorState,
ApiTaskSummary,
ApiTaskDetail,
ApiDiffResult,
ApiLandSelfResult,
LandSelfInput,
LandingState,
SubtaskVerification,
WaitForSignalDoneResult,
} from './types.js';
import { IPC } from '../ipc/channels.js';
const DEFAULT_WAIT_TIMEOUT_MS = 300_000; // 5 minutes
const PROMPT_WRITE_DELAY_MS = 50;
const GIT_LOCK_RETRY_DELAY_MS = 2_000;
const INITIAL_PROMPT_READY_DELAY_MS = 1_500;
const MAX_PENDING_PROMPTS = 32;
const MAX_PROMPT_BYTES = 64 * 1024;
const PROMPT_ECHO_IDLE_SUPPRESSION_MS = 2_000;
const FOCUS_IN = '\x1b[I';
const BRACKETED_PASTE_START = '\x1b[200~';
const BRACKETED_PASTE_END = '\x1b[201~';
const REST_COORDINATOR_SENTINEL = 'api';
const PREAMBLE_ARTIFACT_PATHS = new Set([
'AGENTS.md',
'GEMINI.md',
'.agent.md',
'.claude/settings.local.json',
]);
const UNRESOLVED_LANDED_COMMIT = 'unresolved';
function pasteDelayMs(text: string): number {
const lines = text.split('\n').length;
return Math.min(500, Math.max(50, lines * 15));
}
class PromptWriteError extends Error {
constructor(
message: string,
readonly phase: 'body' | 'enter',
cause: unknown,
) {
const suffix = cause instanceof Error ? `: ${cause.message}` : '';
super(`${message}${suffix}`);
this.name = 'PromptWriteError';
}
}
function isPassedVerification(verification: SubtaskVerification | undefined): boolean {
return Boolean(
verification?.checks.length && verification.checks.every((check) => check.result === 'passed'),
);
}
function verificationFailureReason(verification: SubtaskVerification | undefined): string {
if (!verification?.checks.length) return 'land_self requires at least one verification check';
const failed = verification.checks.find((check) => check.result !== 'passed');
if (!failed) return 'verification passed';
return `verification ${failed.result}: ${failed.name}${failed.reason ? ` — ${failed.reason}` : ''}`;
}
function parsePorcelainPaths(statusOut: string): string[] {
return statusOut
.split('\n')
.map((line) => line.trimEnd())
.filter(Boolean)
.map((line) => {
const renameMarker = ' -> ';
const rawPath = line.slice(3);
if (!rawPath.includes(renameMarker)) return rawPath;
const parts = rawPath.split(renameMarker);
return parts[parts.length - 1] ?? rawPath;
});
}
function execStdout(result: Awaited<ReturnType<typeof execAsync>>): string {
const stdout = typeof result === 'string' ? result : result.stdout;
return typeof stdout === 'string' ? stdout : stdout.toString('utf8');
}
/**
* The per-sub-task MCP config: a stdio launch of the parallel-code MCP server
* scoped to one task. Identical across createTask, coordinator re-registration,
* and hydration rewrite — only the resolved doneToken differs, so callers own
* token generation and pass the final value in.
*/
function buildSubtaskMcpConfig(args: {
serverPath: string;
serverUrl: string;
subtaskToken: string;
taskId: string;
doneToken: string;
}) {
return {
mcpServers: {
'parallel-code': {
type: 'stdio' as const,
command: 'node',
args: [args.serverPath, '--url', args.serverUrl, '--task-id', args.taskId],
env: {
PARALLEL_CODE_MCP_TOKEN: args.subtaskToken,
PARALLEL_CODE_MCP_DONE_TOKEN: args.doneToken,
},
},
},
};
}
export class Coordinator {
private tasks = new Map<string, CoordinatedTask>();
private tailBuffers = new Map<string, string>();
private idleResolvers = new Map<
string,
Array<(result: { reason: 'idle' | 'human_control' | 'exited' | 'removed' }) => void>
>();
private anySignalResolvers = new Map<string, Array<(result: WaitForSignalDoneResult) => void>>();
private subscribers = new Map<string, (encoded: string) => void>();
private decoders = new Map<string, TextDecoder>();
private controlMap = new Map<string, 'coordinator' | 'human'>();
private writingPromptTaskIds = new Set<string>();
private initialPromptTimers = new Map<string, ReturnType<typeof setTimeout>>();
private initialPromptReadyTasks = new Set<string>();
private promptReadySeenAt = new Map<string, number>();
private queuedPromptFlushTimers = new Map<string, ReturnType<typeof setTimeout>>();
private bracketedPasteAgentIds = new Set<string>();
private closingTaskIds = new Set<string>();
private activeSignalWaitCounts = new Map<string, number>();
private recentlyDelivered = new ReplayCache<WaitForSignalDoneResult>();
private win: BrowserWindow | null = null;
private projectRoot: string | null = null;
private projectId: string | null = null;
private defaultCoordinatorTaskId: string | null = null;
private landedOrderCounters = new Map<string, number>();
private coordinatorSpawnDefaults: { command: string; args: string[] } = {
command: 'claude',
args: [],
};
private coordinators = new Map<string, CoordinatorState>();
private notificationDelayMs = 30_000;
private readonly COORDINATOR_RESTAMP_DELAY_MS = 5 * 60_000;
private readonly MAX_ACKED_BATCH_IDS = 64;
// Serializes concurrent preamble writes to the same file path.
private preambleWriteQueue = new Map<string, Promise<void>>();
constructor() {
// Listen for PTY exits to update task status when agents are killed externally
// (e.g., user closes a child task from the UI).
// The singleton guard in enableCoordinatorMode (if (coordinator) return) ensures
// this constructor is called at most once per app lifetime; no teardown needed.
onPtyEvent('exit', (agentId, data) => {
for (const task of this.tasks.values()) {
if (task.agentId === agentId) {
const { exitCode } = (data ?? {}) as { exitCode?: number };
task.status = 'exited';
task.exitCode = exitCode ?? null;
// Resolve any idle waiters so they don't hang
const resolvers = this.idleResolvers.get(task.id);
if (resolvers?.length) {
for (const resolve of resolvers) resolve({ reason: 'exited' });
this.idleResolvers.delete(task.id);
}
if (this.closingTaskIds.has(task.id)) break;
// Resolve any signal waiters so wait_for_signal_done doesn't hang
// when the last sub-task exits without calling signal_done.
const coordinatorId = task.coordinatorTaskId;
const anyResolvers = this.anySignalResolvers.get(coordinatorId);
const firstAnyResolver = anyResolvers?.length ? anyResolvers.shift() : undefined;
if (firstAnyResolver) {
// Suppress the exit notification — the signal waiter receives the
// exit info as its return value (mirrors the signalDone path).
this.suppressPendingNotificationForTask(task);
task.reviewNotificationQueued = true;
const remaining = this.countRemaining(coordinatorId);
// The resolver IS `complete` from waitForSignalDone — it handles
// finishSignalWait, replay-cache write, and timer cleanup itself.
firstAnyResolver({
taskId: task.id,
name: task.name,
status: 'exited',
signalDoneAt: new Date().toISOString(),
remaining,
});
}
this.maybeQueueReviewNotification(task, 'exited', exitCode ?? null);
break;
}
}
});
// Re-subscribe our output callback when the renderer reattaches to, or explicitly
// replaces, a managed agent. Without this, our outputCb is lost and we can never
// detect idle for that sub-task.
onPtyEvent('spawn', (agentId) => {
const outputCb = this.subscribers.get(agentId);
if (!outputCb) return; // not a coordinated agent, or initial spawn (not yet subscribed)
this.tailBuffers.set(agentId, ''); // replaced PTYs should not inherit old prompt text
for (const task of this.tasks.values()) {
if (task.agentId === agentId && task.status === 'exited') {
task.status = 'running';
task.exitCode = null;
}
if (task.agentId === agentId) {
this.updateTailFromScrollback(task);
}
}
subscribeToAgent(agentId, outputCb);
});
}
setTaskControl(taskId: string, who: 'coordinator' | 'human'): void {
const task = this.tasks.get(taskId);
if (!task) {
throw new Error(`Task not found: ${taskId}`);
}
if (who === 'human' && task.initialPrompt && !task.assignedPromptDelivered) {
logInfo('coordinator.control', 'ignored human hold before initial prompt delivery', {
taskId,
});
return;
}
this.controlMap.set(taskId, who);
if (who === 'human') {
// Resolve any pending idle waiters immediately — human has taken over
const resolvers = this.idleResolvers.get(taskId);
if (resolvers?.length) {
for (const resolve of resolvers) resolve({ reason: 'human_control' });
this.idleResolvers.delete(taskId);
}
}
if (who === 'coordinator') {
const hasQueuedWork = Boolean(
task?.initialPrompt || (task?.pendingPrompts && task.pendingPrompts.length > 0),
);
// Fire any idle resolvers queued while human had control
const resolvers = this.idleResolvers.get(taskId);
if (!hasQueuedWork && resolvers?.length) {
for (const resolve of resolvers) resolve({ reason: 'idle' });
this.idleResolvers.delete(taskId);
}
if (task?.initialPrompt) {
this.clearInitialPromptTimer(task.id);
this.scheduleInitialPromptDelivery(task, 0);
} else if (task?.pendingPrompts?.length) {
void this.flushNextQueuedPrompt(task);
}
}
}
private normalizedTail(agentId: string): string {
const tail = (this.tailBuffers.get(agentId) ?? '').slice(-AGENT_READY_TAIL_CHARS * 2);
return (
stripAnsi(tail)
// eslint-disable-next-line no-control-regex -- preserve line breaks for anchored prompt detection.
.replace(/[\x00-\x09\x0b-\x0c\x0e-\x1f\x7f]/g, ' ')
.replace(/[ \t]+/g, ' ')
.trim()
);
}
private tailHasAgentPrompt(task: CoordinatedTask): boolean {
return chunkContainsAgentPrompt(this.normalizedTail(task.agentId));
}
private updateBracketedPasteMode(agentId: string, text: string): void {
// eslint-disable-next-line no-control-regex -- PTYs report bracketed paste mode with CSI ? 2004 h/l.
const re = /\x1b\[\?2004([hl])/g;
let match: RegExpExecArray | null;
while ((match = re.exec(text)) !== null) {
if (match[1] === 'h') this.bracketedPasteAgentIds.add(agentId);
else this.bracketedPasteAgentIds.delete(agentId);
}
}
private updateTailFromScrollback(task: CoordinatedTask): boolean {
const scrollback = getAgentScrollback(task.agentId);
if (!scrollback) return false;
const decoded = Buffer.from(scrollback, 'base64').toString('utf8');
this.updateBracketedPasteMode(task.agentId, decoded);
this.tailBuffers.set(
task.agentId,
decoded.length > 4096 ? decoded.slice(decoded.length - 4096) : decoded,
);
const hasAgentPrompt = this.tailHasAgentPrompt(task);
if (hasAgentPrompt) {
this.scheduleInitialPromptDelivery(task, INITIAL_PROMPT_READY_DELAY_MS, true);
task.status = 'idle';
this.maybeQueueReviewNotification(task, 'idle', null);
}
return hasAgentPrompt;
}
private markAgentPromptReady(task: CoordinatedTask, hasAgentPrompt: boolean): boolean {
if (!hasAgentPrompt) {
this.promptReadySeenAt.delete(task.id);
return false;
}
const now = Date.now();
const firstSeenAt = this.promptReadySeenAt.get(task.id);
if (firstSeenAt === undefined) {
this.promptReadySeenAt.set(task.id, now);
return false;
}
return now - firstSeenAt >= PROMPT_WRITE_DELAY_MS;
}
private scheduleQueuedPromptFlush(task: CoordinatedTask): void {
if (!task.pendingPrompts?.length || this.queuedPromptFlushTimers.has(task.id)) return;
const timer = setTimeout(() => {
this.queuedPromptFlushTimers.delete(task.id);
if (!this.tasks.has(task.id)) return;
if (this.controlMap.get(task.id) === 'human') return;
if (!task.pendingPrompts?.length) return;
if (!this.tailHasAgentPrompt(task)) return;
if (this.writingPromptTaskIds.has(task.id)) {
this.scheduleQueuedPromptFlush(task);
return;
}
void this.flushNextQueuedPrompt(task);
}, PROMPT_WRITE_DELAY_MS);
if (typeof timer === 'object' && 'unref' in timer) timer.unref();
this.queuedPromptFlushTimers.set(task.id, timer);
}
private clearQueuedPromptFlushTimer(taskId: string): void {
const timer = this.queuedPromptFlushTimers.get(taskId);
if (!timer) return;
clearTimeout(timer);
this.queuedPromptFlushTimers.delete(taskId);
}
private suppressPromptEchoIdleNotification(task: CoordinatedTask): void {
task.suppressIdleUntil = Date.now() + PROMPT_ECHO_IDLE_SUPPRESSION_MS;
}
private isPromptEchoOutput(task: CoordinatedTask, text: string): boolean {
const prompt = task.lastPromptEchoText;
if (!prompt) return false;
const normalized = stripAnsi(text)
// eslint-disable-next-line no-control-regex -- compare printable prompt echo text only.
.replace(/[\x00-\x1f\x7f]/g, ' ')
.replace(/\s+/g, ' ')
.trim();
return Boolean(
normalized &&
(prompt.includes(normalized) ||
(normalized.startsWith('[SUB-TASK MODE]') && prompt.startsWith('[SUB-TASK MODE]'))),
);
}
private suppressPromptEchoIdleIfNeeded(task: CoordinatedTask): boolean {
if (!task.assignedPromptDelivered || task.suppressIdleUntil === undefined) return false;
if (Date.now() < task.suppressIdleUntil) {
task.suppressIdleUntil = undefined;
task.lastPromptEchoText = undefined;
this.tailBuffers.set(task.agentId, '');
return true;
}
task.suppressIdleUntil = undefined;
task.lastPromptEchoText = undefined;
return false;
}
private clearInitialPromptTimer(taskId: string): void {
const timer = this.initialPromptTimers.get(taskId);
if (!timer) return;
clearTimeout(timer);
this.initialPromptTimers.delete(taskId);
}
private clearInitialPromptDeliveryState(taskId: string): void {
this.clearInitialPromptTimer(taskId);
this.initialPromptReadyTasks.delete(taskId);
}
private clearPromptDeliveryState(taskId: string): void {
this.clearInitialPromptDeliveryState(taskId);
this.clearQueuedPromptFlushTimer(taskId);
this.promptReadySeenAt.delete(taskId);
this.writingPromptTaskIds.delete(taskId);
}
private scheduleInitialPromptDelivery(
task: CoordinatedTask,
delayMs = INITIAL_PROMPT_READY_DELAY_MS,
promptReady = false,
): void {
if (promptReady) this.initialPromptReadyTasks.add(task.id);
if (!task.initialPrompt || task.assignedPromptDelivered) return;
if (this.initialPromptTimers.has(task.id)) return;
const timer = setTimeout(() => {
this.initialPromptTimers.delete(task.id);
void this.tryDeliverInitialPrompt(task.id);
}, delayMs);
if (typeof timer === 'object' && 'unref' in timer) timer.unref();
this.initialPromptTimers.set(task.id, timer);
logInfo('coordinator.initial_prompt', 'scheduled', {
taskId: task.id,
agentId: task.agentId,
delayMs,
});
}
private buildAgentOutputCb(task: CoordinatedTask): (encoded: string) => void {
return (encoded: string) => {
const bytes = Buffer.from(encoded, 'base64');
const text = (this.decoders.get(task.agentId) ?? new TextDecoder()).decode(bytes, {
stream: true,
});
this.updateBracketedPasteMode(task.agentId, text);
const prev = this.tailBuffers.get(task.agentId) ?? '';
const combined = prev + text;
this.tailBuffers.set(
task.agentId,
combined.length > 4096 ? combined.slice(combined.length - 4096) : combined,
);
const hasAgentPrompt = this.tailHasAgentPrompt(task);
const stableAgentPrompt = this.markAgentPromptReady(task, hasAgentPrompt);
if (!hasAgentPrompt && task.assignedPromptDelivered) {
if (task.suppressIdleUntil !== undefined && !this.isPromptEchoOutput(task, text)) {
task.suppressIdleUntil = undefined;
task.lastPromptEchoText = undefined;
}
}
if (hasAgentPrompt) {
this.scheduleInitialPromptDelivery(task, INITIAL_PROMPT_READY_DELAY_MS, true);
if (
!task.initialPrompt &&
task.assignedPromptDelivered &&
this.controlMap.get(task.id) !== 'human' &&
task.pendingPrompts?.length
) {
if (stableAgentPrompt && !this.writingPromptTaskIds.has(task.id)) {
void this.flushNextQueuedPrompt(task);
} else {
this.scheduleQueuedPromptFlush(task);
}
return;
}
if (task.suppressIdleUntil !== undefined && this.suppressPromptEchoIdleIfNeeded(task)) {
return;
}
if (task.status === 'running') {
task.status = 'idle';
this.maybeQueueReviewNotification(task, 'idle', null);
}
const resolvers = this.idleResolvers.get(task.id);
if (resolvers?.length) {
for (const resolve of resolvers) resolve({ reason: 'idle' });
this.idleResolvers.delete(task.id);
}
} else if (task.status === 'idle') {
task.status = 'running';
this.suppressPendingNotificationForTask(task);
}
};
}
private async tryDeliverInitialPrompt(taskId: string): Promise<void> {
const task = this.tasks.get(taskId);
if (!task?.initialPrompt || task.assignedPromptDelivered) return;
if (task.status === 'exited' || task.status === 'error') return;
const readiness = getAgentPromptReadiness(this.normalizedTail(task.agentId));
const promptReady = this.initialPromptReadyTasks.has(taskId) || readiness.ready;
if (!promptReady) {
logInfo('coordinator.initial_prompt', 'waiting_for_prompt', {
taskId: task.id,
agentId: task.agentId,
reason: readiness.reason,
pendingPromptCount: task.pendingPrompts?.length ?? 0,
tailSample: readiness.tail.slice(-300),
});
this.scheduleInitialPromptDelivery(task, INITIAL_PROMPT_READY_DELAY_MS);
return;
}
if (this.controlMap.get(task.id) === 'human') {
this.scheduleInitialPromptDelivery(task, INITIAL_PROMPT_READY_DELAY_MS, promptReady);
return;
}
if (this.writingPromptTaskIds.has(task.id)) return;
const prompt = task.initialPrompt;
task.initialPrompt = undefined;
this.writingPromptTaskIds.add(task.id);
try {
await this.writePromptToTask(task, prompt);
this.markPromptDelivered(task.id);
logInfo('coordinator.initial_prompt', 'delivered', {
taskId: task.id,
agentId: task.agentId,
});
this.notifyRenderer(IPC.MCP_TaskStateSync, {
taskId: task.id,
initialPrompt: null,
});
} catch (err) {
if (err instanceof PromptWriteError && err.phase === 'enter') {
logWarn(
'coordinator.initial_prompt',
'initial prompt body was written but Enter failed; not retrying body',
{
taskId: task.id,
err: err.message,
},
);
this.notifyRenderer(IPC.MCP_TaskStateSync, {
taskId: task.id,
initialPrompt: null,
});
return;
}
if (this.tasks.has(task.id)) {
task.initialPrompt = prompt;
this.scheduleInitialPromptDelivery(task, INITIAL_PROMPT_READY_DELAY_MS, promptReady);
}
} finally {
this.writingPromptTaskIds.delete(task.id);
}
}
setWindow(win: BrowserWindow): void {
this.win = win;
}
setNotificationDelayMs(ms: number): void {
this.notificationDelayMs = Math.max(5_000, Math.min(300_000, ms));
}
setDefaultProject(projectId: string, projectRoot: string, coordinatorTaskId?: string): void {
this.projectId = projectId;
this.projectRoot = projectRoot;
if (coordinatorTaskId) this.defaultCoordinatorTaskId = coordinatorTaskId;
}
setMCPServerInfo(
coordinatorTaskId: string,
serverUrl: string,
token: string,
subtaskToken: string,
serverPath: string,
): void {
const state = this.coordinators.get(coordinatorTaskId);
if (state) {
state.mcpServerInfo = { serverUrl, token, subtaskToken, serverPath };
state.lifecycle = 'ready';
}
// Rewrite config files only for sub-tasks owned by this coordinator so a
// second coordinator starting up does not overwrite the first's task configs.
for (const task of this.tasks.values()) {
if (task.coordinatorTaskId !== coordinatorTaskId) continue;
if (!task.mcpConfigPath) continue;
// Preserve existing doneToken; generate a fresh one if not yet set (e.g. older persisted task).
if (!task.doneToken) task.doneToken = randomBytes(24).toString('base64url');
const mcpConfig = buildSubtaskMcpConfig({
serverPath,
serverUrl,
subtaskToken,
taskId: task.id,
doneToken: task.doneToken,
});
atomicWriteFileSync(task.mcpConfigPath, JSON.stringify(mcpConfig, null, 2), { mode: 0o600 });
}
}
setCoordinatorSpawnDefaults(coordinatorTaskId: string, command: string, args: string[]): void {
const state = this.coordinators.get(coordinatorTaskId);
if (state) {
state.spawnDefaults = { command, args };
}
// Also update global fallback.
this.coordinatorSpawnDefaults = { command, args };
}
setDockerContainerName(coordinatorTaskId: string, name: string | null): void {
const state = this.coordinators.get(coordinatorTaskId);
if (state) {
state.dockerContainerName = name;
}
}
setDockerImage(coordinatorTaskId: string, image: string | null): void {
const state = this.coordinators.get(coordinatorTaskId);
if (state) {
state.dockerImage = image;
}
}
private maybeQueueReviewNotification(
task: CoordinatedTask,
state: 'idle' | 'exited',
exitCode: number | null,
delayOverrideMs?: number,
): void {
// Always notify for exits — a task killed before prompt delivery still needs to be
// reported so the coordinator doesn't think it's still running.
if (!task.assignedPromptDelivered && state !== 'exited') return;
if (state === 'idle' && task.suppressIdleUntil !== undefined) {
if (this.suppressPromptEchoIdleIfNeeded(task)) return;
}
const coordinator = this.coordinators.get(task.coordinatorTaskId);
if (!coordinator) {
if (task.reviewNotificationQueued) return;
task.reviewNotificationQueued = true;
this.notifyRenderer(IPC.MCP_CoordinatorOrphanedNotification, {
subTaskId: task.id,
notificationId: randomUUID(),
state,
text: `"${task.name}" ${state === 'exited' ? `terminated (exit ${exitCode})` : 'ready for review'} — branch: ${task.branchName}`,
});
return;
}
if (task.reviewNotificationQueued && state === 'exited') {
const existing = coordinator.pendingNotifications.find((n) => n.taskId === task.id);
if (existing && existing.state === 'idle') {
existing.state = 'exited';
existing.exitCode = exitCode;
this.stageBatch(coordinator);
return;
}
return;
}
if (task.reviewNotificationQueued) return;
task.reviewNotificationQueued = true;
const notification: PendingNotification = {
id: randomUUID(),
taskId: task.id,
taskName: task.name,
branchName: task.branchName,
state,
exitCode,
completedAt: new Date(),
};
coordinator.pendingNotifications.push(notification);
this.stageBatch(coordinator, delayOverrideMs);
}
private stageBatch(coordinator: CoordinatorState, delayOverrideMs?: number): void {
const pending = coordinator.pendingNotifications;
if (pending.length === 0) return;
if (this.hasActiveSignalWaiter(coordinator.taskId)) {
logWarn('coordinator.notification', 'stageBatch skipped', {
coordinatorTaskId: coordinator.taskId,
reason: 'active_signal_wait',
activeWaitCount: this.activeSignalWaitCounts.get(coordinator.taskId) ?? 0,
pendingTaskIds: this.pendingNotificationTaskIds(coordinator),
});
if (coordinator.restageTimer) {
clearTimeout(coordinator.restageTimer);
coordinator.restageTimer = null;
}
return;
}
// Clear any previously staged batches — they are superseded by this new batch.
// Leaving old entries causes stagedBatches to grow unboundedly and makes
// deregisterCoordinator incorrectly believe notifications are still pending.
coordinator.stagedBatches.clear();
const batchId = randomUUID();
const notificationIds = pending.map((n) => n.id);
coordinator.stagedBatches.set(batchId, notificationIds);
const anyNonZero = pending.some((n) => n.exitCode !== null && n.exitCode !== 0);
const defaultDelay = anyNonZero
? Math.max(10_000, this.notificationDelayMs / 4)
: this.notificationDelayMs;
const delay = delayOverrideMs ?? defaultDelay;
const autoFireAt = Date.now() + delay;
const text = this.formatNotificationText(pending);
logWarn('coordinator.notification', 'stageBatch emitted', {
coordinatorTaskId: coordinator.taskId,
batchId,
notificationIds,
pendingTaskIds: this.pendingNotificationTaskIds(coordinator),
delayMs: delay,
autoFireAt,
});
this.notifyRenderer(IPC.MCP_CoordinatorNotificationStaged, {
coordinatorTaskId: coordinator.taskId,
batchId,
notificationIds,
text,
autoFireAt,
});
if (coordinator.restageTimer) clearTimeout(coordinator.restageTimer);
coordinator.restageTimer = setTimeout(() => {
coordinator.restageTimer = null;
if (coordinator.pendingNotifications.length > 0) {
this.stageBatch(coordinator);
}
}, this.COORDINATOR_RESTAMP_DELAY_MS);
}
private formatNotificationText(pending: PendingNotification[]): string {
const header = `[Sub-task update — ${pending.length} task(s) completed]`;
const lines = pending.map((n) => {
const status =
n.state === 'landed'
? 'self-landed successfully'
: n.state === 'exited'
? `terminated (exit ${n.exitCode})`
: 'ready for review';
const line = `- "${n.taskName}" ${status} — branch: ${n.branchName}`;
const warn =
n.state !== 'landed' && n.exitCode !== null && n.exitCode !== 0
? '\n ⚠️ Non-zero exit — may need attention. Consider spawning a follow-up agent.'
: '';
return line + warn;
});
const allLanded = pending.every((n) => n.state === 'landed');
const footer = allLanded
? 'Sub-tasks have merged their branches and cleaned up. If there are items remaining on the backlog, spawn the next batch.'
: "Please review each completed task: check its diff, confirm the work looks correct, then commit and merge what's ready. If there are items remaining on the backlog, spawn the next batch.";
return [header, '', ...lines, '', footer].join('\n');
}
async createTask(opts: {
name: string;
prompt?: string;
coordinatorTaskId: string;
projectId?: string;
projectRoot?: string;
agentCommand?: string;
agentArgs?: string[];
skipPermissions?: boolean;
baseBranch?: string;
backend?: string;
}): Promise<CoordinatedTask> {
const coordinatorId =
opts.coordinatorTaskId !== REST_COORDINATOR_SENTINEL
? opts.coordinatorTaskId
: this.defaultCoordinatorTaskId;
if (!coordinatorId) {
throw new Error(
'No coordinator task registered yet. Ensure the coordinator task is fully initialized before calling create_task.',
);
}
const coordinatorState = this.coordinators.get(coordinatorId);
if (!coordinatorState) {
throw new Error(
`Unknown coordinator: ${coordinatorId}. Ensure the coordinator task is registered before creating sub-tasks.`,
);
}
const root = opts.projectRoot ?? coordinatorState.projectRoot ?? this.projectRoot;
const projId = opts.projectId ?? coordinatorState.projectId ?? this.projectId;
if (!root || !projId) throw new Error('No project configured for coordinator');
const coordinatorBranch = coordinatorState.branchName?.trim()
? coordinatorState.branchName
: undefined;
const baseBranch = opts.baseBranch ?? coordinatorBranch;
if (baseBranch !== undefined) {
validateBranchName(baseBranch, 'baseBranch');
}
const backend = opts.backend;
if (backend && !isAgentBackend(backend)) {
throw new Error(`Unsupported agent backend: ${backend}`);
}
const requestedAgent =
backend && isAgentBackend(backend) ? getAgentByBackend(backend) : undefined;
const selectedAgentCommand =
requestedAgent?.command ?? opts.agentCommand ?? coordinatorState.spawnDefaults.command;
const selectedAgentArgs =
requestedAgent?.args ?? opts.agentArgs ?? coordinatorState.spawnDefaults.args;
// Create worktree + branch via existing backend
const result = await createBackendTask(
opts.name,
root,
['.claude', 'node_modules'],
'task',
baseBranch,
);
// Re-check after async gap — deregisterCoordinator may have run while we awaited.
if (!this.coordinators.has(coordinatorId)) {
// Best-effort cleanup of the worktree we just created.
deleteTask({
agentIds: [],
branchName: result.branch_name,
deleteBranch: true,
projectRoot: root,
}).catch((err) => {
console.warn('Failed to clean up race-condition worktree:', err);
this.notifyRenderer(IPC.MCP_TaskCleanupFailed, {
taskId: result.id,
error: err instanceof Error ? err.message : String(err),
});
});
throw new Error(`Coordinator ${coordinatorId} was deregistered during task creation`);
}
const agentId = randomUUID();
const task: CoordinatedTask = {
id: result.id,
name: opts.name,
projectId: projId,
projectRoot: root,
branchName: result.branch_name,
baseBranch,
worktreePath: result.worktree_path,
agentId,
coordinatorTaskId: coordinatorId,
status: 'creating',
exitCode: null,
initialPrompt: opts.prompt ? SUB_TASK_PREAMBLE + opts.prompt : undefined,
dockerContainerName: this.coordinators.get(coordinatorId)?.dockerContainerName ?? null,
};
this.tasks.set(task.id, task);
this.tailBuffers.set(agentId, '');
// Subscribe to PTY output for prompt detection
const decoder = new TextDecoder();
this.decoders.set(agentId, decoder);
const outputCb = this.buildAgentOutputCb(task);
this.subscribers.set(agentId, outputCb);
// Spawn the agent process
if (!this.win) throw new Error('No window set on coordinator');
const agentCmd = selectedAgentCommand.toLowerCase();
const preamble = `<sub-task-mode>\nThese rules override all skills and hooks:\n- When your work is complete, commit your changes and call the \`land_self\` MCP tool with the verification checks you ran. A successful \`land_self\` call is the finish line — do NOT call \`signal_done\` afterward, use finishing-a-development-branch, or offer merge/PR options.\n- Use \`signal_done\` only if the coordinator explicitly asks for manual review instead of self-landing.\n- Asking questions is fine when requirements are unclear or an action is risky.\n</sub-task-mode>`;
// Declared here so the catch block can restore preamble files on failure.
let preambleFilePath: string | undefined;
let preambleFileOriginalContent: string | null = null;
const dockerContainerName =
this.coordinators.get(task.coordinatorTaskId)?.dockerContainerName ?? null;
let subTaskMcpConfigPath: string | undefined;
try {
// Inject sub-task instructions via agent-specific mechanism.
// Inside try so preamble-write failures are cleaned up by the catch block.
// Serialized per file path to prevent races when multiple tasks target the same path.
const injectPreamble = async (filePath: string): Promise<void> => {
const prior = this.preambleWriteQueue.get(filePath) ?? Promise.resolve();
const next = prior.then(async () => {
let existing = '';
try {
await fsAccess(filePath);
existing = await fsReadFile(filePath, 'utf8');
preambleFileOriginalContent = existing;
} catch {
/* file does not exist */
}
await atomicWriteFile(filePath, existing ? `${existing}\n\n${preamble}` : preamble);
});
this.preambleWriteQueue.set(
filePath,
next
.catch(() => {})
.then(() => {
if (this.preambleWriteQueue.get(filePath) === next) {
this.preambleWriteQueue.delete(filePath);
}
}),
);
await next;
};
if (agentCmd.includes('codex') || agentCmd.includes('opencode')) {
const agentsPath = join(result.worktree_path, 'AGENTS.md');
preambleFilePath = agentsPath;
await injectPreamble(agentsPath);
} else if (agentCmd.includes('gemini')) {
const geminiPath = join(result.worktree_path, 'GEMINI.md');
preambleFilePath = geminiPath;
await injectPreamble(geminiPath);
} else if (agentCmd.includes('copilot')) {
const agentMdPath = join(result.worktree_path, '.agent.md');
preambleFilePath = agentMdPath;
await injectPreamble(agentMdPath);
} else {
// Claude and fallback: settings.local.json (gitignored, no restore needed)
const settingsDir = join(result.worktree_path, '.claude');
const settingsPath = join(settingsDir, 'settings.local.json');
await fsMkdir(settingsDir, { recursive: true });
const prior = this.preambleWriteQueue.get(settingsPath) ?? Promise.resolve();
const next = prior.then(async () => {
let existingSettings: Record<string, unknown> = {};
try {
await fsAccess(settingsPath);
existingSettings = JSON.parse(await fsReadFile(settingsPath, 'utf8'));
} catch {
/* ignore */
}
existingSettings.systemPrompt = existingSettings.systemPrompt
? `${existingSettings.systemPrompt}\n\n${preamble}`
: preamble;
await atomicWriteFile(settingsPath, JSON.stringify(existingSettings, null, 2));
});
this.preambleWriteQueue.set(
settingsPath,
next
.catch(() => {})
.then(() => {
if (this.preambleWriteQueue.get(settingsPath) === next) {
this.preambleWriteQueue.delete(settingsPath);
}
}),
);
await next;
}
task.preambleFileExistedBefore = preambleFileOriginalContent !== null;
// Write a per-sub-task MCP config so the agent can call signal_done.
// In Docker mode, write to the coordinator's .parallel-code/ dir (which IS the explicitly
// mounted volume) rather than the sub-task worktree (which may not be in the container).
// Always pass explicit MCP launch args so agents don't rely on auto-discovery.
const mcpServerInfoForTask = coordinatorState.mcpServerInfo;
let subTaskMcpConfig: Parameters<typeof buildMcpLaunchArgs>[2] | undefined;
if (mcpServerInfoForTask) {
const { serverUrl, subtaskToken, serverPath } = mcpServerInfoForTask;
const doneToken = randomBytes(24).toString('base64url');
task.doneToken = doneToken;
const mcpConfig = buildSubtaskMcpConfig({
serverPath,
serverUrl,
subtaskToken,
taskId: task.id,
doneToken,
});
subTaskMcpConfig = mcpConfig;
const configPath = getSubTaskMcpConfigPath(dockerContainerName, serverPath, task.id);
await atomicWriteFile(configPath, JSON.stringify(mcpConfig, null, 2), { mode: 0o600 });
subTaskMcpConfigPath = configPath;
task.mcpConfigPath = configPath;
}