@saturn-universe/runtime-host 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.
Files changed (42) hide show
  1. package/dist/builtin-plugins/saturn-plugin-ctf/index.mjs +2 -2
  2. package/dist/builtin-plugins/saturn-plugin-ctf/package.json +1 -1
  3. package/dist/command-dispatch.js +2 -1
  4. package/dist/composition.d.ts +20 -55
  5. package/dist/composition.js +316 -89
  6. package/dist/context-extensions.d.ts +132 -10
  7. package/dist/context-extensions.js +30 -4
  8. package/dist/cordis/model-responses-plugin.d.ts +2 -1
  9. package/dist/cordis/model-responses-plugin.js +16 -11
  10. package/dist/cordis/plugin-lifecycle.d.ts +1 -0
  11. package/dist/cordis/plugin-lifecycle.js +3 -0
  12. package/dist/cordis/plugin-loader.d.ts +1 -1
  13. package/dist/cordis/plugin-loader.js +45 -10
  14. package/dist/cordis/sandbox-plugin.d.ts +1 -0
  15. package/dist/cordis/sandbox-plugin.js +1 -0
  16. package/dist/cordis/tools/builtin-agent-tools-plugin.d.ts +2 -2
  17. package/dist/cordis/tools/builtin-agent-tools-plugin.js +27 -3
  18. package/dist/cordis/tools/index.d.ts +5 -1
  19. package/dist/cordis/tools/index.js +3 -3
  20. package/dist/cordis/tools/process-manager-plugin.d.ts +1 -1
  21. package/dist/cordis/tools/process-manager-plugin.js +8 -8
  22. package/dist/cordis/tools/tools-core-plugin.js +54 -11
  23. package/dist/env-probe.js +33 -20
  24. package/dist/host-configuration.d.ts +4 -0
  25. package/dist/host-configuration.js +25 -1
  26. package/dist/index.js +9 -2
  27. package/dist/mode-configuration.d.ts +197 -0
  28. package/dist/mode-configuration.js +109 -0
  29. package/dist/modes.js +52 -10
  30. package/dist/provider-catalog.d.ts +301 -34
  31. package/dist/provider-catalog.js +80 -79
  32. package/dist/run-budget.d.ts +30 -7
  33. package/dist/run-budget.js +49 -5
  34. package/dist/runtime-tuning.d.ts +23 -0
  35. package/dist/runtime-tuning.js +68 -0
  36. package/dist/sandbox-manager.d.ts +2 -0
  37. package/dist/sandbox-manager.js +18 -12
  38. package/dist/session-mode-runtime.d.ts +99 -0
  39. package/dist/session-mode-runtime.js +306 -0
  40. package/dist/skills-runtime.d.ts +5 -2
  41. package/dist/skills-runtime.js +8 -5
  42. package/package.json +9 -9
@@ -1,9 +1,10 @@
1
1
  import { realpath, stat } from 'node:fs/promises';
2
2
  import { randomUUID, createHash } from 'node:crypto';
3
3
  import { fileURLToPath, pathToFileURL } from 'node:url';
4
- import { RuntimeError, canonicalJson, configForDerivedAgent, earlierDeadline, isTerminalRunStatus, matchesModeSelector, normalizeFileUriForPlatform, reportDiagnostic, validateTeamConfig, validateTeamHintConfig, } from '@saturn-universe/core';
4
+ import path from 'node:path';
5
+ import { RuntimeError, canonicalJson, configForDerivedAgent, earlierDeadline, isTerminalRunStatus, matchesModeSelector, resolveModeSelector, isLimited, normalizeFileUriForPlatform, reportDiagnostic, defaultTeamConcurrency, validateTeamConfig, validateTeamHintConfig, } from '@saturn-universe/core';
5
6
  import { PROJECT_MCP_CONFIG_FILENAME, resolveCredentialMap } from '@saturn-universe/protocol';
6
- import { createToolExecutor, dataReviewToolSet, isContainedPath } from '@saturn-universe/tools';
7
+ import { createProcessManager, createToolExecutor, dataReviewToolSet, isContainedPath, } from '@saturn-universe/tools';
7
8
  import { createCommandHandler, createContinuationCompletionPolicy, createRuntimeJournal, createAgentLoop, createRunLoop, recoverRuntime, compactSurface, } from '@saturn-universe/runtime';
8
9
  import { createHostLogger, redactExportValue } from './logger.js';
9
10
  import { createSemanticCompletionJudge } from './completion-judge.js';
@@ -18,14 +19,60 @@ import { resolvePluginSessionPaths } from './session-paths.js';
18
19
  import { answerSideQuestion } from './side-question.js';
19
20
  import { startHostContext } from './cordis/host-context.js';
20
21
  import { loadModePlugins } from './cordis/plugin-loader.js';
22
+ import { createSessionModeRuntime } from './session-mode-runtime.js';
21
23
  import { executionTarget, primaryRole } from './cordis/scoped-layers.js';
