@saturn-universe/runtime 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,936 @@
1
+ import { BACKGROUND_CONTEXT_PREFIX, coordinatorPollIntervalMs, earlierDeadline, isAsyncCoordinatorConfig, isTeamNotifyMessageId, isTerminalRunStatus, maxRunTeamWorkers, resolveEffectiveTeamConcurrency, RuntimeError, teamRootId, validateStartedRun, validateTeamConfig, } from '@saturn-universe/core';
2
+ export async function driveTeam(d, scope, parentSignal, wake) {
3
+ const { runId } = scope;
4
+ const stop = new AbortController();
5
+ const signal = AbortSignal.any([parentSignal, stop.signal]);
6
+ const inFlight = new Map();
7
+ const settled = new Set();
8
+ const completedWorkers = new Set();
9
+ const workerStartedAt = new Map();
10
+ const workerWorkSubpaths = new Map();
11
+ const processedMainSpawnTurns = new Set();
12
+ let lastMainActivityAt = Date.now();
13
+ let watchdogTimer;
14
+ let driverError;
15
+ const finishWorker = async (member, status) => {
16
+ if (!member.parent || completedWorkers.has(member.id))
17
+ return;
18
+ completedWorkers.add(member.id);
19
+ let workSubpath = workerWorkSubpaths.get(member.id);
20
+ if (workSubpath === undefined && !workerWorkSubpaths.has(member.id)) {
21
+ const env = await d.environment.load(runId, member.agentSessionId).catch(() => undefined);
22
+ workSubpath = env?.config.team?.members.find((m) => m.id === member.id)?.workSubpath;
23
+ }
24
+ await d.onWorkerComplete?.({
25
+ runId,
26
+ memberId: member.id,
27
+ agentSessionId: member.agentSessionId,
28
+ parentMemberId: member.parent,
29
+ ...(workSubpath !== undefined ? { workSubpath } : {}),
30
+ status,
31
+ });
32
+ };
33
+ let notifyCompletion = () => { };
34
+ let notifyWake = () => { };
35
+ const onWake = () => notifyWake();
36
+ wake.target.addEventListener('wake', onWake);
37
+ signal.addEventListener('abort', onWake);
38
+ const readTeam = async () => {
39
+ const team = await d.state.team?.(runId);
40
+ if (!team)
41
+ throw new RuntimeError('INVALID_RUN_STATE', 'Team roster missing');
42
+ return team;
43
+ };
44
+ const routeFor = async (member) => (await d.environment.load(runId, member.agentSessionId)).route;
45
+ const runMember = async (member, route, turn, activeSignal, teamMembers) => {
46
+ if (member.parent && !activeSignal.aborted) {
47
+ const env = await d.environment.load(runId, member.agentSessionId);
48
+ const memberCfg = env.config.team?.members.find((m) => m.id === member.id);
49
+ workerWorkSubpaths.set(member.id, memberCfg?.workSubpath);
50
+ const parentMember = teamMembers?.find((m) => m.id === member.parent);
51
+ try {
52
+ await d.onWorkerStart?.({
53
+ runId,
54
+ memberId: member.id,
55
+ agentSessionId: member.agentSessionId,
56
+ parentMemberId: member.parent,
57
+ ...(parentMember && parentMember.parent !== null
58
+ ? { parentAgentSessionId: parentMember.agentSessionId }
59
+ : {}),
60
+ ...(memberCfg?.sandboxProfile !== undefined ? { sandboxProfile: memberCfg.sandboxProfile } : {}),
61
+ ...(memberCfg?.workSubpath !== undefined ? { workSubpath: memberCfg.workSubpath } : {}),
62
+ });
63
+ }
64
+ catch (error) {
65
+ if (activeSignal.aborted)
66
+ throw error;
67
+ const failure = {
68
+ code: error instanceof RuntimeError ? error.code : 'WORKER_START_FAILED',
69
+ message: error instanceof Error ? error.message : 'Worker startup failed',
70
+ retryable: false,
71
+ };
72
+ const runState = await d.state.run(runId);
73
+ await d.journal.append(`turn:${turn.id}:start-failed`, [
74
+ d.journal.event('turn.failed', route, {
75
+ turnId: turn.id,
76
+ error: failure,
77
+ usage: runState.chargedUsage,
78
+ }),
79
+ ]);
80
+ await finishWorker(member, 'failed').catch(() => { });
81
+ return {
82
+ status: 'failed',
83
+ turnId: turn.id,
84
+ error: failure,
85
+ usage: runState.chargedUsage,
86
+ };
87
+ }
88
+ }
89
+ const input = { ...route, turnId: turn.id, inputMessageId: turn.inputMessageId };
90
+ return d.agent.resume(input, activeSignal);
91
+ };
92
+ const cleanup = async (stopSignal) => {
93
+ await Promise.all(inFlight.values());
94
+ const team = await readTeam().catch(() => undefined);
95
+ const turns = await d.state.turns(runId);
96
+ const results = await finishTurns(turns
97
+ .filter((turn) => ['queued', 'running', 'paused'].includes(turn.status))
98
+ .map(async (turn) => {
99
+ const env = await d.environment.load(runId, turn.agentSessionId);
100
+ const member = team?.members.find((m) => m.agentSessionId === turn.agentSessionId);
101
+ if (member) {
102
+ return runMember(member, env.route, turn, stopSignal, team?.members);
103
+ }
104
+ return d.agent.resume({ ...env.route, turnId: turn.id, inputMessageId: turn.inputMessageId }, stopSignal);
105
+ }));
106
+ if (team) {
107
+ for (const member of team.members) {
108
+ if (member.parent)
109
+ await finishWorker(member, 'interrupted');
110
+ }
111
+ }
112
+ return results;
113
+ };
114
+ try {
115
+ return await schedule();
116
+ }
117
+ finally {
118
+ clearTimeout(watchdogTimer);
119
+ watchdogTimer = undefined;
120
+ wake.target.removeEventListener('wake', onWake);
121
+ signal.removeEventListener('abort', onWake);
122
+ for (const reply of wake.waiters)
123
+ reply();
124
+ wake.waiters.clear();
125
+ stop.abort();
126
+ await Promise.all(inFlight.values());
127
+ if (driverError) {
128
+ const latest = await readTeam().catch(() => undefined);
129
+ if (latest) {
130
+ for (const member of latest.members) {
131
+ if (member.parent)
132
+ await finishWorker(member, 'interrupted').catch(() => { });
133
+ }
134
+ }
135
+ }
136
+ }
137
+ async function schedule() {
138
+ scheduling: while (true) {
139
+ const wakeRequests = [...wake.waiters];
140
+ const acknowledgeWake = () => {
141
+ for (const reply of wakeRequests) {
142
+ wake.waiters.delete(reply);
143
+ reply();
144
+ }
145
+ };
146
+ for (const id of settled)
147
+ inFlight.delete(id);
148
+ settled.clear();
149
+ const completion = new Promise((resolve) => {
150
+ notifyCompletion = resolve;
151
+ });
152
+ const external = new Promise((resolve) => {
153
+ notifyWake = resolve;
154
+ });
155
+ const run = await d.state.run(runId);
156
+ if (isTerminalRunStatus(run.status))
157
+ return;
158
+ if (run.status === 'cancelling' || signal.aborted) {
159
+ const [interruption] = await cleanup(AbortSignal.abort());
160
+ return (interruption ?? {
161
+ status: 'interrupted',
162
+ turnId: (await d.state.turns(runId))[0].id,
163
+ reason: 'cancelled',
164
+ unresolvedCallIds: run.unresolvedCallIds,
165
+ usage: run.chargedUsage,
166
+ });
167
+ }
168
+ if (driverError)
169
+ throw driverError.cause;
170
+ const mainEnv = await d.environment.load(runId);
171
+ const startedRun = validateStartedRun(run, mainEnv.config.limits);
172
+ const expired = Boolean(startedRun.deadlineAt && Date.parse(d.now()) >= Date.parse(startedRun.deadlineAt));
173
+ if (expired) {
174
+ const turns = await d.state.turns(runId);
175
+ const results = await cleanup(signal);
176
+ return (results.find((result) => result.status === 'interrupted') ?? {
177
+ status: 'interrupted',
178
+ turnId: turns[0].id,
179
+ reason: 'timeout',
180
+ unresolvedCallIds: run.unresolvedCallIds,
181
+ usage: run.chargedUsage,
182
+ });
183
+ }
184
+ const team = await readTeam();
185
+ const asyncCoordinator = isAsyncCoordinatorConfig(mainEnv.config);
186
+ const main = team.members.find((member) => member.id === teamRootId);
187
+ for (const member of team.members) {
188
+ if (member.parent !== null && member.status === 'running' && !workerStartedAt.has(member.id)) {
189
+ workerStartedAt.set(member.id, Date.now());
190
+ }
191
+ }
192
+ const degraded = new Map();
193
+ for (const member of team.members) {
194
+ if (member.status !== 'failed' && member.status !== 'interrupted')
195
+ continue;
196
+ const result = await d.state.turnResult(member.turnId);
197
+ if (result?.status !== 'failed' && result?.status !== 'interrupted')
198
+ throw new RuntimeError('INVALID_RUN_STATE', 'Team Turn result missing');
199
+ if (member.parent !== null &&
200
+ (result.status === 'interrupted'
201
+ ? (result.reason === 'timeout' || result.reason === 'limit') &&
202
+ result.unresolvedCallIds.length === 0
203
+ : !result.error.budget &&
204
+ !['LIMIT', 'RUN_BUDGET_EXCEEDED'].includes(result.error.code) &&
205
+ !(await d.state.pendingTools(result.turnId)).some(({ status }) => status === 'outcome_unknown'))) {
206
+ degraded.set(member.id, result);
207
+ continue;
208
+ }
209
+ stop.abort();
210
+ await cleanup(AbortSignal.abort());
211
+ return result;
212
+ }
213
+ try {
214
+ const blocked = team.members.filter(({ status }) => status === 'paused');
215
+ const running = team.members.filter(({ status }) => status === 'running');
216
+ const occupied = new Set([...inFlight.keys(), ...running.map(({ id }) => id)].filter((id) => !asyncCoordinator || id !== teamRootId));
217
+ const effectiveConcurrency = resolveEffectiveTeamConcurrency(team.concurrency, mainEnv.config, asyncCoordinator);
218
+ let slots = Math.max(0, effectiveConcurrency - occupied.size);
219
+ const resumeEvents = [];
220
+ for (const member of blocked) {
221
+ if (occupied.has(member.id) || inFlight.has(member.id))
222
+ continue;
223
+ const turnId = member.turnId;
224
+ const result = await d.state.turnResult(turnId);
225
+ if (result?.status !== 'paused')
226
+ continue;
227
+ const turn = await d.state.turn(turnId);
228
+ if (result.reason !== 'approval' &&
229
+ turn.deadlineAt &&
230
+ Date.parse(d.now()) >= Date.parse(turn.deadlineAt)) {
231
+ await runMember(member, await routeFor(member), turn, signal, team.members);
232
+ continue scheduling;
233
+ }
234
+ const consumesWorkerSlot = !asyncCoordinator || member.id !== teamRootId;
235
+ if (run.status === 'paused' ||
236
+ (consumesWorkerSlot && slots <= 0) ||
237
+ (await d.state.resumePreference?.(runId, turnId)) !== 'automatic' ||
238
+ (await d.state.pendingTools(turnId)).some((call) => call.status === 'outcome_unknown' ||
239
+ call.status === 'running' ||
240
+ call.approval?.status === 'pending'))
241
+ continue;
242
+ const route = await routeFor(member);
243
+ const deadlineAt = result.reason === 'approval' ? approvalResumeDeadline(turn, run, d.now()) : undefined;
244
+ resumeEvents.push(d.journal.event('turn.resumed', route, {
245
+ turnId,
246
+ reason: result.reason === 'approval' ? 'approval' : 'reconciled',
247
+ ...(deadlineAt ? { deadlineAt } : {}),
248
+ }));
249
+ if (consumesWorkerSlot)
250
+ slots--;
251
+ }
252
+ if (run.status === 'paused') {
253
+ try {
254
+ if (await d.resumeAutomatically(runId, `team:${runId}:resume:${run.throughPosition}`)) {
255
+ acknowledgeWake();
256
+ continue;
257
+ }
258
+ }
259
+ catch (error) {
260
+ if (!(error instanceof RuntimeError) || error.code !== 'RUN_BLOCKED')
261
+ throw error;
262
+ }
263
+ // A decision can land between reading the blocked Turns and leaving the driver.
264
+ if ((await d.state.run(runId)).throughPosition !== run.throughPosition)
265
+ continue;
266
+ acknowledgeWake();
267
+ return;
268
+ }
269
+ if (resumeEvents.length) {
270
+ await d.journal.append(`team:${runId}:resume:${run.throughPosition}`, resumeEvents);
271
+ acknowledgeWake();
272
+ continue;
273
+ }
274
+ acknowledgeWake();
275
+ if (asyncCoordinator &&
276
+ main.status === 'completed' &&
277
+ !inFlight.has(teamRootId) &&
278
+ main.turnId &&
279
+ d.surface &&
280
+ !processedMainSpawnTurns.has(main.turnId)) {
281
+ processedMainSpawnTurns.add(main.turnId);
282
+ const mainSurface = await d.surface.read(main.agentSessionId);
283
+ const spawnReq = extractSpawnTeamCall(mainSurface, main.turnId);
284
+ const historicalIds = new Set(team.tasks.map(({ memberId }) => memberId));
285
+ if (spawnReq && spawnReq.team.members.some(({ id }) => !historicalIds.has(id))) {
286
+ let spawnedTeam;
287
+ let validationError;
288
+ try {
289
+ const byId = new Map(spawnReq.team.members.map((member) => [member.id, member]));
290
+ const normalizedMembers = spawnReq.team.members.map((member) => {
291
+ if (member.workSubpath !== undefined || member.parent === teamRootId)
292
+ return member;
293
+ const parentSubpath = byId.get(member.parent)?.workSubpath;
294
+ return parentSubpath !== undefined ? { ...member, workSubpath: parentSubpath } : member;
295
+ });
296
+ if (mainEnv.config.modeRef === 'ctf@1' || mainEnv.config.modeRef.startsWith('ctf@')) {
297
+ for (const member of normalizedMembers) {
298
+ if (member.parent !== teamRootId)
299
+ continue;
300
+ if (typeof member.workSubpath !== 'string' || !member.workSubpath.trim()) {
301
+ throw new RuntimeError('INVALID_TEAM_CONFIG', `In ctf@1 mode, Depth-1 worker "${member.id}" must provide a non-empty workSubpath`);
302
+ }
303
+ }
304
+ }
305
+ const rawConcurrency = spawnReq.team.concurrency ?? team.concurrency;
306
+ const mergedConcurrency = asyncCoordinator
307
+ ? Math.max(team.concurrency, rawConcurrency)
308
+ : rawConcurrency;
309
+ const clampedConcurrency = mainEnv.config.teamMaxConcurrency !== undefined
310
+ ? Math.min(mergedConcurrency, mainEnv.config.teamMaxConcurrency)
311
+ : mergedConcurrency;
312
+ const candidate = {
313
+ members: normalizedMembers,
314
+ concurrency: clampedConcurrency,
315
+ };
316
+ validateTeamConfig(candidate);
317
+ const duplicate = candidate.members.find(({ id }) => historicalIds.has(id));
318
+ if (duplicate) {
319
+ throw new RuntimeError('INVALID_TEAM_CONFIG', `spawn_team reused member ID "${duplicate.id}"`);
320
+ }
321
+ const maxWorkers = maxRunTeamWorkers(mainEnv.config);
322
+ if (historicalIds.size + candidate.members.length > maxWorkers) {
323
+ throw new RuntimeError('INVALID_TEAM_CONFIG', `spawn_team exceeded the Run limit of ${maxWorkers} workers`);
324
+ }
325
+ spawnedTeam = candidate;
326
+ }
327
+ catch (error) {
328
+ validationError = error instanceof Error ? error.message : 'Invalid team configuration';
329
+ }
330
+ if (!spawnedTeam) {
331
+ stop.abort();
332
+ await cleanup(AbortSignal.abort());
333
+ return {
334
+ status: 'failed',
335
+ turnId: main.turnId,
336
+ error: {
337
+ code: 'INVALID_TEAM_CONFIG',
338
+ message: validationError ?? 'Invalid team configuration',
339
+ retryable: false,
340
+ },
341
+ usage: run.chargedUsage,
342
+ };
343
+ }
344
+ const { planner: _planner, teamHint: _teamHint, ...baseConfig } = mainEnv.config;
345
+ const createdAt = d.now();
346
+ const spawnEvents = [
347
+ d.journal.event('run.team.planned', scope, {
348
+ plannerAgentSessionId: main.agentSessionId,
349
+ decision: 'team',
350
+ reason: spawnReq.reason,
351
+ team: spawnedTeam,
352
+ }),
353
+ ];
354
+ for (const member of spawnedTeam.members) {
355
+ const workerAgentId = d.id();
356
+ const workerAgentSessionId = d.id();
357
+ const workerConfig = d.freezeWorkerConfig
358
+ ? await d.freezeWorkerConfig(mainEnv.config, spawnedTeam, workerAgentSessionId, { depth: 1 })
359
+ : { ...baseConfig, team: spawnedTeam, agentDepth: 1 };
360
+ spawnEvents.push(d.journal.event('agent.created', { kind: 'workspace', workspaceId: scope.workspaceId }, {
361
+ agent: {
362
+ id: workerAgentId,
363
+ workspaceId: scope.workspaceId,
364
+ role: 'worker',
365
+ defaultScope: 'run',
366
+ modeRef: workerConfig.modeRef,
367
+ createdAt,
368
+ },
369
+ }), d.journal.event('agent_session.created', {
370
+ kind: 'agent_session',
371
+ workspaceId: scope.workspaceId,
372
+ sessionId: scope.sessionId,
373
+ runId,
374
+ agentId: workerAgentId,
375
+ agentSessionId: workerAgentSessionId,
376
+ }, {
377
+ agentSession: {
378
+ id: workerAgentSessionId,
379
+ workspaceId: scope.workspaceId,
380
+ agentId: workerAgentId,
381
+ owner: { scope: 'run', sessionId: scope.sessionId, runId },
382
+ status: 'open',
383
+ createdAt,
384
+ },
385
+ }), d.journal.event('run.agent.attached', scope, {
386
+ membership: {
387
+ runId,
388
+ agentId: workerAgentId,
389
+ agentSessionId: workerAgentSessionId,
390
+ role: 'worker',
391
+ teamMemberId: member.id,
392
+ config: workerConfig,
393
+ },
394
+ }));
395
+ }
396
+ await d.journal.append(`team:${runId}:spawn:${main.turnId}`, spawnEvents);
397
+ lastMainActivityAt = Date.now();
398
+ continue scheduling;
399
+ }
400
+ }
401
+ let subSpawned = false;
402
+ for (const member of team.members) {
403
+ if (member.parent &&
404
+ member.status === 'completed' &&
405
+ member.turnId &&
406
+ !hasFinalReport(team.inbox, member)) {
407
+ const memberEnv = await d.environment.load(runId, member.agentSessionId);
408
+ const depth = memberEnv.config.agentDepth ?? 1;
409
+ const maxDepth = memberEnv.config.teamMaxDepth ?? 1;
410
+ if (depth < maxDepth && d.surface) {
411
+ const surface = await d.surface.read(member.agentSessionId);
412
+ const subReq = extractSpawnTeamCall(surface, member.turnId);
413
+ if (subReq) {
414
+ const historicalIds = new Set(team.tasks.map(({ memberId }) => memberId));
415
+ if (subReq.team.members.some(({ id }) => !historicalIds.has(id))) {
416
+ let subTeam;
417
+ let validationError;
418
+ try {
419
+ const parentWorkSubpath = memberEnv.config.team?.members.find((m) => m.id === member.id)?.workSubpath;
420
+ const inheritedMembers = subReq.team.members.map((child) => child.workSubpath === undefined && parentWorkSubpath !== undefined
421
+ ? { ...child, workSubpath: parentWorkSubpath }
422
+ : child);
423
+ const candidate = {
424
+ members: inheritedMembers,
425
+ rootId: member.id,
426
+ ...(subReq.team.concurrency !== undefined
427
+ ? { concurrency: subReq.team.concurrency }
428
+ : {}),
429
+ };
430
+ validateTeamConfig(candidate, {
431
+ rootId: member.id,
432
+ maxDepth: Math.max(1, maxDepth - depth),
433
+ });
434
+ const duplicate = candidate.members.find(({ id }) => historicalIds.has(id));
435
+ if (duplicate) {
436
+ throw new RuntimeError('INVALID_TEAM_CONFIG', `spawn_team reused member ID "${duplicate.id}"`);
437
+ }
438
+ const maxWorkers = maxRunTeamWorkers(mainEnv.config);
439
+ if (historicalIds.size + candidate.members.length > maxWorkers) {
440
+ throw new RuntimeError('INVALID_TEAM_CONFIG', `spawn_team exceeded the Run limit of ${maxWorkers} workers`);
441
+ }
442
+ subTeam = candidate;
443
+ }
444
+ catch (error) {
445
+ validationError = error instanceof Error ? error.message : 'Invalid team configuration';
446
+ }
447
+ if (!subTeam) {
448
+ stop.abort();
449
+ await cleanup(AbortSignal.abort());
450
+ return {
451
+ status: 'failed',
452
+ turnId: member.turnId,
453
+ error: {
454
+ code: 'INVALID_TEAM_CONFIG',
455
+ message: validationError ?? 'Invalid team configuration',
456
+ retryable: false,
457
+ },
458
+ usage: run.chargedUsage,
459
+ };
460
+ }
461
+ const createdAt = d.now();
462
+ const { planner: _planner, teamHint: _teamHint, ...baseWorkerConfig } = memberEnv.config;
463
+ const subEvents = [
464
+ d.journal.event('run.team.planned', scope, {
465
+ plannerAgentSessionId: member.agentSessionId,
466
+ decision: 'team',
467
+ reason: subReq.reason,
468
+ team: subTeam,
469
+ }),
470
+ ];
471
+ for (const child of subTeam.members) {
472
+ const childAgentId = d.id();
473
+ const childAgentSessionId = d.id();
474
+ const childConfig = d.freezeWorkerConfig
475
+ ? await d.freezeWorkerConfig(memberEnv.config, subTeam, childAgentSessionId, {
476
+ depth: depth + 1,
477
+ })
478
+ : { ...baseWorkerConfig, team: subTeam, agentDepth: depth + 1 };
479
+ subEvents.push(d.journal.event('agent.created', { kind: 'workspace', workspaceId: scope.workspaceId }, {
480
+ agent: {
481
+ id: childAgentId,
482
+ workspaceId: scope.workspaceId,
483
+ role: 'worker',
484
+ defaultScope: 'run',
485
+ modeRef: childConfig.modeRef,
486
+ createdAt,
487
+ },
488
+ }), d.journal.event('agent_session.created', {
489
+ kind: 'agent_session',
490
+ workspaceId: scope.workspaceId,
491
+ sessionId: scope.sessionId,
492
+ runId,
493
+ agentId: childAgentId,
494
+ agentSessionId: childAgentSessionId,
495
+ }, {
496
+ agentSession: {
497
+ id: childAgentSessionId,
498
+ workspaceId: scope.workspaceId,
499
+ agentId: childAgentId,
500
+ owner: { scope: 'run', sessionId: scope.sessionId, runId },
501
+ status: 'open',
502
+ createdAt,
503
+ },
504
+ }), d.journal.event('run.agent.attached', scope, {
505
+ membership: {
506
+ runId,
507
+ agentId: childAgentId,
508
+ agentSessionId: childAgentSessionId,
509
+ role: 'worker',
510
+ teamMemberId: child.id,
511
+ config: childConfig,
512
+ },
513
+ }));
514
+ }
515
+ await d.journal.append(`team:${runId}:subspawn:${member.id}:${member.turnId}`, subEvents);
516
+ subSpawned = true;
517
+ break;
518
+ }
519
+ }
520
+ }
521
+ }
522
+ if (member.parent && ['completed', 'failed', 'interrupted'].includes(member.status)) {
523
+ await finishWorker(member, member.status);
524
+ }
525
+ const failure = degraded.get(member.id);
526
+ if (!member.parent ||
527
+ (member.status !== 'completed' && !failure) ||
528
+ hasFinalReport(team.inbox, member))
529
+ continue;
530
+ const attempts = await d.state.modelAttempts(member.turnId);
531
+ const respondedAttempts = attempts.filter((attempt) => attempt.status === 'responded');
532
+ const final = respondedAttempts.at(-1);
533
+ if (!failure && (!final || final !== attempts.at(-1)))
534
+ throw new RuntimeError('INVALID_RUN_STATE', 'Completed member output missing');
535
+ const extracted = final
536
+ ? final.assistant.content
537
+ .flatMap((part) => (part.type === 'text' ? [part.text] : []))
538
+ .join('\n') ||
539
+ (final.assistant.structuredOutput === undefined
540
+ ? 'The result contains non-text output.'
541
+ : JSON.stringify(final.assistant.structuredOutput))
542
+ : '';
543
+ const text = failure?.status === 'failed'
544
+ ? await failureReport(d.surface, member, failure, extracted)
545
+ : failure?.status === 'interrupted' && failure.reason === 'limit'
546
+ ? await limitReport(d.surface, member, failure, extracted)
547
+ : reportText(failure
548
+ ? extracted
549
+ ? `[Subagent "${member.id}" reached its time limit]\n${extracted}`
550
+ : `[Subagent "${member.id}" reached its time limit before producing a summary.]`
551
+ : extracted);
552
+ await d.journal.append(`team:${runId}:report:${member.id}`, [
553
+ d.journal.event('run.team.message.sent', scope, {
554
+ messageId: failure
555
+ ? `${member.turnId}:${failure.status === 'failed' ? 'failure' : failure.reason}-report`
556
+ : final.assistant.id,
557
+ from: member.id,
558
+ to: member.parent,
559
+ text,
560
+ }),
561
+ ]);
562
+ }
563
+ if (subSpawned)
564
+ continue scheduling;
565
+ const latestTeam = await readTeam();
566
+ const latestMain = latestTeam.members.find((member) => member.id === teamRootId);
567
+ const { inbox } = latestTeam;
568
+ const activeWorkers = latestTeam.members.filter((member) => member.parent !== null && member.status !== 'completed' && !degraded.has(member.id));
569
+ const unreportedFinished = latestTeam.members.filter((member) => member.parent !== null &&
570
+ (member.status === 'completed' || degraded.has(member.id)) &&
571
+ !hasFinalReport(inbox, member));
572
+ const unreadForMain = inbox.filter((message) => message.to === teamRootId && !message.readAt);
573
+ const hasPendingSteer = Boolean(d.pendingSteers && d.pendingSteers.size > 0);
574
+ if (latestMain.status === 'completed' &&
575
+ !hasPendingSteer &&
576
+ (!asyncCoordinator ||
577
+ (activeWorkers.length === 0 &&
578
+ unreportedFinished.length === 0 &&
579
+ unreadForMain.length === 0 &&
580
+ inFlight.size === 0))) {
581
+ const result = await d.state.turnResult(latestMain.turnId);
582
+ if (!result)
583
+ throw new RuntimeError('INVALID_RUN_STATE', 'Root Turn result missing');
584
+ const workers = new Set(latestTeam.members
585
+ .filter(({ parent }) => parent !== null)
586
+ .map(({ agentSessionId }) => agentSessionId));
587
+ const sessions = (await d.state.ownedAgentSessions(runId)).filter(({ id, status }) => status === 'open' && workers.has(id));
588
+ if (sessions.length)
589
+ await d.journal.append(`team:${runId}:archive:${latestMain.turnId}`, sessions.map(({ id, agentId }) => d.journal.event('agent_session.archived', { ...scope, kind: 'agent_session', agentSessionId: id, agentId }, { reason: 'run_ended' })));
590
+ return result;
591
+ }
592
+ const pollIntervalMs = asyncCoordinator ? coordinatorPollIntervalMs(mainEnv.config) : 0;
593
+ const watchdogDue = asyncCoordinator &&
594
+ pollIntervalMs > 0 &&
595
+ activeWorkers.length > 0 &&
596
+ unreadForMain.length === 0 &&
597
+ !inFlight.has(teamRootId) &&
598
+ latestMain.status !== 'running' &&
599
+ latestMain.status !== 'paused' &&
600
+ Date.now() - lastMainActivityAt >= pollIntervalMs;
601
+ const readyWorkers = latestTeam.members.filter((member) => (!asyncCoordinator || member.id !== teamRootId) &&
602
+ ['queued', 'waiting'].includes(member.status) &&
603
+ latestTeam.members
604
+ .filter((child) => child.parent === member.id)
605
+ .every((child) => (child.status === 'completed' || degraded.has(child.id)) && hasFinalReport(inbox, child)));
606
+ const mainReady = asyncCoordinator &&
607
+ !inFlight.has(teamRootId) &&
608
+ latestMain.status !== 'running' &&
609
+ latestMain.status !== 'paused' &&
610
+ (latestMain.status === 'queued' || unreadForMain.length > 0 || watchdogDue || hasPendingSteer);
611
+ const depth1Cap = mainEnv.config.teamMaxActiveDepth1;
612
+ const activeDepth1Count = depth1Cap !== undefined
613
+ ? [...occupied].filter((id) => latestTeam.members.find((member) => member.id === id)?.parent === teamRootId).length
614
+ : 0;
615
+ let depth1Slots = depth1Cap !== undefined ? Math.max(0, depth1Cap - activeDepth1Count) : Infinity;
616
+ const selectedReady = [];
617
+ for (const worker of readyWorkers) {
618
+ if (selectedReady.length >= slots)
619
+ break;
620
+ if (worker.parent === teamRootId) {
621
+ if (depth1Slots <= 0)
622
+ continue;
623
+ depth1Slots -= 1;
624
+ }
625
+ selectedReady.push(worker);
626
+ }
627
+ const runnableMap = new Map();
628
+ for (const member of [
629
+ ...running.filter(({ id }) => !inFlight.has(id)),
630
+ ...(mainReady ? [latestMain] : []),
631
+ ...selectedReady,
632
+ ]) {
633
+ if (!inFlight.has(member.id) && !runnableMap.has(member.id))
634
+ runnableMap.set(member.id, member);
635
+ }
636
+ const runnable = [...runnableMap.values()];
637
+ if (!runnable.length && !inFlight.size) {
638
+ const blockedTurn = blocked[0];
639
+ if (!blockedTurn)
640
+ throw new RuntimeError('INVALID_RUN_STATE', 'Team has no runnable Turn');
641
+ const result = await d.state.turnResult(blockedTurn.turnId);
642
+ if (result?.status !== 'paused')
643
+ continue;
644
+ await d.journal.append(`team:${runId}:pause:${run.throughPosition}`, [
645
+ d.journal.event('run.paused', scope, { reason: result.reason, blockedTurnId: result.turnId }),
646
+ ]);
647
+ continue;
648
+ }
649
+ for (const member of runnable) {
650
+ const route = await routeFor(member);
651
+ const unreadReports = inbox.filter((message) => message.to === member.id && !message.readAt);
652
+ const events = unreadReports.map((message) => d.journal.event('run.team.message.read', scope, {
653
+ messageId: message.messageId,
654
+ memberId: member.id,
655
+ }));
656
+ const needsNewTurn = !member.turnId || (member.id === teamRootId && member.status === 'completed');
657
+ const turn = !needsNewTurn && member.turnId
658
+ ? await d.state.turn(member.turnId)
659
+ : { id: d.id(), inputMessageId: d.id() };
660
+ if (needsNewTurn) {
661
+ const existingTurns = await d.state.turns(runId);
662
+ const ordinal = existingTurns
663
+ .filter((candidate) => candidate.agentSessionId === member.agentSessionId)
664
+ .reduce((max, candidate) => Math.max(max, candidate.ordinal), 0) + 1;
665
+ const directReports = unreadReports.map(({ from, text }) => ({ from, text }));
666
+ const reportsBlock = directReports.length
667
+ ? `${BACKGROUND_CONTEXT_PREFIX}Team reports from direct reports (background data)\n${JSON.stringify(directReports)}\n\n`
668
+ : '';
669
+ const workerTask = latestTeam.tasks.find((candidate) => candidate.memberId === member.id)?.task ?? '';
670
+ const formatActiveWorkersList = () => activeWorkers
671
+ .map((worker) => {
672
+ const elapsedSec = Math.round(Math.max(0, Date.now() - (workerStartedAt.get(worker.id) ?? Date.now())) / 1000);
673
+ return `- ${worker.id} (status=${worker.status}, elapsed=${elapsedSec}s)`;
674
+ })
675
+ .join('\n');
676
+ let taskText;
677
+ const drainedSteers = member.id === teamRootId && d.pendingSteers && d.pendingSteers.size > 0
678
+ ? [...d.pendingSteers.values()]
679
+ : [];
680
+ const steerHeader = drainedSteers.length
681
+ ? `[User Steering Directive]\n${drainedSteers.map((entry) => entry.content).join('\n\n')}\n\n`
682
+ : '';
683
+ if (member.id === teamRootId) {
684
+ const hasFailureReport = directReports.some(({ text }) => text.includes('"status":"failed"') || text.includes('reached its'));
685
+ const failureGuidance = hasFailureReport
686
+ ? 'One or more workers failed or terminated early above: inspect the error/tool evidence, fix any configuration/scope issue, and re-dispatch replacement worker(s) with new member IDs while respecting max_active_challenges.'
687
+ : undefined;
688
+ if (drainedSteers.length > 0 && activeWorkers.length > 0 && unreadReports.length === 0) {
689
+ taskText = `${steerHeader}${[
690
+ `User steering directive received while ${activeWorkers.length} worker(s) remain active:`,
691
+ formatActiveWorkersList(),
692
+ '',
693
+ 'Act on the user directive above (including any `spawn_team` dispatch/reallocation or platform actions), then end your turn to return to Idle / Watching mode.',
694
+ ].join('\n')}`;
695
+ }
696
+ else if (asyncCoordinator && activeWorkers.length > 0 && unreadReports.length > 0) {
697
+ taskText = `${steerHeader}${reportsBlock}${[
698
+ `Incremental team update received while ${activeWorkers.length} worker(s) remain active:`,
699
+ formatActiveWorkersList(),
700
+ ...(failureGuidance ? [failureGuidance] : []),
701
+ 'Review the update(s) above, run any needed coordination or verification (or call spawn_team with new member IDs to backfill freed slots), and end your turn with no further tool calls to return to Idle / Watching mode until the next event.',
702
+ ].join('\n')}`;
703
+ }
704
+ else if (asyncCoordinator && activeWorkers.length > 0 && unreadReports.length === 0) {
705
+ const idleSec = Math.round(Math.max(0, Date.now() - lastMainActivityAt) / 1000);
706
+ taskText = [
707
+ `${BACKGROUND_CONTEXT_PREFIX}Coordinator Watchdog Heartbeat (${idleSec}s since last coordinator activity)`,
708
+ `Active workers (${activeWorkers.length}):`,
709
+ formatActiveWorkersList(),
710
+ '',
711
+ 'Check progress via `ctf_board_status` / `ctf_query_ledger` if needed, resolve any stalled leases or backfill freed slots via `spawn_team`, then end your turn to return to Idle / Watching mode.',
712
+ ].join('\n');
713
+ }
714
+ else {
715
+ taskText = `${steerHeader}${reportsBlock}${[
716
+ ...(failureGuidance
717
+ ? [failureGuidance]
718
+ : ['All team workers have completed their tasks and reported back to you above.']),
719
+ 'Review their evidence, resolve gaps, and verify the remaining work against the user goal.',
720
+ 'If another team wave is needed, use new member IDs. Every worker counts toward the Run member limit.',
721
+ ].join(' ')}`;
722
+ }
723
+ }
724
+ else {
725
+ taskText =
726
+ directReports.length > 0
727
+ ? `${reportsBlock}All of your delegated sub-workers have reported back to you above. Synthesize their evidence for your original assignment ("${workerTask}") and return a concise, verified final report to ${member.parent}.`
728
+ : workerTask;
729
+ }
730
+ events.push(d.journal.event('turn.queued', route, {
731
+ turnId: turn.id,
732
+ inputMessageId: turn.inputMessageId,
733
+ ordinal,
734
+ }), d.journal.event('message.user.added', route, {
735
+ message: {
736
+ id: turn.inputMessageId,
737
+ agentSessionId: member.agentSessionId,
738
+ runId,
739
+ turnId: turn.id,
740
+ role: 'user',
741
+ content: [{ type: 'text', text: taskText }],
742
+ },
743
+ }));
744
+ for (const entry of drainedSteers)
745
+ d.pendingSteers?.delete(entry.commandId);
746
+ }
747
+ const previousReports = inbox.some(({ to, readAt }) => to === member.id && readAt);
748
+ const key = previousReports ||
749
+ (member.id === teamRootId && needsNewTurn && member.turnId !== undefined) ||
750
+ (member.id !== teamRootId && unreadReports.length > 0)
751
+ ? `${member.id}:${turn.id}`
752
+ : member.id;
753
+ if (events.length)
754
+ await d.journal.append(`team:${runId}:prepare:${key}`, events);
755
+ if (signal.aborted)
756
+ break;
757
+ if (member.id === teamRootId) {
758
+ lastMainActivityAt = Date.now();
759
+ }
760
+ else if (!workerStartedAt.has(member.id)) {
761
+ workerStartedAt.set(member.id, Date.now());
762
+ }
763
+ const work = runMember(member, route, turn, signal, latestTeam.members)
764
+ .then(() => { }, (cause) => {
765
+ if (!signal.aborted &&
766
+ member.parent !== null &&
767
+ cause instanceof RuntimeError &&
768
+ (cause.code === 'VERSION_CONFLICT' || cause.message.includes('team concurrency exceeded'))) {
769
+ return;
770
+ }
771
+ driverError ??= { cause };
772
+ })
773
+ .finally(() => {
774
+ if (member.id === teamRootId) {
775
+ lastMainActivityAt = Date.now();
776
+ }
777
+ settled.add(member.id);
778
+ notifyCompletion();
779
+ });
780
+ inFlight.set(member.id, work);
781
+ }
782
+ if (!signal.aborted) {
783
+ const latestAfterLaunch = await readTeam();
784
+ const remainingActiveWorkers = latestAfterLaunch.members.filter((member) => member.parent !== null && member.status !== 'completed' && !degraded.has(member.id));
785
+ const latestMainAfterLaunch = latestAfterLaunch.members.find((member) => member.id === teamRootId);
786
+ const shouldWatchdog = asyncCoordinator &&
787
+ pollIntervalMs > 0 &&
788
+ !inFlight.has(teamRootId) &&
789
+ latestMainAfterLaunch.status !== 'running' &&
790
+ latestMainAfterLaunch.status !== 'paused' &&
791
+ remainingActiveWorkers.length > 0;
792
+ if (shouldWatchdog) {
793
+ const remainingMs = Math.max(1, pollIntervalMs - (Date.now() - lastMainActivityAt));
794
+ const watchdog = new Promise((resolve) => {
795
+ watchdogTimer = setTimeout(resolve, remainingMs);
796
+ });
797
+ await Promise.race([completion, external, watchdog]);
798
+ clearTimeout(watchdogTimer);
799
+ watchdogTimer = undefined;
800
+ }
801
+ else {
802
+ await Promise.race([completion, external]);
803
+ }
804
+ }
805
+ }
806
+ catch (error) {
807
+ const latest = await d.state.run(runId);
808
+ if (!signal.aborted &&
809
+ latest.status !== 'cancelling' &&
810
+ (!(error instanceof RuntimeError) ||
811
+ !['INVALID_TRANSITION', 'VERSION_CONFLICT', 'PROJECTION_FAILED'].includes(error.code) ||
812
+ latest.throughPosition === run.throughPosition))
813
+ throw error;
814
+ }
815
+ }
816
+ }
817
+ }
818
+ async function finishTurns(work) {
819
+ const outcomes = await Promise.allSettled(work);
820
+ return outcomes.map((outcome) => {
821
+ if (outcome.status === 'rejected')
822
+ throw outcome.reason;
823
+ return outcome.value;
824
+ });
825
+ }
826
+ export function extractSpawnTeamCall(surface, turnId) {
827
+ const reasons = [];
828
+ const mergedMembers = new Map();
829
+ let concurrency;
830
+ let rootId;
831
+ let found = 0;
832
+ for (let i = 0; i < surface.items.length; i++) {
833
+ const item = surface.items[i];
834
+ if (!item.active || item.message.turnId !== turnId || item.message.role !== 'tool')
835
+ continue;
836
+ const outcome = item.message.result.outcome;
837
+ if (outcome.status !== 'success' ||
838
+ !outcome.data ||
839
+ typeof outcome.data !== 'object' ||
840
+ Array.isArray(outcome.data))
841
+ continue;
842
+ const data = outcome.data;
843
+ if (data.kind !== 'spawn_team' ||
844
+ typeof data.reason !== 'string' ||
845
+ !data.team ||
846
+ typeof data.team !== 'object' ||
847
+ Array.isArray(data.team))
848
+ continue;
849
+ const team = data.team;
850
+ found += 1;
851
+ const reason = data.reason.trim();
852
+ if (reason && !reasons.includes(reason))
853
+ reasons.push(reason);
854
+ if (team.concurrency !== undefined) {
855
+ concurrency = concurrency === undefined ? team.concurrency : Math.max(concurrency, team.concurrency);
856
+ }
857
+ if (rootId === undefined && team.rootId !== undefined)
858
+ rootId = team.rootId;
859
+ for (const member of team.members) {
860
+ mergedMembers.set(member.id, member);
861
+ }
862
+ }
863
+ if (!found || mergedMembers.size === 0)
864
+ return undefined;
865
+ return {
866
+ reason: reasons.join(' / ') || 'Main agent spawned a team.',
867
+ team: {
868
+ members: [...mergedMembers.values()],
869
+ ...(concurrency !== undefined ? { concurrency } : {}),
870
+ ...(rootId !== undefined ? { rootId } : {}),
871
+ },
872
+ };
873
+ }
874
+ export function approvalResumeDeadline(turn, run, now) {
875
+ if (!turn.deadlineAt || !turn.pausedAt)
876
+ return;
877
+ const pauseMs = Math.max(0, Date.parse(now) - Date.parse(turn.pausedAt));
878
+ return earlierDeadline(new Date(Date.parse(turn.deadlineAt) + pauseMs).toISOString(), run.deadlineAt);
879
+ }
880
+ async function recentTurnToolEvidence(surface, agentSessionId, turnId) {
881
+ const messages = (await surface?.read(agentSessionId))?.items ?? [];
882
+ const toolNames = new Map(messages.flatMap(({ message }) => message.role === 'assistant' && message.turnId === turnId
883
+ ? message.toolCalls.map(({ id, toolName }) => [id, toolName])
884
+ : []));
885
+ return messages
886
+ .flatMap(({ message }) => {
887
+ if (message.role !== 'tool' || message.turnId !== turnId)
888
+ return [];
889
+ const { toolCallId, outcome, evidenceRef } = message.result;
890
+ return [
891
+ {
892
+ toolCallId,
893
+ toolName: toolNames.get(toolCallId),
894
+ status: outcome.status,
895
+ evidenceRef,
896
+ evidence: JSON.stringify(outcome).slice(0, 500),
897
+ },
898
+ ];
899
+ })
900
+ .slice(-4);
901
+ }
902
+ async function failureReport(surface, member, failure, summary) {
903
+ const tools = await recentTurnToolEvidence(surface, member.agentSessionId, failure.turnId);
904
+ return JSON.stringify({
905
+ status: 'failed',
906
+ memberId: member.id,
907
+ error: { code: failure.error.code, message: failure.error.message.slice(0, 500) },
908
+ summary: summary.slice(0, 800),
909
+ tools,
910
+ });
911
+ }
912
+ async function limitReport(surface, member, interrupted, summary) {
913
+ const tools = await recentTurnToolEvidence(surface, member.agentSessionId, interrupted.turnId);
914
+ const budgetText = interrupted.budget
915
+ ? `${interrupted.budget.resource} (${interrupted.budget.used}/${interrupted.budget.max})`
916
+ : 'execution limit';
917
+ const parts = [`[Subagent "${member.id}" reached its ${budgetText} limit]`];
918
+ if (summary.trim())
919
+ parts.push(summary.trim());
920
+ else
921
+ parts.push(`Subagent "${member.id}" reached its ${budgetText} limit before producing a summary.`);
922
+ if (tools.length)
923
+ parts.push(`Observed tool evidence:\n${JSON.stringify(tools)}`);
924
+ return reportText(parts.join('\n'));
925
+ }
926
+ function hasFinalReport(inbox, member) {
927
+ if (!member.parent)
928
+ return false;
929
+ return inbox.some((message) => message.from === member.id && message.to === member.parent && !isTeamNotifyMessageId(message.messageId));
930
+ }
931
+ function reportText(value) {
932
+ const text = value.trim() || 'The member completed without a text summary.';
933
+ if (text.length <= 4_000)
934
+ return text;
935
+ return `${text.slice(0, 4_000).replace(/[\uD800-\uDBFF]$/u, '')}\n[Report excerpt]`;
936
+ }