@saturn-universe/runtime-host 0.1.2-dev.6 → 0.1.2-dev.9

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 (37) 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 +1 -0
  4. package/dist/composition.d.ts +20 -56
  5. package/dist/composition.js +302 -89
  6. package/dist/context-extensions.d.ts +130 -10
  7. package/dist/context-extensions.js +30 -4
  8. package/dist/cordis/plugin-lifecycle.d.ts +1 -0
  9. package/dist/cordis/plugin-lifecycle.js +3 -0
  10. package/dist/cordis/sandbox-plugin.d.ts +1 -0
  11. package/dist/cordis/sandbox-plugin.js +1 -0
  12. package/dist/cordis/tools/builtin-agent-tools-plugin.d.ts +1 -1
  13. package/dist/cordis/tools/builtin-agent-tools-plugin.js +15 -1
  14. package/dist/cordis/tools/index.d.ts +3 -1
  15. package/dist/cordis/tools/index.js +3 -3
  16. package/dist/cordis/tools/process-manager-plugin.d.ts +1 -1
  17. package/dist/cordis/tools/process-manager-plugin.js +8 -8
  18. package/dist/cordis/tools/tools-core-plugin.js +46 -5
  19. package/dist/host-configuration.d.ts +1 -0
  20. package/dist/host-configuration.js +2 -1
  21. package/dist/index.js +1 -1
  22. package/dist/mode-configuration.d.ts +46 -3
  23. package/dist/mode-configuration.js +3 -0
  24. package/dist/modes.js +52 -10
  25. package/dist/provider-catalog.d.ts +84 -14
  26. package/dist/provider-catalog.js +29 -45
  27. package/dist/run-budget.d.ts +21 -6
  28. package/dist/run-budget.js +48 -12
  29. package/dist/runtime-tuning.d.ts +23 -0
  30. package/dist/runtime-tuning.js +68 -0
  31. package/dist/sandbox-manager.d.ts +2 -0
  32. package/dist/sandbox-manager.js +18 -12
  33. package/dist/session-mode-runtime.d.ts +99 -0
  34. package/dist/session-mode-runtime.js +306 -0
  35. package/dist/skills-runtime.d.ts +5 -2
  36. package/dist/skills-runtime.js +8 -5
  37. 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;
@@ -114,6 +167,7 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
114
167
  ...(options.hostPluginTimeoutMs !== undefined ? { timeoutMs: options.hostPluginTimeoutMs } : {}),
115
168
  activeMode,
116
169
  sandbox: {
170
+ cleanupOrphans: shared.cleanupSandboxOrphans,
117
171
  ...(options.allowUnsafeSandboxFallback ? { allowUnsafeFallback: true } : {}),
118
172
  ...(options.sandboxRunner ? { runner: options.sandboxRunner } : {}),
119
173
  },
@@ -125,6 +179,8 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
125
179
  registerSecret(value) {
126
180
  if (value.trim() && !secrets.includes(value))
127
181
  secrets.push(value);
182
+ if (value.trim() && !shared.secrets.includes(value))
183
+ shared.secrets.push(value);
128
184
  },