22
24
  import { resolveActiveMode, resolveModeToolLayers } from './modes.js';
23
- import { resolveRunDefaults, resolveWorkerReasoning, hardLimits } from './provider-catalog.js';
25
+ import { resolveDefaultReasoning, resolveRunDefaults, resolveWorkerReasoning } from './provider-catalog.js';
26
+ import { explicitTimingLimits, hardLimits } from './run-budget.js';
24
27
  import { resolveWebSearchKey } from './user-config.js';
25
28
  export async function composeRuntime(store, root, options = {}, diagnosticDestination) {
29
+ const hostConfiguration = await loadHostConfiguration(root, options.configFile);
30
+ const { activeMode, availableModes } = resolveActiveMode(hostConfiguration.catalog, options.mode);
31
+ const secrets = [];
32
+ const logger = createHostLogger(secrets, diagnosticDestination);
33
+ const processManager = createProcessManager({
34
+ directory: path.join(root, '.saturn', 'processes'),
35
+ async getRunDeadline(runId) {
36
+ const state = await store.stateReader.run(runId);
37
+ return state.deadlineAt ? Date.parse(state.deadlineAt) : undefined;
38
+ },
39
+ onRecordError: (processId) => logger.error({ code: 'PROCESS_RECORD_INVALID', processId }, 'Skipped an invalid process journal; the reservation will not be restarted'),
40
+ });
41
+ // Container ownership labels belong to the workspace. A later Mode mount must
42
+ // not run startup orphan cleanup against other scopes' live containers.
43
+ let sandboxCleanup;
44
+ const dependencies = {
45
+ commit: store,
46
+ reader: store,
47
+ receipt: (id, hash) => store.receipt(id, hash),
48
+ hash: (value) => createHash('sha256').update(canonicalJson(value)).digest('hex'),
49
+ now: () => new Date().toISOString(),
50
+ id: randomUUID,
51
+ epoch: store.epoch,
52
+ rootUri: pathToFileURL(root).href,
53
+ };
54
+ const shared = {
55
+ hostConfiguration,
56
+ dependencies,
57
+ journal: createRuntimeJournal({ ...dependencies, stateReader: store.stateReader }),
58
+ liveProgress: createLiveText(),
59
+ processManager,
60
+ secrets,
61
+ cleanupSandboxOrphans: (cleanup) => (sandboxCleanup ??= cleanup()),
62
+ };
63
+ return createSessionModeRuntime({
64
+ store,
65
+ activeMode,
66
+ availableModes,
67
+ processManager,
68
+ logger,
69
+ mount: (mode, workers, plugins) => composeModeRuntime(store, root, { ...options, mode }, diagnosticDestination, shared, workers, plugins),
70
+ });
71
+ }
72
+ async function composeModeRuntime(store, root, options, diagnosticDestination, shared, workers, plugins) {
26
73
  const resources = {};
27
74
  try {
28
- return await assembleRuntime(resources, store, root, options, diagnosticDestination);
75
+ return await assembleRuntime(resources, store, root, options, diagnosticDestination, shared, workers, plugins);
29
76
  }
30
77
  catch (error) {
31
78
  try {
@@ -36,9 +83,9 @@ export async function composeRuntime(store, root, options = {}, diagnosticDestin
36
83
  }
37
84
  }
38
85
  }
39
- async function assembleRuntime(resources, store, root, options, diagnosticDestination) {
86
+ async function assembleRuntime(resources, store, root, options, diagnosticDestination, shared, workers, plugins) {
40
87
  const readConfiguration = () => loadHostConfiguration(root, options.configFile);
41
- const hostConfiguration = await readConfiguration();
88
+ const hostConfiguration = shared.hostConfiguration;
42
89
  const { catalog, configSource, trustedMcp, mcpServers, mcpServerMeta, mcpJsonError } = hostConfiguration;
43
90
  const credentialMap = await resolveCredentialMap(root);
44
91
  const entryProfile = options.profile ?? process.env.SATURN_PROVIDER_PROFILE;
@@ -66,12 +113,18 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
66
113
  }
67
114
  const toolLayers = resolveModeToolLayers(activeMode, catalog?.workspaceTools);
68
115
  const suppressedGuidanceRoles = new Set(['main', 'worker'].filter((role) => activeMode.prompts?.roles?.[role]?.some((section) => section.mode === 'replace')));
69
- const externalPlugins = await loadModePlugins(activeMode, hostConfiguration, logger);
116
+ for (const secret of secrets)
117
+ if (!shared.secrets.includes(secret))
118
+ shared.secrets.push(secret);
119
+ const externalPlugins = plugins ?? (await loadModePlugins(activeMode, hostConfiguration, logger));
70
120
  const pluginStatuses = new Map();
71
- const skillService = await createSkillRegistryService(root, activeMode, catalog);
72
- const hash = (value) => createHash('sha256').update(canonicalJson(value)).digest('hex');
121
+ const skillService = await createSkillRegistryService(root, activeMode, catalog, {
122
+ packageRoot: hostConfiguration.modePackageDirectories.get(activeMode.ref),
123
+ });
124
+ const { dependencies, journal, liveProgress } = shared;
125
+ const { hash, now } = dependencies;
73
126
  const clock = {
74
- now: () => new Date().toISOString(),
127
+ now,
75
128
  async delay(ms, signal) {
76
129
  signal.throwIfAborted();
77
130
  let timer;
@@ -89,6 +142,8 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
89
142
  }
90
143
  },
91
144
  };
145
+ let stopMemberImpl;
146
+ let steerMemberImpl;
92
147
  let notifyParentImpl;
93
148
  let syncWorkspaceSubpathsImpl;
94
149
  const workerLifecycleListeners = new Set();
@@ -112,6 +167,7 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
112
167
  ...(options.hostPluginTimeoutMs !== undefined ? { timeoutMs: options.hostPluginTimeoutMs } : {}),
113
168
  activeMode,
114
169
  sandbox: {
170
+ cleanupOrphans: shared.cleanupSandboxOrphans,
115
171
  ...(options.allowUnsafeSandboxFallback ? { allowUnsafeFallback: true } : {}),
116
172
  ...(options.sandboxRunner ? { runner: options.sandboxRunner } : {}),
117
173
  },
@@ -123,6 +179,8 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
123
179
  registerSecret(value) {
124
180
  if (value.trim() && !secrets.includes(value))
125
181
  secrets.push(value);
182
+ if (value.trim() && !shared.secrets.includes(value))
183
+ shared.secrets.push(value);
126
184
  },
127
185
  redactValue(value) {
128
186
  return redactExportValue(value, secrets);
@@ -200,14 +258,19 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
200
258
  hash,
201
259
  resultReader: createToolResultReader(store.toolReader),
202
260
  suppressedGuidanceRoles,
203
- processManager: {
204
- async getRunDeadline(runId) {
205
- const state = await store.stateReader.run(runId);
206
- return state.deadlineAt ? Date.parse(state.deadlineAt) : undefined;
207
- },
208
- onRecordError: (processId) => logger.error({ code: 'PROCESS_RECORD_INVALID', processId }, 'Skipped an invalid process journal; the reservation will not be restarted'),
209
- },
261
+ sharedProcessManager: shared.processManager,
262
+ resolveWorkerModeRef: (selector) => resolveModeSelector(selector, availableModes)?.ref,
210
263
  previousDataReview: (runId) => store.hasNumericReview(runId),
264
+ stopMember: (ctx, memberId, reason) => {
265
+ if (!stopMemberImpl)
266
+ throw new RuntimeError('INVALID_RUN_STATE', 'Team stopping is not initialized');
267
+ return stopMemberImpl(ctx, memberId, reason);
268
+ },
269
+ steerMember: (ctx, memberId, message) => {
270
+ if (!steerMemberImpl)
271
+ throw new RuntimeError('INVALID_RUN_STATE', 'Team steering is not initialized');
272
+ return steerMemberImpl(ctx, memberId, message);
273
+ },
211
274
  notifyParent: (delivery) => {
212
275
  if (!notifyParentImpl) {
213
276
  return Promise.reject(new RuntimeError('INVALID_RUN_STATE', 'Team notifier is not initialized'));
@@ -231,19 +294,7 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
231
294
  const { gateway, resolveFrozenModel } = saturnModel;
232
295
  const { composer } = saturnContext;
233
296
  const { registry } = tools;
234
- const dependencies = {
235
- commit: store,
236
- reader: store,
237
- receipt: (id, h) => store.receipt(id, h),
238
- hash,
239
- now: clock.now,
240
- id: randomUUID,
241
- epoch: store.epoch,
242
- rootUri: pathToFileURL(root).href,
243
- stateReader: store.stateReader,
244
- };
245
297
  const admission = createCommandHandler(dependencies);
246
- const journal = createRuntimeJournal(dependencies);
247
298
  async function checkWorkingDirectory(uri) {
248
299
  let working;
249
300
  try {
@@ -349,8 +400,16 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
349
400
  ...turns.map(({ agentSessionId }) => agentSessionId),
350
401
  ]);
351
402
  others.delete(route.agentSessionId);
352
- for (const agentSessionId of others)
353
- await verifyConfigVersions((await environment.load(runId, agentSessionId)).config);
403
+ const team = await store.stateReader.team?.(runId);
404
+ for (const agentSessionId of others) {
405
+ const { config } = await environment.load(runId, agentSessionId);
406
+ const member = team?.members.find((member) => member.agentSessionId === agentSessionId);
407
+ if (config.modeRef !== activeMode.ref &&
408
+ member &&
409
+ ['completed', 'failed', 'interrupted', 'stopped'].includes(member.status))
410
+ continue;
411
+ await (await workerRuntime(runId, agentSessionId, config.modeRef)).verify(config);
412
+ }
354
413
  for (const turn of turns) {
355
414
  for (const call of await store.toolReader.pending(turn.id)) {
356
415
  if (call.definition &&
@@ -358,11 +417,10 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
358
417
  call.approval?.status === 'approved' ||
359
418
  call.status === 'running' ||
360
419
  call.status === 'outcome_unknown'))
361
- await registry.resolveFrozen(call.definition);
420
+ await (await workerRuntime(runId, call.agentSessionId)).verifyTool(call.definition);
362
421
  }
363
422
  }
364
423
  }
365
- const liveProgress = createLiveText();
366
424
  const agent = createAgentLoop({
367
425
  logger,
368
426
  environment,
@@ -388,19 +446,71 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
388
446
  id: randomUUID,
389
447
  signal: stop.signal,
390
448
  });
391
- const loop = createRunLoop({
392
- ...dependencies,
393
- journal,
394
- state: store.stateReader,
395
- environment,
449
+ const worker = {
396
450
  agent,
397
- tools: store.toolReader,
398
- surface: store.surfaceReader,
399
- freezeWorkerConfig: (config, team, agentSessionId, workerOpts) => tools.freezeWorker(config, team, agentSessionId, config.workerReasoningEffort ? resolveFrozenModel(config).capabilities : undefined, workerOpts),
400
- verifyPluginVersions: verifyRunVersions,
401
- completionPolicy: createContinuationCompletionPolicy({ semanticJudge }),
402
- createCheckpoint: (input, prior) => createRunCheckpoint(store.surfaceReader, input, prior),
403
- onWorkerStart: async (workerInput) => {
451
+ executor,
452
+ verify: verifyConfigVersions,
453
+ verifyTool: (definition) => registry.resolveFrozen(definition),
454
+ async freeze(parent, team, agentSessionId, depth) {
455
+ let config = parent;
456
+ const capabilities = resolveFrozenModel(parent).capabilities;
457
+ if (parent.modeRef !== activeMode.ref) {
458
+ const { contextExtensions: _context, pluginBindings, toolSnapshot: _snapshot, workerSoftCheckpointMs: _checkpoint, compaction: _compaction, ...base } = parent;
459
+ const defaults = resolveRunDefaults(parent.model, catalog?.runDefaults, {
460
+ modeBudget,
461
+ capabilities,
462
+ modeRuntime: activeMode,
463
+ ...(parent.runtimeOverrides ? { overrides: parent.runtimeOverrides } : {}),
464
+ });
465
+ const { wallTimeMs: modeWallTime, ...modeLimits } = defaults.limits;
466
+ const limits = {
467
+ ...modeLimits,
468
+ ...(parent.limits.wallTimeMs !== undefined ? { wallTimeMs: parent.limits.wallTimeMs } : {}),
469
+ };
470
+ for (const key of ['maxModelAttempts', 'maxToolCalls', 'maxSteps', 'maxTotalTokens']) {
471
+ const parentLimit = parent.limits[key];
472
+ if (isLimited(parentLimit))
473
+ limits[key] = isLimited(limits[key]) ? Math.min(limits[key], parentLimit) : parentLimit;
474
+ }
475
+ if (isLimited(modeWallTime)) {
476
+ const limit = limits.subagentWallTimeMs;
477
+ limits.subagentWallTimeMs = isLimited(limit) ? Math.min(limit, modeWallTime) : modeWallTime;
478
+ }
479
+ const { modeEffort: _sourceModeEffort, ...workerReasoning } = parent.workerReasoningDefaults ?? {
480
+ reasoning: parent.responses.reasoning ?? null,
481
+ };
482
+ const modeEffort = activeMode.reasoning?.workerEffort;
483
+ config = {
484
+ ...base,
485
+ modeRef: activeMode.ref,
486
+ ...(parent.workerReasoningDefaults || modeEffort
487
+ ? { workerReasoningDefaults: { ...workerReasoning, ...(modeEffort ? { modeEffort } : {}) } }
488
+ : {}),
489
+ toolSetVersion: tools.defaultVersion(capabilities),
490
+ teamMaxDepth: Math.min(parent.teamMaxDepth ?? 1, activeMode.team?.maxDepth ?? 1),
491
+ ...(activeMode.team?.workerSoftCheckpointMs !== undefined
492
+ ? { workerSoftCheckpointMs: activeMode.team.workerSoftCheckpointMs }
493
+ : {}),
494
+ ...(toolLayers.permissionMode
495
+ ? { policyVersion: interactiveToolPolicies[toolLayers.permissionMode] }
496
+ : {}),
497
+ limits,
498
+ retry: parent.runtimeOverrides || activeMode.retry ? defaults.retry : parent.retry,
499
+ ...(defaults.compaction ? { compaction: defaults.compaction } : {}),
500
+ ...(await freezeContextExtensions(root, activeMode, catalog?.skills)),
501
+ };
502
+ const { bindings } = freezeContributions(config, { role: 'worker', agentSessionId });
503
+ config = {
504
+ ...config,
505
+ pluginBindings: {
506
+ ...bindings,
507
+ ...(pluginBindings?.modelProvider ? { modelProvider: pluginBindings.modelProvider } : {}),
508
+ },
509
+ };
510
+ }
511
+ return tools.freezeWorker(config, team, agentSessionId, capabilities, { depth });
512
+ },
513
+ start: async (workerInput) => {
404
514
  const workerEnv = await environment.load(workerInput.runId, workerInput.agentSessionId);
405
515
  const sessionId = workerEnv.route.sessionId;
406
516
  if (saturnSandbox)
@@ -414,7 +524,7 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
414
524
  ...(workerInput.workSubpath !== undefined ? { workSubpath: workerInput.workSubpath } : {}),
415
525
  });
416
526
  },
417
- onWorkerComplete: async (workerInput) => {
527
+ complete: async (workerInput) => {
418
528
  const workerEnv = await environment
419
529
  .load(workerInput.runId, workerInput.agentSessionId)
420
530
  .catch(() => undefined);
@@ -460,14 +570,81 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
460
570
  ...(usage ? { usage } : {}),
461
571
  });
462
572
  },
573
+ };
574
+ async function workerRuntime(runId, agentSessionId, modeRef) {
575
+ const selector = modeRef ?? (await environment.load(runId, agentSessionId)).config.modeRef;
576
+ const ref = resolveModeSelector(selector, availableModes)?.ref;
577
+ if (!ref && selector.includes('@'))
578
+ throw new RuntimeError('PLUGIN_VERSION_UNAVAILABLE', `Worker Mode ${selector} is unavailable`);
579
+ return ref && ref !== activeMode.ref ? workers.acquire(ref, runId, agentSessionId) : worker;
580
+ }
581
+ function freezeWorker(runId, parent, team, agentSessionId, member) {
582
+ let selector = member.modeRef;
583
+ let depth = (parent.agentDepth ?? 0) + 1;
584
+ let ancestor = team.members.find(({ id }) => id === member.parent);
585
+ while (ancestor) {
586
+ selector ??= ancestor.modeRef;
587
+ depth++;
588
+ const ancestorParent = ancestor.parent;
589
+ ancestor = team.members.find(({ id }) => id === ancestorParent);
590
+ }
591
+ const ref = selector ? resolveModeSelector(selector, availableModes)?.ref : parent.modeRef;
592
+ if (!ref)
593
+ throw new RuntimeError('INVALID_TEAM_CONFIG', `Unknown worker Mode: ${selector}`);
594
+ return workerRuntime(runId, agentSessionId, ref).then((runtime) => runtime.freeze(parent, team, agentSessionId, depth));
595
+ }
596
+ const loop = createRunLoop({
597
+ ...dependencies,
598
+ journal,
599
+ state: store.stateReader,
600
+ environment,
601
+ agent: {
602
+ ...agent,
603
+ async resume(input, signal) {
604
+ return (await workerRuntime(input.runId, input.agentSessionId)).agent.resume(input, signal);
605
+ },
606
+ async steer(agentSessionId, commandId, command) {
607
+ return (await workerRuntime(command.runId, agentSessionId)).agent.steer(agentSessionId, commandId, command);
608
+ },
609
+ },
610
+ tools: store.toolReader,
611
+ surface: store.surfaceReader,
612
+ freezeWorkerConfig: freezeWorker,
613
+ verifyPluginVersions: verifyRunVersions,
614
+ completionPolicy: createContinuationCompletionPolicy({ semanticJudge }),
615
+ createCheckpoint: (input, prior) => createRunCheckpoint(store.surfaceReader, input, prior),
616
+ async onWorkerStart(input) {
617
+ const { parentAgentSessionId, ...details } = input;
618
+ const runtime = await workerRuntime(input.runId, input.agentSessionId);
619
+ const sameParentMode = parentAgentSessionId &&
620
+ (await environment.load(input.runId, parentAgentSessionId)).config.modeRef ===
621
+ (await environment.load(input.runId, input.agentSessionId)).config.modeRef;
622
+ await runtime.start({ ...details, ...(sameParentMode ? { parentAgentSessionId } : {}) });
623
+ },
624
+ async onWorkerComplete(input) {
625
+ try {
626
+ const { config } = await environment.load(input.runId, input.agentSessionId);
627
+ const runtime = matchesModeSelector(config.modeRef, activeMode.ref, availableModes)
628
+ ? worker
629
+ : workers.find(input.runId, input.agentSessionId);
630
+ await runtime?.complete(input);
631
+ }
632
+ finally {
633
+ await workers.release(input.runId, input.agentSessionId);
634
+ }
635
+ },
463
636
  });
637
+ steerMemberImpl = loop.steerMember;
638
+ stopMemberImpl = loop.stopMember;
464
639
  notifyParentImpl = async ({ runId, from, to, messageId, text }) => {
465
640
  const { route } = await environment.load(runId);
466
641
  const scope = { kind: 'run', workspaceId: route.workspaceId, sessionId: route.sessionId, runId };
467
642
  await journal.append(`team:${runId}:notify:${messageId}`, [
468
643
  journal.event('run.team.message.sent', scope, { messageId, from, to, text }),
469
644
  ]);
470
- void loop.wakeTeam(runId);
645
+ void workers
646
+ .wake(runId)
647
+ .catch((error) => reportDiagnostic(logger, error, randomUUID(), 'TEAM_WAKE_FAILED', { runId }));
471
648
  };
472
649
  syncWorkspaceSubpathsImpl = async ({ runId, sessionId }, subpaths) => {
473
650
  if (!saturnSandbox || !subpaths.length)
@@ -482,6 +659,7 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
482
659
  let closing = false;
483
660
  let closeTask;
484
661
  async function cleanupRunProcesses(runId, terminalStatus) {
662
+ await workers.release(runId);
485
663
  executor.clearFileSnapshots(runId);
486
664
  const processes = await processManager?.stopRun(runId);
487
665
  for (const process of processes ?? []) {
@@ -606,13 +784,22 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
606
784
  state: store.stateReader,
607
785
  environment,
608
786
  tools: store.toolReader,
609
- executor,
787
+ executor: {
788
+ async executeBatch(input) {
789
+ return (await workerRuntime(input.runId, input.agentSessionId)).executor.executeBatch(input);
790
+ },
791
+ async recover(input) {
792
+ return (await workerRuntime(input.runId, input.agentSessionId)).executor.recover(input);
793
+ },
794
+ },
610
795
  clock,
611
796
  hash,
612
797
  loop,
613
798
  signal: stop.signal,
614
799
  }, schedule, runIds);
615
800
  }
801
+ let stopRunsTask;
802
+ const stopRuns = () => (stopRunsTask ??= loop.stop());
616
803
  async function shutdown() {
617
804
  closing = true;
618
805
  const stopLifecycle = lifecycle.stop();
@@ -620,7 +807,7 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
620
807
  clearTimeout(timer);
621
808
  deadlines.clear();
622
809
  try {
623
- await loop.stop();
810
+ await stopRuns();
624
811
  }
625
812
  finally {
626
813
  stop.abort();
@@ -713,24 +900,11 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
713
900
  : {}),
714
901
  };
715
902
  },
716
- async recover() {
717
- const processes = await processManager?.recover();
718
- for (const runId of new Set((processes ?? []).map(({ scope }) => scope.runId))) {
719
- try {
720
- const state = await store.stateReader.run(runId);
721
- if (isTerminalRunStatus(state.status))
722
- await cleanupRunProcesses(runId);
723
- }
724
- catch (error) {
725
- if (!(error instanceof RuntimeError) || error.code !== 'NOT_FOUND')
726
- throw error;
727
- // A database restore does not roll back process side effects or their journals.
728
- await cleanupRunProcesses(runId);
729
- logger.info({ code: 'ORPHAN_PROCESS_RUN', runId }, 'Cleaned up a process scope absent from the restored database');
730
- }
731
- }
732
- return recoverRuns();
733
- },
903
+ recoverRuns,
904
+ stopRuns,
905
+ wakeTeam: loop.wakeTeam,
906
+ worker,
907
+ activePlugins: () => lifecycle.activePlugins(),
734
908
  handle(request, requestSignal) {
735
909
  if (closing)
736
910
  return Promise.reject(new RuntimeError('HOST_CLOSING', 'Host is shutting down'));
@@ -749,6 +923,8 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
749
923
  async function handle(request, requestSignal) {
750
924
  const { command, commandId } = request;
751
925
  switch (command.type) {
926
+ case 'session.mode.select':
927
+ throw new RuntimeError('UNSUPPORTED', 'Session Mode selection belongs to the Host');
752
928
  case 'run.submit': {
753
929
  return lifecycle.withAdmission(async () => {
754
930
  const identity = { version: 2, hash: hash({ version: 2, command }) };
@@ -772,12 +948,13 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
772
948
  const defaults = catalog?.runDefaults;
773
949
  const defaultToolSet = tools.defaultVersion(resolvedModel.capabilities);
774
950
  let team = input.config?.team;
775
- if (input.teamPreset !== undefined) {
951
+ const presetName = input.teamPreset ?? (team === undefined ? activeMode.team?.defaultPreset : undefined);
952
+ if (presetName !== undefined) {
776
953
  if (input.config?.team !== undefined)
777
954
  throw new RuntimeError('INVALID_CONFIG', 'teamPreset and config.team are mutually exclusive');
778
- if (!catalog?.teamPresets || !Object.hasOwn(catalog.teamPresets, input.teamPreset))
779
- throw new RuntimeError('INVALID_CONFIG', 'Unknown team preset');
780
- const preset = catalog.teamPresets[input.teamPreset];
955
+ if (!catalog?.teamPresets || !Object.hasOwn(catalog.teamPresets, presetName))
956
+ throw new RuntimeError('INVALID_CONFIG', `Unknown team preset "${presetName}"${input.teamPreset === undefined ? ` configured as team.default_preset for Mode ${activeMode.ref}` : ''}`);
957
+ const preset = catalog.teamPresets[presetName];
781
958
  const userPrompt = input.content
782
959
  .flatMap((part) => (part.type === 'text' ? [part.text] : []))
783
960
  .join('\n')
@@ -797,7 +974,9 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
797
974
  if (team && teamHint)
798
975
  throw new RuntimeError('INVALID_CONFIG', 'team and teamHint are mutually exclusive');
799
976
  if (team) {
800
- validateTeamConfig(team);
977
+ validateTeamConfig(team, activeMode.team?.maxDepth !== undefined ? { maxDepth: activeMode.team.maxDepth } : undefined);
978
+ if (team.members.some(({ modeRef }) => modeRef !== undefined))
979
+ throw new RuntimeError('INVALID_TEAM_CONFIG', 'Team member modeRef is supported by spawn_team');
801
980
  if (activeMode.ref === 'ctf@1' || activeMode.ref.startsWith('ctf@')) {
802
981
  for (const member of team.members) {
803
982
  if (member.parent !== 'main')
@@ -812,22 +991,59 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
812
991
  validateTeamHintConfig(teamHint);
813
992
  if (input.config?.modeRef !== undefined &&
814
993
  !matchesModeSelector(input.config.modeRef, activeMode.ref, availableModes))
815
- throw new RuntimeError('MODE_MISMATCH', `Host is running in mode ${activeMode.ref}; cannot submit run for mode ${input.config.modeRef}`);
816
- const { planner: _ignoredPlanner, ...restInputConfig } = input.config ?? {};
994
+ throw new RuntimeError('MODE_MISMATCH', `Session is using mode ${activeMode.ref}; cannot submit run for mode ${input.config.modeRef}`);
995
+ const { planner: _ignoredPlanner, limits: suppliedLimits, retry: suppliedRetry, compaction: suppliedCompaction, ...restInputConfig } = input.config ?? {};
996
+ const timingOverrides = explicitTimingLimits(suppliedLimits);
817
997
  const effectivePermissionMode = input.permissionMode ?? toolLayers.permissionMode ?? defaults?.permission_mode;
998
+ const runDefaults = defaultToolSet !== '1' ? { tool_set_version: defaultToolSet, ...defaults } : defaults;
999
+ const defaultOptions = {
1000
+ capabilities: resolvedModel.capabilities,
1001
+ ...(profileReasoningEffort ? { profileReasoningEffort } : {}),
1002
+ modeBudget,
1003
+ modeRuntime: activeMode,
1004
+ overrides: {
1005
+ ...(suppliedLimits ? { limits: suppliedLimits } : {}),
1006
+ ...(suppliedRetry ? { retry: suppliedRetry } : {}),
1007
+ ...(suppliedCompaction ? { compaction: suppliedCompaction } : {}),
1008
+ },
1009
+ };
1010
+ const defaultConfig = resolveRunDefaults(model, runDefaults, defaultOptions);
1011
+ const { mainEffort, workerEffort } = activeMode.reasoning ?? {};
1012
+ const { reasoning: _globalReasoning, ...responseDefaults } = defaultConfig.responses;
1013
+ const modeReasoning = mainEffort
1014
+ ? resolveDefaultReasoning(runDefaults, { ...defaultOptions, modeMainReasoningEffort: mainEffort })
1015
+ : undefined;
1016
+ const mainResponses = restInputConfig.responses ??
1017
+ (mainEffort
1018
+ ? { ...responseDefaults, ...(modeReasoning ? { reasoning: modeReasoning } : {}) }
1019
+ : defaultConfig.responses);
1020
+ const workerReasoning = (restInputConfig.responses ?? defaultConfig.responses).reasoning ?? null;
818
1021
  const selectedConfig = {
819
- ...resolveRunDefaults(model, defaultToolSet !== '1'
820
- ? {
821
- tool_set_version: defaultToolSet,
822
- ...defaults,
823
- }
824
- : defaults, {
825
- capabilities: resolvedModel.capabilities,
826
- ...(profileReasoningEffort ? { profileReasoningEffort } : {}),
827
- modeBudget,
828
- }),
1022
+ ...defaultConfig,
829
1023
  ...restInputConfig,
1024
+ responses: mainResponses,
830
1025
  modeRef: activeMode.ref,
1026
+ // Version-one receipts hashed the complete limits supplied by the caller.
1027
+ ...(previous && suppliedLimits ? { limits: suppliedLimits } : {}),
1028
+ ...(!previous && (timingOverrides || suppliedRetry || suppliedCompaction || activeMode.retry)
1029
+ ? {
1030
+ runtimeOverrides: {
1031
+ ...(timingOverrides ? { limits: timingOverrides } : {}),
1032
+ ...(suppliedRetry ? { retry: suppliedRetry } : {}),
1033
+ ...(suppliedCompaction ? { compaction: suppliedCompaction } : {}),
1034
+ },
1035
+ }
1036
+ : {}),
1037
+ // Keep the baseline and explicit override intent for workers dispatched to another Mode.
1038
+ ...(!previous && availableModes.some((mode) => mode.reasoning)
1039
+ ? {
1040
+ workerReasoningDefaults: {
1041
+ reasoning: workerReasoning,
1042
+ ...(workerEffort ? { modeEffort: workerEffort } : {}),
1043
+ ...(restInputConfig.workerReasoningEffort !== undefined ? { explicitEffort: true } : {}),
1044
+ },
1045
+ }
1046
+ : {}),
831
1047
  ...(activeMode.team?.maxDepth !== undefined ? { teamMaxDepth: activeMode.team.maxDepth } : {}),
832
1048
  ...(activeMode.team?.asyncCoordinator !== undefined
833
1049
  ? { teamAsyncCoordinator: activeMode.team.asyncCoordinator }
@@ -841,6 +1057,7 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
841
1057
  ...(activeMode.team?.maxActiveDepth1 !== undefined
842
1058
  ? { teamMaxActiveDepth1: activeMode.team.maxActiveDepth1 }
843
1059
  : {}),
1060
+ teamDefaultConcurrency: activeMode.team?.defaultConcurrency ?? defaultTeamConcurrency,
844
1061
  ...(activeMode.team?.maxConcurrency !== undefined
845
1062
  ? { teamMaxConcurrency: activeMode.team.maxConcurrency }
846
1063
  : {}),
@@ -941,7 +1158,7 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
941
1158
  if (state.status === 'failed') {
942
1159
  const { route, config: original, workingDirectory } = await store.environmentReader.load(runId);
943
1160
  if (original.modeRef && !matchesModeSelector(original.modeRef, activeMode.ref, availableModes))
944
- throw new RuntimeError('MODE_MISMATCH', `Host is running in mode ${activeMode.ref}; checkpoint run belongs to mode ${original.modeRef}`);
1161
+ throw new RuntimeError('MODE_MISMATCH', `Session is using mode ${activeMode.ref}; checkpoint run belongs to mode ${original.modeRef}`);
945
1162
  const terminal = (await store.receipt(`run:${runId}:terminal`))?.events.find((event) => event.type === 'run.failed');
946
1163
  const checkpoint = terminal?.payload.error.checkpoint;
947
1164
  if (!checkpoint)
@@ -963,7 +1180,9 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
963
1180
  content: originalInput.content,
964
1181
  },
965
1182
  }, identity, (config, role, agentSessionId) => role === 'worker'
966
- ? resolveWorkerReasoning(configForDerivedAgent(config, role, agentSessionId), config.workerReasoningEffort ? resolveFrozenModel(config).capabilities : undefined)
1183
+ ? resolveWorkerReasoning(configForDerivedAgent(config, role, agentSessionId), config.workerReasoningEffort || config.workerReasoningDefaults
1184
+ ? resolveFrozenModel(config).capabilities
1185
+ : undefined)
967
1186
  : config));
968
1187
  schedule(result.runId);
969
1188
  return { runId: result.runId, cursor: await store.head() };
@@ -1005,7 +1224,8 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
1005
1224
  case 'tool.reconcile': {
1006
1225
  const call = await store.toolReader.read(command.toolCallId);
1007
1226
  return withRun(call.runId, async () => {
1008
- await executor.reconcile(command.toolCallId, command.decision, commandId);
1227
+ const runtime = await workerRuntime(call.runId, call.agentSessionId);
1228
+ await runtime.executor.reconcile(command.toolCallId, command.decision, commandId);
1009
1229
  await maybeResume(call.runId, `reconcile:${commandId}:resume`);
1010
1230
  return {
1011
1231
  toolCallId: command.toolCallId,
@@ -1053,7 +1273,7 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
1053
1273
  return (await store.sessionList(command));
1054
1274
  case 'session.export': {
1055
1275
  const { platformCredentials, ...page } = await store.sessionExport(command);
1056
- const exportSecrets = [...secrets, ...platformCredentials];
1276
+ const exportSecrets = [...shared.secrets, ...platformCredentials];
1057
1277
  return {
1058
1278
  ...page,
1059
1279
  records: page.records.map((record) => ({
@@ -1151,7 +1371,14 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
1151
1371
  case 'run.timeline':
1152
1372
  return runTimeline(store, command);
1153
1373
  case 'surface.compact':
1154
- return compactSurface({ ...dependencies, environment, surfaceReader: store.surfaceReader, gateway, logger }, commandId, command);
1374
+ return compactSurface({
1375
+ ...dependencies,
1376
+ environment,
1377
+ stateReader: store.stateReader,
1378
+ surfaceReader: store.surfaceReader,
1379
+ gateway,
1380
+ logger,
1381
+ }, commandId, command);
1155
1382
  case 'context.query': {
1156
1383
  const { route } = await environment.load(command.runId);
1157
1384
  const snapshot = await store.contextReader.read(route.agentSessionId, command.runId);