@saturn-universe/runtime 0.1.2-dev.5 → 0.1.2-dev.6

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.
@@ -38,7 +38,9 @@ export interface AgentLoopDependencies {
38
38
  export declare function modelRetryDelayMs(retry: RunConfig['retry'], attempt: number, retryAfterMs: number | undefined, random?: () => number): number;
39
39
  type SteeringCommand = Extract<HostCommand, {
40
40
  type: 'run.steer';
41
- }>;
41
+ }> & {
42
+ readonly source?: 'main';
43
+ };
42
44
  export declare function createAgentLoop(d: AgentLoopDependencies): {
43
45
  execute: (input: AgentInput, signal: AbortSignal) => Promise<AgentResult>;
44
46
  resume: (input: AgentInput, signal: AbortSignal) => Promise<AgentResult>;
@@ -1,5 +1,6 @@
1
1
  import { BudgetError, defaultModelTotalTimeoutMs, DEFAULT_SUBAGENT_WALL_TIME_MS, earlierDeadline, isLimited, maxModelReasoningSummaryLength, modelReasoningSummary, modelTokenBudget, reportDiagnostic, resolveSubagentMaxModelAttempts, resolveSubagentWallTimeMs, rewriteModelRequest, RuntimeError, shouldTriggerCompaction, slimModelRequest, validateStartedRun, } from '@saturn-universe/core';
2
2
  import { autoCompactSurface, resolveAutoCompactionOptions, } from './compaction.js';
3
+ import { workerStopReason } from './team-loop.js';
3
4
  export function modelRetryDelayMs(retry, attempt, retryAfterMs, random = Math.random) {
4
5
  if (retryAfterMs !== undefined)
5
6
  return retryAfterMs;
@@ -34,6 +35,7 @@ export function createAgentLoop(d) {
34
35
  await d.journal.append(`steer:${commandId}`, [
35
36
  d.journal.event('message.user.added', route, {
36
37
  steering: true,
38
+ ...(command.source ? { steeringSource: command.source } : {}),
37
39
  message: {
38
40
  id: d.id(),
39
41
  agentSessionId: route.agentSessionId,
@@ -55,7 +57,7 @@ export function createAgentLoop(d) {
55
57
  return previous;
56
58
  const entry = await d.state.run(input.runId);
57
59
  if (entry.status === 'cancelling' || signal.aborted)
58
- return interrupt(input, 'cancelled');
60
+ return interrupt(input, 'cancelled', undefined, signal);
59
61
  const hooks = d.hooks?.(config, env);
60
62
  const startedRun = validateStartedRun(entry, config.limits);
61
63
  let turn = await d.state.turn(input.turnId);
@@ -83,7 +85,7 @@ export function createAgentLoop(d) {
83
85
  while (true) {
84
86
  const run = await d.state.run(input.runId);
85
87
  if (run.status === 'cancelling' || signal.aborted)
86
- return interrupt(input, 'cancelled');
88
+ return interrupt(input, 'cancelled', undefined, signal);
87
89
  if (deadlineAt && Date.parse(d.clock.now()) >= Date.parse(deadlineAt))
88
90
  return interrupt(input, 'timeout', elapsedBudget(limitWallTimeMs, deadlineAt));
89
91
  turn = await d.state.turn(input.turnId);
@@ -111,13 +113,13 @@ export function createAgentLoop(d) {
111
113
  }
112
114
  if (steering.pending.size) {
113
115
  if (signal.aborted || (await d.state.run(input.runId)).status === 'cancelling')
114
- return interrupt(input, 'cancelled');
116
+ return interrupt(input, 'cancelled', undefined, signal);
115
117
  try {
116
118
  await appendSteering(steering, route);
117
119
  }
118
120
  catch (error) {
119
121
  if (signal.aborted || (await d.state.run(input.runId)).status === 'cancelling')
120
- return interrupt(input, 'cancelled');
122
+ return interrupt(input, 'cancelled', undefined, signal);
121
123
  throw error;
122
124
  }
123
125
  if (steering.pending.size)
@@ -254,11 +256,11 @@ export function createAgentLoop(d) {
254
256
  const result = await d.executor.executeBatch(group);
255
257
  d.liveAgents?.update(input, { phase: 'idle', lastActivityAt: d.clock.now() });
256
258
  if (signal.aborted || (await d.state.run(input.runId)).status === 'cancelling')
257
- return interrupt(input, 'cancelled');
259
+ return interrupt(input, 'cancelled', undefined, signal);
258
260
  if (result.status === 'paused')
259
261
  return { status: 'paused', turnId: input.turnId, reason: result.reason };
260
262
  if (result.status === 'cancelled')
261
- return interrupt(input, 'cancelled');
263
+ return interrupt(input, 'cancelled', undefined, signal);
262
264
  if (result.status === 'interrupted')
263
265
  return interrupt(input, result.reason, result.budget);
264
266
  const spawnCallIds = new Set(last.assistant.toolCalls.filter((call) => call.toolName === 'spawn_team').map((call) => call.id));
@@ -420,7 +422,7 @@ export function createAgentLoop(d) {
420
422
  }
421
423
  }
422
424
  catch {
423
- return interrupt(input, 'cancelled');
425
+ return interrupt(input, 'cancelled', undefined, signal);
424
426
  }
425
427
  const surface = await d.surface.read(input.agentSessionId);
426
428
  const fullPrevious = previousWireRequest?.id === last.request.id ? previousWireRequest : undefined;
@@ -606,12 +608,12 @@ export function createAgentLoop(d) {
606
608
  request = rewritten;
607
609
  }
608
610
  if (signal.aborted)
609
- return interrupt(input, 'cancelled');
611
+ return interrupt(input, 'cancelled', undefined, signal);
610
612
  }
611
613
  }
612
614
  catch (error) {
613
615
  if (signal.aborted)
614
- return interrupt(input, 'cancelled');
616
+ return interrupt(input, 'cancelled', undefined, signal);
615
617
  if (error instanceof RuntimeError && error.code === 'PLUGIN_VERSION_UNAVAILABLE')
616
618
  throw error;
617
619
  if (error instanceof RuntimeError && error.code === 'RUN_BUDGET_EXCEEDED') {
@@ -656,7 +658,7 @@ export function createAgentLoop(d) {
656
658
  catch (error) {
657
659
  const current = await d.state.run(input.runId);
658
660
  if (current.status === 'cancelling' || signal.aborted)
659
- return interrupt(input, 'cancelled');
661
+ return interrupt(input, 'cancelled', undefined, signal);
660
662
  if (deadlineAt && Date.parse(d.clock.now()) >= Date.parse(deadlineAt))
661
663
  return interrupt(input, 'timeout', elapsedBudget(limitWallTimeMs, deadlineAt));
662
664
  if ((config.team || env.membership?.searchBranchId !== undefined) &&
@@ -991,7 +993,7 @@ export function createAgentLoop(d) {
991
993
  await d.executor.executeBatch({ ...input, assistantMessageId, signal }, reason === 'cancelled' ? undefined : reason);
992
994
  }
993
995
  }
994
- async function interrupt(input, reason, budget) {
996
+ async function interrupt(input, reason, budget, signal) {
995
997
  await cleanup(input, reason);
996
998
  const state = await d.state.run(input.runId);
997
999
  const { route } = await d.environment.load(input.runId, input.agentSessionId);
@@ -1016,6 +1018,7 @@ export function createAgentLoop(d) {
1016
1018
  d.journal.event('turn.interrupted', route, {
1017
1019
  turnId: input.turnId,
1018
1020
  reason,
1021
+ ...(signal?.reason === workerStopReason ? { stoppedByMain: true } : {}),
1019
1022
  usage: current.chargedUsage,
1020
1023
  unresolvedCallIds: state.unresolvedCallIds,
1021
1024
  ...(budget ? { budget } : {}),
@@ -1043,7 +1046,7 @@ export function createAgentLoop(d) {
1043
1046
  if (!turn?.accepting || turn.input.runId !== command.runId)
1044
1047
  throw new RuntimeError('STEER_UNAVAILABLE', 'The target agent has no active turn accepting steering');
1045
1048
  const pending = turn.pending.get(commandId);
1046
- if (pending && pending.content !== command.content)
1049
+ if (pending && (pending.content !== command.content || pending.source !== command.source))
1047
1050
  throw new RuntimeError('COMMAND_CONFLICT', 'Steering command ID is already in use');
1048
1051
  turn.pending.set(commandId, command);
1049
1052
  turn.attempt?.abort();
package/dist/journal.js CHANGED
@@ -345,6 +345,8 @@ function findCause(event, current, facts) {
345
345
  latest(['model.responded'], sameTurn));
346
346
  case 'run.team.planned':
347
347
  return latest(['turn.completed'], sameRun) ?? latest(['run.started'], sameRun);
348
+ case 'run.team.member.stop_requested':
349
+ return latest(['turn.started', 'turn.resumed'], sameTurn);
348
350
  case 'run.team.message.sent':
349
351
  return (latest(['turn.completed'], (fact) => fact.messageId === event.payload.messageId && sameRun(fact)) ??
350
352
  latest(['tool.call.started', 'tool.call.requested'], sameRun) ??
@@ -352,6 +354,8 @@ function findCause(event, current, facts) {
352
354
  case 'run.team.message.read':
353
355
  return latest(['run.team.message.sent'], (fact) => fact.messageId === event.payload.messageId && sameRun(fact));
354
356
  case 'turn.interrupted':
357
+ if (event.payload.stoppedByMain)
358
+ return latest(['run.team.member.stop_requested'], sameTurn);
355
359
  return (latest(['model.failed', 'tool.call.outcome_unknown'], sameTurn) ??
356
360
  latest(['run.cancel_requested'], sameRun));
357
361
  case 'turn.failed':
@@ -401,6 +405,7 @@ function turnIdOf(event) {
401
405
  case 'turn.completed':
402
406
  case 'turn.failed':
403
407
  case 'turn.interrupted':
408
+ case 'run.team.member.stop_requested':
404
409
  return event.payload.turnId;
405
410
  case 'model.requested':
406
411
  return event.payload.request.turnId;
@@ -1,5 +1,6 @@
1
- import type { HostCommand, AgentSessionId, RunLoop, RunId, CommandId, AgentLoop, AgentInput, RuntimeJournal, RuntimeStateReader, ExecutionEnvironmentReader, RunCompletionPolicy, ToolExecutionReader, SurfaceReader, RunConfig, TeamConfig, RunCheckpoint, WorkerSandboxProfile } from '@saturn-universe/core';
1
+ import type { HostCommand, AgentSessionId, RunLoop, RunId, CommandId, AgentLoop, AgentInput, RuntimeJournal, RuntimeStateReader, ExecutionEnvironmentReader, RunCompletionPolicy, ToolExecutionReader, SurfaceReader, RunConfig, TeamConfig, TeamMemberActionResult, ToolContext, RunCheckpoint, WorkerSandboxProfile } from '@saturn-universe/core';
2
2
  import type { CommandDependencies } from './command-dependencies.js';
3
+ type MemberToolCaller = Pick<ToolContext, 'runId' | 'agentSessionId' | 'executionKey'>;
3
4
  type PrepareRun = (signal: AbortSignal) => Promise<void>;
4
5
  export declare const defaultCompletionPolicy: RunCompletionPolicy;
5
6
  export declare function createRunLoop(d: CommandDependencies & {
@@ -40,6 +41,8 @@ export declare function createRunLoop(d: CommandDependencies & {
40
41
  steer(commandId: CommandId, command: Extract<HostCommand, {
41
42
  type: 'run.steer';
42
43
  }>): Promise<void>;
44
+ steerMember(caller: MemberToolCaller, memberId: string, message: string): Promise<TeamMemberActionResult>;
45
+ stopMember(caller: MemberToolCaller, memberId: string, reason: string): Promise<TeamMemberActionResult>;
43
46
  requestCancel(runId: RunId, commandId: CommandId, reason: string): Promise<{
44
47
  work: Promise<void>;
45
48
  }>;
package/dist/run-loop.js CHANGED
@@ -1,6 +1,6 @@
1
- import { BACKGROUND_CONTEXT_PREFIX, isAsyncCoordinatorConfig, isTerminalRunStatus, maxRunTeamWorkers, RuntimeError, validateStartedRun, validateTeamConfig, } from '@saturn-universe/core';
1
+ import { BACKGROUND_CONTEXT_PREFIX, isAsyncCoordinatorConfig, isTerminalRunStatus, maxRunTeamWorkers, RuntimeError, teamMemberIdPattern, teamRootId, validateStartedRun, validateTeamConfig, } from '@saturn-universe/core';
2
2
  import { createCommandHandler } from './command-handler.js';
3
- import { approvalResumeDeadline, driveTeam, extractSpawnTeamCall } from './team-loop.js';
3
+ import { approvalResumeDeadline, driveTeam, extractSpawnTeamCall, workerStopReason, } from './team-loop.js';
4
4
  import { driveSelectiveSearch, formatSearchResultMessage, hasSearchBudget, searchTokenUsage, } from './search-loop.js';
5
5
  export const defaultCompletionPolicy = {
6
6
  decide(state, result) {
@@ -29,6 +29,139 @@ export function createRunLoop(d) {
29
29
  };
30
30
  const active = new Map();
31
31
  const cancellations = new Set();
32
+ async function findTeamWorker(caller, memberId) {
33
+ const { route, config } = await d.environment.load(caller.runId);
34
+ if (route.agentSessionId !== caller.agentSessionId || !isAsyncCoordinatorConfig(config))
35
+ return {
36
+ status: 'forbidden',
37
+ message: 'Only the main coordinator of an asynchronous Run can control workers.',
38
+ };
39
+ const team = await d.state.team?.(caller.runId);
40
+ const member = team?.members.find(({ id }) => id === memberId);
41
+ if (!teamMemberIdPattern.test(memberId) || memberId === teamRootId || !member?.parent)
42
+ return { status: 'invalid_target', message: `Worker "${memberId}" does not belong to this Run.` };
43
+ return member;
44
+ }
45
+ function endedMember(memberId) {
46
+ return { status: 'ended', message: `Worker "${memberId}" has already ended.` };
47
+ }
48
+ function isFinishedWorker(member) {
49
+ return ['completed', 'failed', 'interrupted', 'stopped'].includes(member.status);
50
+ }
51
+ async function steer(commandId, command) {
52
+ const { runId, agentSessionId } = command;
53
+ const { route } = await d.environment.load(runId, agentSessionId);
54
+ if (!d.agent.steer)
55
+ throw new RuntimeError('STEER_UNAVAILABLE', 'Runtime agent does not support steering');
56
+ try {
57
+ await d.agent.steer(route.agentSessionId, commandId, command);
58
+ }
59
+ catch (error) {
60
+ if (!(error instanceof RuntimeError) || error.code !== 'STEER_UNAVAILABLE')
61
+ throw error;
62
+ const [runState, teamState, mainEnv] = await Promise.all([
63
+ d.state.run(runId),
64
+ d.state.team?.(runId) ?? Promise.resolve(null),
65
+ d.environment.load(runId),
66
+ ]);
67
+ const isIdleAsyncMain = runState.status === 'running' &&
68
+ Boolean(teamState) &&
69
+ isAsyncCoordinatorConfig(mainEnv.config) &&
70
+ route.agentSessionId === mainEnv.route.agentSessionId;
71
+ if (!isIdleAsyncMain)
72
+ throw error;
73
+ if (await d.journal.receipt(`steer:${commandId}`, command))
74
+ return;
75
+ const runSteers = getPendingCoordinatorSteers(runId);
76
+ const existing = runSteers.get(commandId);
77
+ if (existing && existing.content !== command.content) {
78
+ throw new RuntimeError('COMMAND_CONFLICT', 'Steering command ID is already in use');
79
+ }
80
+ runSteers.set(commandId, { commandId, content: command.content });
81
+ const wake = teamWakes.get(runId);
82
+ if (wake) {
83
+ wake.target.dispatchEvent(new Event('wake'));
84
+ }
85
+ }
86
+ }
87
+ async function steerMember(caller, memberId, message) {
88
+ const worker = await findTeamWorker(caller, memberId);
89
+ if (!('agentSessionId' in worker))
90
+ return worker;
91
+ if (isFinishedWorker(worker))
92
+ return endedMember(memberId);
93
+ if (worker.status === 'running') {
94
+ try {
95
+ await steer(`team-steer:${caller.runId}:${caller.executionKey}`, {
96
+ type: 'run.steer',
97
+ runId: caller.runId,
98
+ agentSessionId: worker.agentSessionId,
99
+ source: teamRootId,
100
+ content: `[Steering directive from main]\n${message}`,
101
+ });
102
+ return { status: 'accepted', message: `Steering accepted for worker "${memberId}".` };
103
+ }
104
+ catch (error) {
105
+ if (!(error instanceof RuntimeError) || error.code !== 'STEER_UNAVAILABLE')
106
+ throw error;
107
+ const latest = (await d.state.team?.(caller.runId))?.members.find(({ id }) => id === memberId);
108
+ if (latest && isFinishedWorker(latest))
109
+ return endedMember(memberId);
110
+ }
111
+ }
112
+ return { status: 'inactive', message: `Worker "${memberId}" has no active turn accepting steering.` };
113
+ }
114
+ async function stopMember(caller, memberId, reason) {
115
+ const worker = await findTeamWorker(caller, memberId);
116
+ if (!('agentSessionId' in worker))
117
+ return worker;
118
+ if (isFinishedWorker(worker))
119
+ return endedMember(memberId);
120
+ const wake = teamWakes.get(caller.runId);
121
+ const controller = wake?.workers.get(memberId);
122
+ const inactive = {
123
+ status: 'inactive',
124
+ message: `Worker "${memberId}" has no active turn to stop.`,
125
+ };
126
+ if (worker.stopRequest)
127
+ return { status: 'accepted', message: `Stop already requested for worker "${memberId}".` };
128
+ if (!wake || !controller || worker.status !== 'running' || !worker.turnId)
129
+ return inactive;
130
+ const { workspaceId, sessionId, runId } = await d.environment
131
+ .load(caller.runId)
132
+ .then(({ route }) => route);
133
+ const request = {
134
+ memberId,
135
+ turnId: worker.turnId,
136
+ requesterAgentSessionId: caller.agentSessionId,
137
+ requestedBy: teamRootId,
138
+ reason,
139
+ };
140
+ try {
141
+ await d.journal.append(`team-stop:${runId}:${caller.executionKey}`, [
142
+ d.journal.event('run.team.member.stop_requested', { kind: 'run', workspaceId, sessionId, runId }, request),
143
+ ], undefined, request);
144
+ }
145
+ catch (error) {
146
+ if (!(error instanceof RuntimeError) ||
147
+ !['INVALID_TRANSITION', 'VERSION_CONFLICT', 'PROJECTION_FAILED'].includes(error.code))
148
+ throw error;
149
+ const latest = (await d.state.team?.(runId))?.members.find(({ id }) => id === memberId);
150
+ if (latest && isFinishedWorker(latest))
151
+ return endedMember(memberId);
152
+ if (latest?.stopRequest)
153
+ return { status: 'accepted', message: `Stop already requested for worker "${memberId}".` };
154
+ if (latest?.status !== 'running' || (await d.state.run(runId)).status !== 'running')
155
+ return inactive;
156
+ throw error;
157
+ }
158
+ controller.abort(workerStopReason);
159
+ wake.target.dispatchEvent(new Event('wake'));
160
+ return {
161
+ status: 'accepted',
162
+ message: `Stop requested for worker "${memberId}". Cleanup is in progress.`,
163
+ };
164
+ }
32
165
  let stopping = false;
33
166
  async function drive(runId, signal, prepare) {
34
167
  const existing = active.get(runId);
@@ -223,7 +356,7 @@ export function createRunLoop(d) {
223
356
  const shouldDriveTeam = Boolean(teamState && teamState.members.length > 1 && !teamCompleted);
224
357
  let stepResult;
225
358
  if (shouldDriveTeam) {
226
- const wake = { target: new EventTarget(), waiters: new Set() };
359
+ const wake = { target: new EventTarget(), waiters: new Set(), workers: new Map() };
227
360
  teamWakes.set(runId, wake);
228
361
  try {
229
362
  stepResult = await driveTeam({
@@ -659,42 +792,9 @@ export function createRunLoop(d) {
659
792
  drive,
660
793
  checkPluginVersions,
661
794
  requestCancel,
662
- async steer(commandId, command) {
663
- const { runId, agentSessionId } = command;
664
- const { route } = await d.environment.load(runId, agentSessionId);
665
- if (!d.agent.steer)
666
- throw new RuntimeError('STEER_UNAVAILABLE', 'Runtime agent does not support steering');
667
- try {
668
- await d.agent.steer(route.agentSessionId, commandId, command);
669
- }
670
- catch (error) {
671
- if (!(error instanceof RuntimeError) || error.code !== 'STEER_UNAVAILABLE')
672
- throw error;
673
- const [runState, teamState, mainEnv] = await Promise.all([
674
- d.state.run(runId),
675
- d.state.team?.(runId) ?? Promise.resolve(null),
676
- d.environment.load(runId),
677
- ]);
678
- const isIdleAsyncMain = runState.status === 'running' &&
679
- Boolean(teamState) &&
680
- isAsyncCoordinatorConfig(mainEnv.config) &&
681
- route.agentSessionId === mainEnv.route.agentSessionId;
682
- if (!isIdleAsyncMain)
683
- throw error;
684
- if (await d.journal.receipt(`steer:${commandId}`, command))
685
- return;
686
- const runSteers = getPendingCoordinatorSteers(runId);
687
- const existing = runSteers.get(commandId);
688
- if (existing && existing.content !== command.content) {
689
- throw new RuntimeError('COMMAND_CONFLICT', 'Steering command ID is already in use');
690
- }
691
- runSteers.set(commandId, { commandId, content: command.content });
692
- const wake = teamWakes.get(runId);
693
- if (wake) {
694
- wake.target.dispatchEvent(new Event('wake'));
695
- }
696
- }
697
- },
795
+ steer,
796
+ steerMember,
797
+ stopMember,
698
798
  async cancel(runId, commandId, reason) {
699
799
  const { work } = await requestCancel(runId, commandId, reason);
700
800
  await work;
@@ -33,9 +33,11 @@ interface Dependencies {
33
33
  now(): string;
34
34
  id(): string;
35
35
  }
36
+ export declare const workerStopReason: unique symbol;
36
37
  export interface TeamWake {
37
38
  readonly target: EventTarget;
38
39
  readonly waiters: Set<() => void>;
40
+ readonly workers: Map<string, AbortController>;
39
41
  }
40
42
  export declare function driveTeam(d: Dependencies, scope: RunScope, parentSignal: AbortSignal, wake: TeamWake): Promise<AgentResult | undefined>;
41
43
  export declare function extractSpawnTeamCall(surface: SessionSurface, turnId: TurnId): {
package/dist/team-loop.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { BACKGROUND_CONTEXT_PREFIX, coordinatorPollIntervalMs, earlierDeadline, isAsyncCoordinatorConfig, isTeamNotifyMessageId, isTerminalRunStatus, maxRunTeamWorkers, resolveEffectiveTeamConcurrency, RuntimeError, teamRootId, validateStartedRun, validateTeamConfig, } from '@saturn-universe/core';
2
+ export const workerStopReason = Symbol('Worker stopped by main');
2
3
  export async function driveTeam(d, scope, parentSignal, wake) {
3
4
  const { runId } = scope;
4
5
  const stop = new AbortController();
@@ -184,6 +185,13 @@ export async function driveTeam(d, scope, parentSignal, wake) {
184
185
  const team = await readTeam();
185
186
  const asyncCoordinator = isAsyncCoordinatorConfig(mainEnv.config);
186
187
  const main = team.members.find((member) => member.id === teamRootId);
188
+ const stoppingMember = team.members.find((member) => member.stopRequest && ['running', 'paused'].includes(member.status) && !inFlight.has(member.id));
189
+ if (stoppingMember) {
190
+ // A persisted request can outlive its original driver or race with a tool pause.
191
+ const turn = await d.state.turn(stoppingMember.turnId);
192
+ await runMember(stoppingMember, await routeFor(stoppingMember), turn, AbortSignal.abort(workerStopReason));
193
+ continue;
194
+ }
187
195
  for (const member of team.members) {
188
196
  if (member.parent !== null && member.status === 'running' && !workerStartedAt.has(member.id)) {
189
197
  workerStartedAt.set(member.id, Date.now());
@@ -519,6 +527,28 @@ export async function driveTeam(d, scope, parentSignal, wake) {
519
527
  }
520
528
  }
521
529
  }
530
+ if (member.status === 'stopped' &&
531
+ member.parent &&
532
+ !inFlight.has(member.id) &&
533
+ !hasFinalReport(team.inbox, member)) {
534
+ await finishWorker(member, 'interrupted');
535
+ const pending = await d.state.pendingTools(member.turnId);
536
+ const text = JSON.stringify({
537
+ status: 'stopped',
538
+ memberId: member.id,
539
+ requestedBy: member.stopRequest.requestedBy,
540
+ reason: member.stopRequest.reason,
541
+ cleanup: pending.length ? 'tool_outcome_unconfirmed' : 'complete',
542
+ ...(pending.length ? { unresolvedToolCallIds: pending.map(({ call }) => call.id) } : {}),
543
+ });
544
+ const recipients = new Set([teamRootId, member.parent]);
545
+ await d.journal.append(`team:${runId}:stop-report:${member.turnId}`, [...recipients].map((to) => d.journal.event('run.team.message.sent', scope, {
546
+ messageId: `${member.turnId}:stop-report:${to}`,
547
+ from: member.id,
548
+ to,
549
+ text,
550
+ })));
551
+ }
522
552
  if (member.parent && ['completed', 'failed', 'interrupted'].includes(member.status)) {
523
553
  await finishWorker(member, member.status);
524
554
  }
@@ -565,9 +595,12 @@ export async function driveTeam(d, scope, parentSignal, wake) {
565
595
  const latestTeam = await readTeam();
566
596
  const latestMain = latestTeam.members.find((member) => member.id === teamRootId);
567
597
  const { inbox } = latestTeam;
568
- const activeWorkers = latestTeam.members.filter((member) => member.parent !== null && member.status !== 'completed' && !degraded.has(member.id));
598
+ const activeWorkers = latestTeam.members.filter((member) => member.parent !== null &&
599
+ member.status !== 'completed' &&
600
+ member.status !== 'stopped' &&
601
+ !degraded.has(member.id));
569
602
  const unreportedFinished = latestTeam.members.filter((member) => member.parent !== null &&
570
- (member.status === 'completed' || degraded.has(member.id)) &&
603
+ (member.status === 'completed' || member.status === 'stopped' || degraded.has(member.id)) &&
571
604
  !hasFinalReport(inbox, member));
572
605
  const unreadForMain = inbox.filter((message) => message.to === teamRootId && !message.readAt);
573
606
  const hasPendingSteer = Boolean(d.pendingSteers && d.pendingSteers.size > 0);
@@ -587,6 +620,20 @@ export async function driveTeam(d, scope, parentSignal, wake) {
587
620
  const sessions = (await d.state.ownedAgentSessions(runId)).filter(({ id, status }) => status === 'open' && workers.has(id));
588
621
  if (sessions.length)
589
622
  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' })));
623
+ const latestRun = await d.state.run(runId);
624
+ if (latestTeam.members.some(({ status }) => status === 'stopped') &&
625
+ latestRun.unresolvedCallIds.length) {
626
+ return {
627
+ status: 'failed',
628
+ turnId: latestMain.turnId,
629
+ error: {
630
+ code: 'WORKER_STOP_OUTCOME_UNKNOWN',
631
+ message: 'A stopped worker has tool outcomes that still require reconciliation.',
632
+ retryable: false,
633
+ },
634
+ usage: latestRun.chargedUsage,
635
+ };
636
+ }
590
637
  return result;
591
638
  }
592
639
  const pollIntervalMs = asyncCoordinator ? coordinatorPollIntervalMs(mainEnv.config) : 0;
@@ -602,7 +649,8 @@ export async function driveTeam(d, scope, parentSignal, wake) {
602
649
  ['queued', 'waiting'].includes(member.status) &&
603
650
  latestTeam.members
604
651
  .filter((child) => child.parent === member.id)
605
- .every((child) => (child.status === 'completed' || degraded.has(child.id)) && hasFinalReport(inbox, child)));
652
+ .every((child) => (child.status === 'completed' || child.status === 'stopped' || degraded.has(child.id)) &&
653
+ hasFinalReport(inbox, child)));
606
654
  const mainReady = asyncCoordinator &&
607
655
  !inFlight.has(teamRootId) &&
608
656
  latestMain.status !== 'running' &&
@@ -760,7 +808,11 @@ export async function driveTeam(d, scope, parentSignal, wake) {
760
808
  else if (!workerStartedAt.has(member.id)) {
761
809
  workerStartedAt.set(member.id, Date.now());
762
810
  }
763
- const work = runMember(member, route, turn, signal, latestTeam.members)
811
+ const workerController = asyncCoordinator && member.parent !== null ? new AbortController() : undefined;
812
+ if (workerController)
813
+ wake.workers.set(member.id, workerController);
814
+ const memberSignal = workerController ? AbortSignal.any([signal, workerController.signal]) : signal;
815
+ const work = runMember(member, route, turn, memberSignal, latestTeam.members)
764
816
  .then(() => { }, (cause) => {
765
817
  if (!signal.aborted &&
766
818
  member.parent !== null &&
@@ -774,6 +826,7 @@ export async function driveTeam(d, scope, parentSignal, wake) {
774
826
  if (member.id === teamRootId) {
775
827
  lastMainActivityAt = Date.now();
776
828
  }
829
+ wake.workers.delete(member.id);
777
830
  settled.add(member.id);
778
831
  notifyCompletion();
779
832
  });
@@ -781,7 +834,10 @@ export async function driveTeam(d, scope, parentSignal, wake) {
781
834
  }
782
835
  if (!signal.aborted) {
783
836
  const latestAfterLaunch = await readTeam();
784
- const remainingActiveWorkers = latestAfterLaunch.members.filter((member) => member.parent !== null && member.status !== 'completed' && !degraded.has(member.id));
837
+ const remainingActiveWorkers = latestAfterLaunch.members.filter((member) => member.parent !== null &&
838
+ member.status !== 'completed' &&
839
+ member.status !== 'stopped' &&
840
+ !degraded.has(member.id));
785
841
  const latestMainAfterLaunch = latestAfterLaunch.members.find((member) => member.id === teamRootId);
786
842
  const shouldWatchdog = asyncCoordinator &&
787
843
  pollIntervalMs > 0 &&
package/package.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "@saturn-universe/runtime",
3
- "version": "0.1.2-dev.5",
3
+ "version": "0.1.2-dev.6",
4
4
  "license": "AGPL-3.0-only",
5
5
  "type": "module",
6
6
  "files": [
7
7
  "dist"
8
8
  ],
9
9
  "dependencies": {
10
- "@saturn-universe/core": "0.1.2-dev.5"
10
+ "@saturn-universe/core": "0.1.2-dev.6"
11
11
  },
12
12
  "exports": {
13
13
  ".": {