@saturn-universe/runtime 0.1.1 → 0.1.2-dev.10

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));
@@ -322,7 +324,7 @@ export function createAgentLoop(d) {
322
324
  }
323
325
  async function planRequest(input, signal, route, config, attempts, deadlineAt, limitWallTimeMs, reservedTokens, hooks, previousWireRequest) {
324
326
  const last = attempts.at(-1);
325
- const autoCompactOpts = resolveAutoCompactionOptions(d.autoCompaction);
327
+ const autoCompactOpts = resolveAutoCompactionOptions(config.compaction ?? d.autoCompaction);
326
328
  const maxOverflowCompactionRecoveries = 2;
327
329
  let request;
328
330
  try {
@@ -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();
@@ -1,17 +1,6 @@
1
- import type { AgentExecutionScope, CommandId, ExecutionEnvironmentReader, Hash, HostCommand, LoggerPort, ModelGateway, RunConfig, RuntimeJournal, RuntimeStateReader, SurfaceCompactionReceipt, SurfaceItem, SurfaceReader, SurfaceUnit, TurnId } from '@saturn-universe/core';
1
+ import type { AgentExecutionScope, AutoCompactionOptions, CommandId, ExecutionEnvironmentReader, Hash, HostCommand, LoggerPort, ModelGateway, RunConfig, RuntimeJournal, RuntimeStateReader, SurfaceCompactionReceipt, SurfaceItem, SurfaceReader, SurfaceUnit, TurnId } from '@saturn-universe/core';
2
2
  import type { CommandDependencies } from './command-dependencies.js';
3
- export interface AutoCompactionOptions {
4
- readonly enabled?: boolean;
5
- readonly thresholdRatio?: number;
6
- readonly maxHeadroomTokens?: number;
7
- readonly headroomRatio?: number;
8
- readonly minRecentSteps?: number;
9
- readonly tailWindowRatio?: number;
10
- readonly preflightWindowRatio?: number;
11
- readonly maxHalvings?: number;
12
- readonly minPrefixChars?: number;
13
- readonly summaryTimeoutMs?: number;
14
- }
3
+ export type { AutoCompactionOptions } from '@saturn-universe/core';
15
4
  export interface PreflightSummaryPlan {
16
5
  readonly units: readonly SurfaceUnit[];
17
6
  readonly items: readonly SurfaceItem[];
@@ -392,6 +392,7 @@ export async function compactSurface(d, commandId, command) {
392
392
  config,
393
393
  units: targetUnits,
394
394
  signal: controller.signal,
395
+ ...(config.compaction ? { options: config.compaction } : {}),
395
396
  });
396
397
  if (!generated.ok) {
397
398
  throw new RuntimeError('COMPACTION_FAILED', `Automatic compaction skipped: ${generated.reason}`);
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, TeamMemberConfig, 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 & {
@@ -9,9 +10,7 @@ export declare function createRunLoop(d: CommandDependencies & {
9
10
  agent: AgentLoop & Partial<Pick<ReturnType<typeof import('./agent-loop.js').createAgentLoop>, 'steer' | 'clearSteering'>>;
10
11
  tools: ToolExecutionReader;
11
12
  surface?: SurfaceReader;
12
- freezeWorkerConfig?: (mainConfig: RunConfig, team: TeamConfig, id: AgentSessionId, options?: {
13
- readonly depth?: number;
14
- }) => Promise<RunConfig>;
13
+ freezeWorkerConfig?: (runId: RunId, mainConfig: RunConfig, team: TeamConfig, id: AgentSessionId, member: TeamMemberConfig) => Promise<RunConfig>;
15
14
  verifyPluginVersions?: (runId: RunId) => Promise<void>;
16
15
  completionPolicy?: RunCompletionPolicy;
17
16
  createCheckpoint?: (input: AgentInput, prior?: RunCheckpoint) => Promise<RunCheckpoint | undefined>;
@@ -40,6 +39,8 @@ export declare function createRunLoop(d: CommandDependencies & {
40
39
  steer(commandId: CommandId, command: Extract<HostCommand, {
41
40
  type: 'run.steer';
42
41
  }>): Promise<void>;
42
+ steerMember(caller: MemberToolCaller, memberId: string, message: string): Promise<TeamMemberActionResult>;
43
+ stopMember(caller: MemberToolCaller, memberId: string, reason: string): Promise<TeamMemberActionResult>;
43
44
  requestCancel(runId: RunId, commandId: CommandId, reason: string): Promise<{
44
45
  work: Promise<void>;
45
46
  }>;
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, isTerminalRunStatus, maxRunTeamWorkers, RuntimeError, teamMemberIdPattern, teamRootId, validateStartedRun, validateTeamConfig, maxTeamDepth, isAsyncCoordinatorConfig, } 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({
@@ -281,20 +414,12 @@ export function createRunLoop(d) {
281
414
  }
282
415
  }
283
416
  }
284
- const asyncCoordinator = isAsyncCoordinatorConfig(env.config);
285
- const rawConcurrency = spawnReq.team.concurrency ??
286
- (teamState ? teamState.concurrency : env.config.teamHint?.concurrency);
287
- const mergedConcurrency = asyncCoordinator && teamState && rawConcurrency !== undefined
288
- ? Math.max(teamState.concurrency, rawConcurrency)
289
- : rawConcurrency;
290
- const clampedConcurrency = mergedConcurrency !== undefined && env.config.teamMaxConcurrency !== undefined
291
- ? Math.min(mergedConcurrency, env.config.teamMaxConcurrency)
292
- : mergedConcurrency;
417
+ const concurrency = spawnReq.team.concurrency ?? env.config.teamHint?.concurrency;
293
418
  const candidate = {
294
419
  members: normalizedMembers,
295
- ...(clampedConcurrency !== undefined ? { concurrency: clampedConcurrency } : {}),
420
+ ...(concurrency !== undefined ? { concurrency } : {}),
296
421
  };
297
- validateTeamConfig(candidate);
422
+ validateTeamConfig(candidate, { maxDepth: env.config.teamMaxDepth ?? maxTeamDepth });
298
423
  const historicalIds = new Set(teamState?.tasks.map(({ memberId }) => memberId));
299
424
  const duplicate = candidate.members.find(({ id }) => historicalIds.has(id));
300
425
  if (duplicate)
@@ -336,7 +461,7 @@ export function createRunLoop(d) {
336
461
  const workerAgentId = d.id();
337
462
  const workerAgentSessionId = d.id();
338
463
  const workerConfig = d.freezeWorkerConfig
339
- ? await d.freezeWorkerConfig(env.config, spawnedTeam, workerAgentSessionId, { depth: 1 })
464
+ ? await d.freezeWorkerConfig(runId, env.config, spawnedTeam, workerAgentSessionId, member)
340
465
  : { ...baseConfig, team: spawnedTeam, agentDepth: 1 };
341
466
  spawnEvents.push(d.journal.event('agent.created', { kind: 'workspace', workspaceId: route.workspaceId }, {
342
467
  agent: {
@@ -659,42 +784,9 @@ export function createRunLoop(d) {
659
784
  drive,
660
785
  checkPluginVersions,
661
786
  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
- },
787
+ steer,
788
+ steerMember,
789
+ stopMember,
698
790
  async cancel(runId, commandId, reason) {
699
791
  const { work } = await requestCancel(runId, commandId, reason);
700
792
  await work;
@@ -1,4 +1,4 @@
1
- import type { AgentLoop, AgentResult, AgentSessionId, CommandId, ExecutionEnvironmentReader, RunConfig, RunId, RunScope, RunState, RuntimeJournal, RuntimeStateReader, SessionSurface, SurfaceReader, TeamConfig, Turn, TurnId, WorkerSandboxProfile } from '@saturn-universe/core';
1
+ import type { AgentLoop, AgentResult, AgentSessionId, CommandId, ExecutionEnvironmentReader, RunConfig, RunId, RunScope, RunState, RuntimeJournal, RuntimeStateReader, SessionSurface, SurfaceReader, TeamConfig, TeamMemberConfig, Turn, TurnId, WorkerSandboxProfile } from '@saturn-universe/core';
2
2
  interface Dependencies {
3
3
  agent: AgentLoop;
4
4
  environment: ExecutionEnvironmentReader;
@@ -6,9 +6,7 @@ interface Dependencies {
6
6
  journal: RuntimeJournal;
7
7
  surface?: SurfaceReader;
8
8
  resumeAutomatically(runId: RunState['runId'], commandId: CommandId): Promise<boolean>;
9
- freezeWorkerConfig?: (mainConfig: RunConfig, team: TeamConfig, id: AgentSessionId, options?: {
10
- readonly depth?: number;
11
- }) => Promise<RunConfig>;
9
+ freezeWorkerConfig?: (runId: RunId, mainConfig: RunConfig, team: TeamConfig, id: AgentSessionId, member: TeamMemberConfig) => Promise<RunConfig>;
12
10
  pendingSteers?: Map<CommandId, {
13
11
  readonly commandId: CommandId;
14
12
  readonly content: string;
@@ -33,9 +31,11 @@ interface Dependencies {
33
31
  now(): string;
34
32
  id(): string;
35
33
  }
34
+ export declare const workerStopReason: unique symbol;
36
35
  export interface TeamWake {
37
36
  readonly target: EventTarget;
38
37
  readonly waiters: Set<() => void>;
38
+ readonly workers: Map<string, AbortController>;
39
39
  }
40
40
  export declare function driveTeam(d: Dependencies, scope: RunScope, parentSignal: AbortSignal, wake: TeamWake): Promise<AgentResult | undefined>;
41
41
  export declare function extractSpawnTeamCall(surface: SessionSurface, turnId: TurnId): {
package/dist/team-loop.js CHANGED
@@ -1,4 +1,5 @@
1
- import { BACKGROUND_CONTEXT_PREFIX, coordinatorPollIntervalMs, earlierDeadline, isAsyncCoordinatorConfig, isTeamNotifyMessageId, isTerminalRunStatus, maxRunTeamWorkers, resolveEffectiveTeamConcurrency, RuntimeError, teamRootId, validateStartedRun, validateTeamConfig, } from '@saturn-universe/core';
1
+ import { BACKGROUND_CONTEXT_PREFIX, coordinatorPollIntervalMs, earlierDeadline, isAsyncCoordinatorConfig, isTeamNotifyMessageId, isTerminalRunStatus, maxRunTeamWorkers, maxTeamDepth, 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());
@@ -214,7 +222,7 @@ export async function driveTeam(d, scope, parentSignal, wake) {
214
222
  const blocked = team.members.filter(({ status }) => status === 'paused');
215
223
  const running = team.members.filter(({ status }) => status === 'running');
216
224
  const occupied = new Set([...inFlight.keys(), ...running.map(({ id }) => id)].filter((id) => !asyncCoordinator || id !== teamRootId));
217
- const effectiveConcurrency = resolveEffectiveTeamConcurrency(team.concurrency, mainEnv.config, asyncCoordinator);
225
+ const effectiveConcurrency = resolveEffectiveTeamConcurrency(team.concurrency, mainEnv.config);
218
226
  let slots = Math.max(0, effectiveConcurrency - occupied.size);
219
227
  const resumeEvents = [];
220
228
  for (const member of blocked) {
@@ -302,18 +310,13 @@ export async function driveTeam(d, scope, parentSignal, wake) {
302
310
  }
303
311
  }
304
312
  }
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
313
  const candidate = {
313
314
  members: normalizedMembers,
314
- concurrency: clampedConcurrency,
315
+ ...(spawnReq.team.concurrency !== undefined
316
+ ? { concurrency: spawnReq.team.concurrency }
317
+ : {}),
315
318
  };
316
- validateTeamConfig(candidate);
319
+ validateTeamConfig(candidate, { maxDepth: mainEnv.config.teamMaxDepth ?? maxTeamDepth });
317
320
  const duplicate = candidate.members.find(({ id }) => historicalIds.has(id));
318
321
  if (duplicate) {
319
322
  throw new RuntimeError('INVALID_TEAM_CONFIG', `spawn_team reused member ID "${duplicate.id}"`);
@@ -355,7 +358,7 @@ export async function driveTeam(d, scope, parentSignal, wake) {
355
358
  const workerAgentId = d.id();
356
359
  const workerAgentSessionId = d.id();
357
360
  const workerConfig = d.freezeWorkerConfig
358
- ? await d.freezeWorkerConfig(mainEnv.config, spawnedTeam, workerAgentSessionId, { depth: 1 })
361
+ ? await d.freezeWorkerConfig(runId, mainEnv.config, spawnedTeam, workerAgentSessionId, member)
359
362
  : { ...baseConfig, team: spawnedTeam, agentDepth: 1 };
360
363
  spawnEvents.push(d.journal.event('agent.created', { kind: 'workspace', workspaceId: scope.workspaceId }, {
361
364
  agent: {
@@ -472,9 +475,7 @@ export async function driveTeam(d, scope, parentSignal, wake) {
472
475
  const childAgentId = d.id();
473
476
  const childAgentSessionId = d.id();
474
477
  const childConfig = d.freezeWorkerConfig
475
- ? await d.freezeWorkerConfig(memberEnv.config, subTeam, childAgentSessionId, {
476
- depth: depth + 1,
477
- })
478
+ ? await d.freezeWorkerConfig(runId, memberEnv.config, subTeam, childAgentSessionId, child)
478
479
  : { ...baseWorkerConfig, team: subTeam, agentDepth: depth + 1 };
479
480
  subEvents.push(d.journal.event('agent.created', { kind: 'workspace', workspaceId: scope.workspaceId }, {
480
481
  agent: {
@@ -519,7 +520,30 @@ export async function driveTeam(d, scope, parentSignal, wake) {
519
520
  }
520
521
  }
521
522
  }
523
+ if (member.status === 'stopped' &&
524
+ member.parent &&
525
+ !inFlight.has(member.id) &&
526
+ !hasFinalReport(team.inbox, member)) {
527
+ await finishWorker(member, 'interrupted');
528
+ const pending = await d.state.pendingTools(member.turnId);
529
+ const text = JSON.stringify({
530
+ status: 'stopped',
531
+ memberId: member.id,
532
+ requestedBy: member.stopRequest.requestedBy,
533
+ reason: member.stopRequest.reason,
534
+ cleanup: pending.length ? 'tool_outcome_unconfirmed' : 'complete',
535
+ ...(pending.length ? { unresolvedToolCallIds: pending.map(({ call }) => call.id) } : {}),
536
+ });
537
+ const recipients = new Set([teamRootId, member.parent]);
538
+ await d.journal.append(`team:${runId}:stop-report:${member.turnId}`, [...recipients].map((to) => d.journal.event('run.team.message.sent', scope, {
539
+ messageId: `${member.turnId}:stop-report:${to}`,
540
+ from: member.id,
541
+ to,
542
+ text,
543
+ })));
544
+ }
522
545
  if (member.parent && ['completed', 'failed', 'interrupted'].includes(member.status)) {
546
+ await inFlight.get(member.id);
523
547
  await finishWorker(member, member.status);
524
548
  }
525
549
  const failure = degraded.get(member.id);
@@ -565,9 +589,12 @@ export async function driveTeam(d, scope, parentSignal, wake) {
565
589
  const latestTeam = await readTeam();
566
590
  const latestMain = latestTeam.members.find((member) => member.id === teamRootId);
567
591
  const { inbox } = latestTeam;
568
- const activeWorkers = latestTeam.members.filter((member) => member.parent !== null && member.status !== 'completed' && !degraded.has(member.id));
592
+ const activeWorkers = latestTeam.members.filter((member) => member.parent !== null &&
593
+ member.status !== 'completed' &&
594
+ member.status !== 'stopped' &&
595
+ !degraded.has(member.id));
569
596
  const unreportedFinished = latestTeam.members.filter((member) => member.parent !== null &&
570
- (member.status === 'completed' || degraded.has(member.id)) &&
597
+ (member.status === 'completed' || member.status === 'stopped' || degraded.has(member.id)) &&
571
598
  !hasFinalReport(inbox, member));
572
599
  const unreadForMain = inbox.filter((message) => message.to === teamRootId && !message.readAt);
573
600
  const hasPendingSteer = Boolean(d.pendingSteers && d.pendingSteers.size > 0);
@@ -587,6 +614,20 @@ export async function driveTeam(d, scope, parentSignal, wake) {
587
614
  const sessions = (await d.state.ownedAgentSessions(runId)).filter(({ id, status }) => status === 'open' && workers.has(id));
588
615
  if (sessions.length)
589
616
  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' })));
617
+ const latestRun = await d.state.run(runId);
618
+ if (latestTeam.members.some(({ status }) => status === 'stopped') &&
619
+ latestRun.unresolvedCallIds.length) {
620
+ return {
621
+ status: 'failed',
622
+ turnId: latestMain.turnId,
623
+ error: {
624
+ code: 'WORKER_STOP_OUTCOME_UNKNOWN',
625
+ message: 'A stopped worker has tool outcomes that still require reconciliation.',
626
+ retryable: false,
627
+ },
628
+ usage: latestRun.chargedUsage,
629
+ };
630
+ }
590
631
  return result;
591
632
  }
592
633
  const pollIntervalMs = asyncCoordinator ? coordinatorPollIntervalMs(mainEnv.config) : 0;
@@ -599,10 +640,12 @@ export async function driveTeam(d, scope, parentSignal, wake) {
599
640
  latestMain.status !== 'paused' &&
600
641
  Date.now() - lastMainActivityAt >= pollIntervalMs;
601
642
  const readyWorkers = latestTeam.members.filter((member) => (!asyncCoordinator || member.id !== teamRootId) &&
643
+ !inFlight.has(member.id) &&
602
644
  ['queued', 'waiting'].includes(member.status) &&
603
645
  latestTeam.members
604
646
  .filter((child) => child.parent === member.id)
605
- .every((child) => (child.status === 'completed' || degraded.has(child.id)) && hasFinalReport(inbox, child)));
647
+ .every((child) => (child.status === 'completed' || child.status === 'stopped' || degraded.has(child.id)) &&
648
+ hasFinalReport(inbox, child)));
606
649
  const mainReady = asyncCoordinator &&
607
650
  !inFlight.has(teamRootId) &&
608
651
  latestMain.status !== 'running' &&
@@ -760,7 +803,11 @@ export async function driveTeam(d, scope, parentSignal, wake) {
760
803
  else if (!workerStartedAt.has(member.id)) {
761
804
  workerStartedAt.set(member.id, Date.now());
762
805
  }
763
- const work = runMember(member, route, turn, signal, latestTeam.members)
806
+ const workerController = asyncCoordinator && member.parent !== null ? new AbortController() : undefined;
807
+ if (workerController)
808
+ wake.workers.set(member.id, workerController);
809
+ const memberSignal = workerController ? AbortSignal.any([signal, workerController.signal]) : signal;
810
+ const work = runMember(member, route, turn, memberSignal, latestTeam.members)
764
811
  .then(() => { }, (cause) => {
765
812
  if (!signal.aborted &&
766
813
  member.parent !== null &&
@@ -774,6 +821,7 @@ export async function driveTeam(d, scope, parentSignal, wake) {
774
821
  if (member.id === teamRootId) {
775
822
  lastMainActivityAt = Date.now();
776
823
  }
824
+ wake.workers.delete(member.id);
777
825
  settled.add(member.id);
778
826
  notifyCompletion();
779
827
  });
@@ -781,7 +829,10 @@ export async function driveTeam(d, scope, parentSignal, wake) {
781
829
  }
782
830
  if (!signal.aborted) {
783
831
  const latestAfterLaunch = await readTeam();
784
- const remainingActiveWorkers = latestAfterLaunch.members.filter((member) => member.parent !== null && member.status !== 'completed' && !degraded.has(member.id));
832
+ const remainingActiveWorkers = latestAfterLaunch.members.filter((member) => member.parent !== null &&
833
+ member.status !== 'completed' &&
834
+ member.status !== 'stopped' &&
835
+ !degraded.has(member.id));
785
836
  const latestMainAfterLaunch = latestAfterLaunch.members.find((member) => member.id === teamRootId);
786
837
  const shouldWatchdog = asyncCoordinator &&
787
838
  pollIntervalMs > 0 &&
package/package.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "@saturn-universe/runtime",
3
- "version": "0.1.1",
3
+ "version": "0.1.2-dev.10",
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.1"
10
+ "@saturn-universe/core": "0.1.2-dev.10"
11
11
  },
12
12
  "exports": {
13
13
  ".": {