129
185
  redactValue(value) {
130
186
  return redactExportValue(value, secrets);
@@ -202,13 +258,8 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
202
258
  hash,
203
259
  resultReader: createToolResultReader(store.toolReader),
204
260
  suppressedGuidanceRoles,
205
- processManager: {
206
- async getRunDeadline(runId) {
207
- const state = await store.stateReader.run(runId);
208
- return state.deadlineAt ? Date.parse(state.deadlineAt) : undefined;
209
- },
210
- onRecordError: (processId) => logger.error({ code: 'PROCESS_RECORD_INVALID', processId }, 'Skipped an invalid process journal; the reservation will not be restarted'),
211
- },
261
+ sharedProcessManager: shared.processManager,
262
+ resolveWorkerModeRef: (selector) => resolveModeSelector(selector, availableModes)?.ref,
212
263
  previousDataReview: (runId) => store.hasNumericReview(runId),
213
264
  stopMember: (ctx, memberId, reason) => {
214
265
  if (!stopMemberImpl)
@@ -243,19 +294,7 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
243
294
  const { gateway, resolveFrozenModel } = saturnModel;
244
295
  const { composer } = saturnContext;
245
296
  const { registry } = tools;
246
- const dependencies = {
247
- commit: store,
248
- reader: store,
249
- receipt: (id, h) => store.receipt(id, h),
250
- hash,
251
- now: clock.now,
252
- id: randomUUID,
253
- epoch: store.epoch,
254
- rootUri: pathToFileURL(root).href,
255
- stateReader: store.stateReader,
256
- };
257
297
  const admission = createCommandHandler(dependencies);
258
- const journal = createRuntimeJournal(dependencies);
259
298
  async function checkWorkingDirectory(uri) {
260
299
  let working;
261
300
  try {
@@ -361,8 +400,16 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
361
400
  ...turns.map(({ agentSessionId }) => agentSessionId),
362
401
  ]);
363
402
  others.delete(route.agentSessionId);
364
- for (const agentSessionId of others)
365
- 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
+ }
366
413
  for (const turn of turns) {
367
414
  for (const call of await store.toolReader.pending(turn.id)) {
368
415
  if (call.definition &&
@@ -370,11 +417,10 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
370
417
  call.approval?.status === 'approved' ||
371
418
  call.status === 'running' ||
372
419
  call.status === 'outcome_unknown'))
373
- await registry.resolveFrozen(call.definition);
420
+ await (await workerRuntime(runId, call.agentSessionId)).verifyTool(call.definition);
374
421
  }
375
422
  }
376
423
  }
377
- const liveProgress = createLiveText();
378
424
  const agent = createAgentLoop({
379
425
  logger,
380
426
  environment,
@@ -400,19 +446,71 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
400
446
  id: randomUUID,
401
447
  signal: stop.signal,
402
448
  });
403
- const loop = createRunLoop({
404
- ...dependencies,
405
- journal,
406
- state: store.stateReader,
407
- environment,
449
+ const worker = {
408
450
  agent,
409
- tools: store.toolReader,
410
- surface: store.surfaceReader,
411
- freezeWorkerConfig: (config, team, agentSessionId, workerOpts) => tools.freezeWorker(config, team, agentSessionId, config.workerReasoningEffort ? resolveFrozenModel(config).capabilities : undefined, workerOpts),
412
- verifyPluginVersions: verifyRunVersions,
413
- completionPolicy: createContinuationCompletionPolicy({ semanticJudge }),
414
- createCheckpoint: (input, prior) => createRunCheckpoint(store.surfaceReader, input, prior),
415
- 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) => {
416
514
  const workerEnv = await environment.load(workerInput.runId, workerInput.agentSessionId);
417
515
  const sessionId = workerEnv.route.sessionId;
418
516
  if (saturnSandbox)
@@ -426,7 +524,7 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
426
524
  ...(workerInput.workSubpath !== undefined ? { workSubpath: workerInput.workSubpath } : {}),
427
525
  });
428
526
  },
429
- onWorkerComplete: async (workerInput) => {
527
+ complete: async (workerInput) => {
430
528
  const workerEnv = await environment
431
529
  .load(workerInput.runId, workerInput.agentSessionId)
432
530
  .catch(() => undefined);
@@ -472,6 +570,69 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
472
570
  ...(usage ? { usage } : {}),
473
571
  });
474
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
+ },
475
636
  });
476
637
  steerMemberImpl = loop.steerMember;
477
638
  stopMemberImpl = loop.stopMember;
@@ -481,7 +642,9 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
481
642
  await journal.append(`team:${runId}:notify:${messageId}`, [
482
643
  journal.event('run.team.message.sent', scope, { messageId, from, to, text }),
483
644
  ]);
484
- void loop.wakeTeam(runId);
645
+ void workers
646
+ .wake(runId)
647
+ .catch((error) => reportDiagnostic(logger, error, randomUUID(), 'TEAM_WAKE_FAILED', { runId }));
485
648
  };
486
649
  syncWorkspaceSubpathsImpl = async ({ runId, sessionId }, subpaths) => {
487
650
  if (!saturnSandbox || !subpaths.length)
@@ -496,6 +659,7 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
496
659
  let closing = false;
497
660
  let closeTask;
498
661
  async function cleanupRunProcesses(runId, terminalStatus) {
662
+ await workers.release(runId);
499
663
  executor.clearFileSnapshots(runId);
500
664
  const processes = await processManager?.stopRun(runId);
501
665
  for (const process of processes ?? []) {
@@ -620,13 +784,22 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
620
784
  state: store.stateReader,
621
785
  environment,
622
786
  tools: store.toolReader,
623
- 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
+ },
624
795
  clock,
625
796
  hash,
626
797
  loop,
627
798
  signal: stop.signal,
628
799
  }, schedule, runIds);
629
800
  }
801
+ let stopRunsTask;
802
+ const stopRuns = () => (stopRunsTask ??= loop.stop());
630
803
  async function shutdown() {
631
804
  closing = true;
632
805
  const stopLifecycle = lifecycle.stop();
@@ -634,7 +807,7 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
634
807
  clearTimeout(timer);
635
808
  deadlines.clear();
636
809
  try {
637
- await loop.stop();
810
+ await stopRuns();
638
811
  }
639
812
  finally {
640
813
  stop.abort();
@@ -727,24 +900,11 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
727
900
  : {}),
728
901
  };
729
902
  },
730
- async recover() {
731
- const processes = await processManager?.recover();
732
- for (const runId of new Set((processes ?? []).map(({ scope }) => scope.runId))) {
733
- try {
734
- const state = await store.stateReader.run(runId);
735
- if (isTerminalRunStatus(state.status))
736
- await cleanupRunProcesses(runId);
737
- }
738
- catch (error) {
739
- if (!(error instanceof RuntimeError) || error.code !== 'NOT_FOUND')
740
- throw error;
741
- // A database restore does not roll back process side effects or their journals.
742
- await cleanupRunProcesses(runId);
743
- logger.info({ code: 'ORPHAN_PROCESS_RUN', runId }, 'Cleaned up a process scope absent from the restored database');
744
- }
745
- }
746
- return recoverRuns();
747
- },
903
+ recoverRuns,
904
+ stopRuns,
905
+ wakeTeam: loop.wakeTeam,
906
+ worker,
907
+ activePlugins: () => lifecycle.activePlugins(),
748
908
  handle(request, requestSignal) {
749
909
  if (closing)
750
910
  return Promise.reject(new RuntimeError('HOST_CLOSING', 'Host is shutting down'));
@@ -763,6 +923,8 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
763
923
  async function handle(request, requestSignal) {
764
924
  const { command, commandId } = request;
765
925
  switch (command.type) {
926
+ case 'session.mode.select':
927
+ throw new RuntimeError('UNSUPPORTED', 'Session Mode selection belongs to the Host');
766
928
  case 'run.submit': {
767
929
  return lifecycle.withAdmission(async () => {
768
930
  const identity = { version: 2, hash: hash({ version: 2, command }) };
@@ -786,12 +948,13 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
786
948
  const defaults = catalog?.runDefaults;
787
949
  const defaultToolSet = tools.defaultVersion(resolvedModel.capabilities);
788
950
  let team = input.config?.team;
789
- if (input.teamPreset !== undefined) {
951
+ const presetName = input.teamPreset ?? (team === undefined ? activeMode.team?.defaultPreset : undefined);
952
+ if (presetName !== undefined) {
790
953
  if (input.config?.team !== undefined)
791
954
  throw new RuntimeError('INVALID_CONFIG', 'teamPreset and config.team are mutually exclusive');
792
- if (!catalog?.teamPresets || !Object.hasOwn(catalog.teamPresets, input.teamPreset))
793
- throw new RuntimeError('INVALID_CONFIG', 'Unknown team preset');
794
- 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];
795
958
  const userPrompt = input.content
796
959
  .flatMap((part) => (part.type === 'text' ? [part.text] : []))
797
960
  .join('\n')
@@ -811,7 +974,9 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
811
974
  if (team && teamHint)
812
975
  throw new RuntimeError('INVALID_CONFIG', 'team and teamHint are mutually exclusive');
813
976
  if (team) {
814
- 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');
815
980
  if (activeMode.ref === 'ctf@1' || activeMode.ref.startsWith('ctf@')) {
816
981
  for (const member of team.members) {
817
982
  if (member.parent !== 'main')
@@ -826,22 +991,59 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
826
991
  validateTeamHintConfig(teamHint);
827
992
  if (input.config?.modeRef !== undefined &&
828
993
  !matchesModeSelector(input.config.modeRef, activeMode.ref, availableModes))
829
- throw new RuntimeError('MODE_MISMATCH', `Host is running in mode ${activeMode.ref}; cannot submit run for mode ${input.config.modeRef}`);
830
- 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);
831
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;
832
1021
  const selectedConfig = {
833
- ...resolveRunDefaults(model, defaultToolSet !== '1'
834
- ? {
835
- tool_set_version: defaultToolSet,
836
- ...defaults,
837
- }
838
- : defaults, {
839
- capabilities: resolvedModel.capabilities,
840
- ...(profileReasoningEffort ? { profileReasoningEffort } : {}),
841
- modeBudget,
842
- }),
1022
+ ...defaultConfig,
843
1023
  ...restInputConfig,
1024
+ responses: mainResponses,
844
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
+ : {}),
845
1047
  ...(activeMode.team?.maxDepth !== undefined ? { teamMaxDepth: activeMode.team.maxDepth } : {}),
846
1048
  ...(activeMode.team?.asyncCoordinator !== undefined
847
1049
  ? { teamAsyncCoordinator: activeMode.team.asyncCoordinator }
@@ -855,6 +1057,7 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
855
1057
  ...(activeMode.team?.maxActiveDepth1 !== undefined
856
1058
  ? { teamMaxActiveDepth1: activeMode.team.maxActiveDepth1 }
857
1059
  : {}),
1060
+ teamDefaultConcurrency: activeMode.team?.defaultConcurrency ?? defaultTeamConcurrency,
858
1061
  ...(activeMode.team?.maxConcurrency !== undefined
859
1062
  ? { teamMaxConcurrency: activeMode.team.maxConcurrency }
860
1063
  : {}),
@@ -955,7 +1158,7 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
955
1158
  if (state.status === 'failed') {
956
1159
  const { route, config: original, workingDirectory } = await store.environmentReader.load(runId);
957
1160
  if (original.modeRef && !matchesModeSelector(original.modeRef, activeMode.ref, availableModes))
958
- 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}`);
959
1162
  const terminal = (await store.receipt(`run:${runId}:terminal`))?.events.find((event) => event.type === 'run.failed');
960
1163
  const checkpoint = terminal?.payload.error.checkpoint;
961
1164
  if (!checkpoint)
@@ -977,7 +1180,9 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
977
1180
  content: originalInput.content,
978
1181
  },
979
1182
  }, identity, (config, role, agentSessionId) => role === 'worker'
980
- ? 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)
981
1186
  : config));
982
1187
  schedule(result.runId);
983
1188
  return { runId: result.runId, cursor: await store.head() };
@@ -1019,7 +1224,8 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
1019
1224
  case 'tool.reconcile': {
1020
1225
  const call = await store.toolReader.read(command.toolCallId);
1021
1226
  return withRun(call.runId, async () => {
1022
- 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);
1023
1229
  await maybeResume(call.runId, `reconcile:${commandId}:resume`);
1024
1230
  return {
1025
1231
  toolCallId: command.toolCallId,
@@ -1067,7 +1273,7 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
1067
1273
  return (await store.sessionList(command));
1068
1274
  case 'session.export': {
1069
1275
  const { platformCredentials, ...page } = await store.sessionExport(command);
1070
- const exportSecrets = [...secrets, ...platformCredentials];
1276
+ const exportSecrets = [...shared.secrets, ...platformCredentials];
1071
1277
  return {
1072
1278
  ...page,
1073
1279
  records: page.records.map((record) => ({
@@ -1165,7 +1371,14 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
1165
1371
  case 'run.timeline':
1166
1372
  return runTimeline(store, command);
1167
1373
  case 'surface.compact':
1168
- 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);
1169
1382
  case 'context.query': {
1170
1383
  const { route } = await environment.load(command.runId);
1171
1384
  const snapshot = await store.contextReader.read(route.agentSessionId, command.runId);