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

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.
@@ -171,10 +171,10 @@ function matchesScopeFilters(item, categorySet, idSet) {
171
171
 
172
172
  export default {
173
173
  id: 'ctf',
174
- version: '0.1.2-dev.6',
174
+ version: '0.1.2-dev.8',
175
175
  kind: 'saturn-registrar',
176
176
  apiVersion: 1,
177
- sdkVersion: '0.1.2-dev.6',
177
+ sdkVersion: '0.1.2-dev.8',
178
178
  async setup(api, config = {}) {
179
179
  const { boardToken, boardPublicHost, ...boardSettings } = settingsFor(config);
180
180
  if (boardToken) api.registerSecret?.(boardToken);
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "saturn-plugin-ctf",
3
- "version": "0.1.2-dev.6",
3
+ "version": "0.1.2-dev.8",
4
4
  "license": "AGPL-3.0-only",
5
5
  "type": "module",
6
6
  "main": "./index.mjs",
@@ -21,6 +21,7 @@ const commandLanes = {
21
21
  'run.steer': 'mutations',
22
22
  'run.submit': 'mutations',
23
23
  'session.create': 'mutations',
24
+ 'session.mode.select': 'mutations',
24
25
  'surface.compact': 'mutations',
25
26
  'tool.approval.resolve': 'mutations',
26
27
  'tool.reconcile': 'mutations',
@@ -1,4 +1,4 @@
1
- import type { HostProtocolRequest, JsonValue } from '@saturn-universe/core';
1
+ import type { SessionId, HostProtocolRequest, JsonValue } from '@saturn-universe/core';
2
2
  import type { SqliteStore } from '@saturn-universe/storage';
3
3
  import type { ContainerRunner } from '@saturn-universe/tools';
4
4
  import { createHostLogger } from './logger.js';
@@ -14,79 +14,43 @@ type RuntimeOptions = {
14
14
  hostPluginTimeoutMs?: number;
15
15
  };
16
16
  export declare function composeRuntime(store: SqliteStore, root: string, options?: RuntimeOptions, diagnosticDestination?: Parameters<typeof createHostLogger>[1]): Promise<{
17
- readonly status: {
18
- runDefaults?: {
19
- modeRef?: string;
20
- workerReasoningEffort?: string;
21
- reasoningEffort?: string;
22
- permissionMode?: "default" | "strict" | "full";
23
- };
24
- taskProfiles?: Readonly<Record<string, string>>;
25
- driverFailures: {
17
+ readonly status: Omit<import("@saturn-universe/protocol").HostStatusFields, "cursor" | "epoch"> & {
18
+ readonly configuredProfiles: number;
19
+ readonly plugins: {
20
+ id: string;
21
+ version: string;
22
+ kind: "saturn-registrar" | "cordis";
23
+ status: "active" | "draining";
24
+ }[];
25
+ readonly driverFailures: readonly {
26
26
  runId: string;
27
27
  code: string;
28
28
  diagnosticId: string;
29
29
  }[];
30
- mcpServers?: import("@saturn-universe/protocol").HostMcpServerSummary[];
31
- activeMode: {
30
+ };
31
+ recover: () => Promise<void>;
32
+ handle: (request: HostProtocolRequest, signal?: AbortSignal) => Promise<JsonValue> | Promise<Readonly<{
33
+ sessionId: SessionId;
34
+ mode: {
32
35
  ref: string;
33
36
  displayName: string;
34
37
  description: string;
35
38
  };
36
- availableModes: {
37
- ref: string;
38
- displayName: string;
39
- description: string;
40
- }[];
41
- modes: string[];
42
- skills: string[];
43
- discoveredSkills: readonly import("@saturn-universe/protocol").DiscoveredSkillSummary[];
44
- teamPresets: string[];
45
- boardUrl?: string;
46
- sandbox?: import("@saturn-universe/core").HostSandboxStatus;
47
- configSource: import("./host-configuration.js").ConfigSource;
48
- plugins: {
49
- id: string;
50
- version: string;
51
- kind: "saturn-registrar" | "cordis";
52
- status: "active" | "draining";
53
- }[];
54
- workspaceTools: boolean;
55
- profiles?: {
56
- ready: boolean;
57
- capabilityDigest: string;
58
- defaultReasoningEffort: string | null;
59
- contextWindow: number;
60
- reasoningModel: boolean;
61
- reasoningEfforts: string[];
62
- modelId: string;
63
- reasoningEffort?: string;
64
- name: string;
65
- providerId: string;
66
- revision: string;
67
- codecVersion: 1 | 2;
68
- protocol: "openai-responses" | "openai-chat" | "anthropic" | "gemini";
69
- baseURL: string;
70
- }[];
71
- selectedProfile?: string;
72
- defaultProfile?: string;
73
- configuredProfiles: number;
74
- };
75
- recover(): Promise<void>;
76
- handle(request: HostProtocolRequest, requestSignal?: AbortSignal): Promise<JsonValue>;
39
+ cursor: import("@saturn-universe/core").EventPosition;
40
+ }>>;
77
41
  reloadPlugins: () => Promise<{
78
42
  id: string;
79
43
  version: string;
80
44
  kind: "saturn-registrar" | "cordis";
81
45
  status: "active" | "draining";
82
46
  }[]>;
83
- reloadPlugin: (pluginId: string) => Promise<{
47
+ reloadPlugin: (id: string) => Promise<{
84
48
  id: string;
85
49
  version: string;
86
50
  kind: "saturn-registrar" | "cordis";
87
51
  status: "active" | "draining";
88
52
  }[]>;
89
- deactivatePlugin: (pluginId: string) => Promise<{
53
+ deactivatePlugin: (id: string) => Promise<{
90
54
  id: string;
91
55
  version: string;
92
56
  kind: "saturn-registrar" | "cordis";
@@ -104,6 +68,6 @@ export declare function composeRuntime(store: SqliteStore, root: string, options
104
68
  kind: "saturn-registrar" | "cordis";
105
69
  status: "active" | "draining";
106
70
  }[]>;
107
- close: () => Promise<void>;
71
+ close(): Promise<void>;
108
72
  }>;
109
73
  export {};
@@ -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,59 @@ 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
25
  import { resolveRunDefaults, resolveWorkerReasoning, hardLimits } from './provider-catalog.js';
24
26
  import { resolveWebSearchKey } from './user-config.js';
25
27
  export async function composeRuntime(store, root, options = {}, diagnosticDestination) {
28
+ const hostConfiguration = await loadHostConfiguration(root, options.configFile);
29
+ const { activeMode, availableModes } = resolveActiveMode(hostConfiguration.catalog, options.mode);
30
+ const secrets = [];
31
+ const logger = createHostLogger(secrets, diagnosticDestination);
32
+ const processManager = createProcessManager({
33
+ directory: path.join(root, '.saturn', 'processes'),
34
+ async getRunDeadline(runId) {
35
+ const state = await store.stateReader.run(runId);
36
+ return state.deadlineAt ? Date.parse(state.deadlineAt) : undefined;
37
+ },
38
+ onRecordError: (processId) => logger.error({ code: 'PROCESS_RECORD_INVALID', processId }, 'Skipped an invalid process journal; the reservation will not be restarted'),
39
+ });
40
+ // Container ownership labels belong to the workspace. A later Mode mount must
41
+ // not run startup orphan cleanup against other scopes' live containers.
42
+ let sandboxCleanup;
43
+ const dependencies = {
44
+ commit: store,
45
+ reader: store,
46
+ receipt: (id, hash) => store.receipt(id, hash),
47
+ hash: (value) => createHash('sha256').update(canonicalJson(value)).digest('hex'),
48
+ now: () => new Date().toISOString(),
49
+ id: randomUUID,
50
+ epoch: store.epoch,
51
+ rootUri: pathToFileURL(root).href,
52
+ };
53
+ const shared = {
54
+ hostConfiguration,
55
+ dependencies,
56
+ journal: createRuntimeJournal({ ...dependencies, stateReader: store.stateReader }),
57
+ liveProgress: createLiveText(),
58
+ processManager,
59
+ secrets,
60
+ cleanupSandboxOrphans: (cleanup) => (sandboxCleanup ??= cleanup()),
61
+ };
62
+ return createSessionModeRuntime({
63
+ store,
64
+ activeMode,
65
+ availableModes,
66
+ processManager,
67
+ logger,
68
+ mount: (mode, workers, plugins) => composeModeRuntime(store, root, { ...options, mode }, diagnosticDestination, shared, workers, plugins),
69
+ });
70
+ }
71
+ async function composeModeRuntime(store, root, options, diagnosticDestination, shared, workers, plugins) {
26
72
  const resources = {};
27
73
  try {
28
- return await assembleRuntime(resources, store, root, options, diagnosticDestination);
74
+ return await assembleRuntime(resources, store, root, options, diagnosticDestination, shared, workers, plugins);
29
75
  }
30
76
  catch (error) {
31
77
  try {
@@ -36,9 +82,9 @@ export async function composeRuntime(store, root, options = {}, diagnosticDestin
36
82
  }
37
83
  }
38
84
  }
39
- async function assembleRuntime(resources, store, root, options, diagnosticDestination) {
85
+ async function assembleRuntime(resources, store, root, options, diagnosticDestination, shared, workers, plugins) {
40
86
  const readConfiguration = () => loadHostConfiguration(root, options.configFile);
41
- const hostConfiguration = await readConfiguration();
87
+ const hostConfiguration = shared.hostConfiguration;
42
88
  const { catalog, configSource, trustedMcp, mcpServers, mcpServerMeta, mcpJsonError } = hostConfiguration;
43
89
  const credentialMap = await resolveCredentialMap(root);
44
90
  const entryProfile = options.profile ?? process.env.SATURN_PROVIDER_PROFILE;
@@ -66,12 +112,16 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
66
112
  }
67
113
  const toolLayers = resolveModeToolLayers(activeMode, catalog?.workspaceTools);
68
114
  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);
115
+ for (const secret of secrets)
116
+ if (!shared.secrets.includes(secret))
117
+ shared.secrets.push(secret);
118
+ const externalPlugins = plugins ?? (await loadModePlugins(activeMode, hostConfiguration, logger));
70
119
  const pluginStatuses = new Map();
71
120
  const skillService = await createSkillRegistryService(root, activeMode, catalog);
72
- const hash = (value) => createHash('sha256').update(canonicalJson(value)).digest('hex');
121
+ const { dependencies, journal, liveProgress } = shared;
122
+ const { hash, now } = dependencies;
73
123
  const clock = {
74
- now: () => new Date().toISOString(),
124
+ now,
75
125
  async delay(ms, signal) {
76
126
  signal.throwIfAborted();
77
127
  let timer;
@@ -114,6 +164,7 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
114
164
  ...(options.hostPluginTimeoutMs !== undefined ? { timeoutMs: options.hostPluginTimeoutMs } : {}),
115
165
  activeMode,
116
166
  sandbox: {
167
+ cleanupOrphans: shared.cleanupSandboxOrphans,
117
168
  ...(options.allowUnsafeSandboxFallback ? { allowUnsafeFallback: true } : {}),
118
169
  ...(options.sandboxRunner ? { runner: options.sandboxRunner } : {}),
119
170
  },
@@ -125,6 +176,8 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
125
176
  registerSecret(value) {
126
177
  if (value.trim() && !secrets.includes(value))
127
178
  secrets.push(value);
179
+ if (value.trim() && !shared.secrets.includes(value))
180
+ shared.secrets.push(value);
128
181
  },
129
182
  redactValue(value) {
130
183
  return redactExportValue(value, secrets);
@@ -202,13 +255,8 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
202
255
  hash,
203
256
  resultReader: createToolResultReader(store.toolReader),
204
257
  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
- },
258
+ sharedProcessManager: shared.processManager,
259
+ resolveWorkerModeRef: (selector) => resolveModeSelector(selector, availableModes)?.ref,
212
260
  previousDataReview: (runId) => store.hasNumericReview(runId),
213
261
  stopMember: (ctx, memberId, reason) => {
214
262
  if (!stopMemberImpl)
@@ -243,19 +291,7 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
243
291
  const { gateway, resolveFrozenModel } = saturnModel;
244
292
  const { composer } = saturnContext;
245
293
  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
294
  const admission = createCommandHandler(dependencies);
258
- const journal = createRuntimeJournal(dependencies);
259
295
  async function checkWorkingDirectory(uri) {
260
296
  let working;
261
297
  try {
@@ -361,8 +397,16 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
361
397
  ...turns.map(({ agentSessionId }) => agentSessionId),
362
398
  ]);
363
399
  others.delete(route.agentSessionId);
364
- for (const agentSessionId of others)
365
- await verifyConfigVersions((await environment.load(runId, agentSessionId)).config);
400
+ const team = await store.stateReader.team?.(runId);
401
+ for (const agentSessionId of others) {
402
+ const { config } = await environment.load(runId, agentSessionId);
403
+ const member = team?.members.find((member) => member.agentSessionId === agentSessionId);
404
+ if (config.modeRef !== activeMode.ref &&
405
+ member &&
406
+ ['completed', 'failed', 'interrupted', 'stopped'].includes(member.status))
407
+ continue;
408
+ await (await workerRuntime(runId, agentSessionId, config.modeRef)).verify(config);
409
+ }
366
410
  for (const turn of turns) {
367
411
  for (const call of await store.toolReader.pending(turn.id)) {
368
412
  if (call.definition &&
@@ -370,11 +414,10 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
370
414
  call.approval?.status === 'approved' ||
371
415
  call.status === 'running' ||
372
416
  call.status === 'outcome_unknown'))
373
- await registry.resolveFrozen(call.definition);
417
+ await (await workerRuntime(runId, call.agentSessionId)).verifyTool(call.definition);
374
418
  }
375
419
  }
376
420
  }
377
- const liveProgress = createLiveText();
378
421
  const agent = createAgentLoop({
379
422
  logger,
380
423
  environment,
@@ -400,19 +443,57 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
400
443
  id: randomUUID,
401
444
  signal: stop.signal,
402
445
  });
403
- const loop = createRunLoop({
404
- ...dependencies,
405
- journal,
406
- state: store.stateReader,
407
- environment,
446
+ const worker = {
408
447
  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) => {
448
+ executor,
449
+ verify: verifyConfigVersions,
450
+ verifyTool: (definition) => registry.resolveFrozen(definition),
451
+ async freeze(parent, team, agentSessionId, depth) {
452
+ let config = parent;
453
+ const capabilities = resolveFrozenModel(parent).capabilities;
454
+ if (parent.modeRef !== activeMode.ref) {
455
+ const { contextExtensions: _context, pluginBindings, toolSnapshot: _snapshot, workerSoftCheckpointMs: _checkpoint, ...base } = parent;
456
+ const defaults = resolveRunDefaults(parent.model, catalog?.runDefaults, { modeBudget, capabilities });
457
+ const { wallTimeMs: modeWallTime, ...modeLimits } = defaults.limits;
458
+ const limits = {
459
+ ...modeLimits,
460
+ ...(parent.limits.wallTimeMs !== undefined ? { wallTimeMs: parent.limits.wallTimeMs } : {}),
461
+ };
462
+ for (const key of ['maxModelAttempts', 'maxToolCalls', 'maxSteps', 'maxTotalTokens']) {
463
+ const parentLimit = parent.limits[key];
464
+ if (isLimited(parentLimit))
465
+ limits[key] = isLimited(limits[key]) ? Math.min(limits[key], parentLimit) : parentLimit;
466
+ }
467
+ if (isLimited(modeWallTime)) {
468
+ const limit = limits.subagentWallTimeMs;
469
+ limits.subagentWallTimeMs = isLimited(limit) ? Math.min(limit, modeWallTime) : modeWallTime;
470
+ }
471
+ config = {
472
+ ...base,
473
+ modeRef: activeMode.ref,
474
+ toolSetVersion: tools.defaultVersion(capabilities),
475
+ teamMaxDepth: Math.min(parent.teamMaxDepth ?? 1, activeMode.team?.maxDepth ?? 1),
476
+ ...(activeMode.team?.workerSoftCheckpointMs !== undefined
477
+ ? { workerSoftCheckpointMs: activeMode.team.workerSoftCheckpointMs }
478
+ : {}),
479
+ ...(toolLayers.permissionMode
480
+ ? { policyVersion: interactiveToolPolicies[toolLayers.permissionMode] }
481
+ : {}),
482
+ limits,
483
+ ...(await freezeContextExtensions(root, activeMode, catalog?.skills)),
484
+ };
485
+ const { bindings } = freezeContributions(config, { role: 'worker', agentSessionId });
486
+ config = {
487
+ ...config,
488
+ pluginBindings: {
489
+ ...bindings,
490
+ ...(pluginBindings?.modelProvider ? { modelProvider: pluginBindings.modelProvider } : {}),
491
+ },
492
+ };
493
+ }
494
+ return tools.freezeWorker(config, team, agentSessionId, capabilities, { depth });
495
+ },
496
+ start: async (workerInput) => {
416
497
  const workerEnv = await environment.load(workerInput.runId, workerInput.agentSessionId);
417
498
  const sessionId = workerEnv.route.sessionId;
418
499
  if (saturnSandbox)
@@ -426,7 +507,7 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
426
507
  ...(workerInput.workSubpath !== undefined ? { workSubpath: workerInput.workSubpath } : {}),
427
508
  });
428
509
  },
429
- onWorkerComplete: async (workerInput) => {
510
+ complete: async (workerInput) => {
430
511
  const workerEnv = await environment
431
512
  .load(workerInput.runId, workerInput.agentSessionId)
432
513
  .catch(() => undefined);
@@ -472,6 +553,69 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
472
553
  ...(usage ? { usage } : {}),
473
554
  });
474
555
  },
556
+ };
557
+ async function workerRuntime(runId, agentSessionId, modeRef) {
558
+ const selector = modeRef ?? (await environment.load(runId, agentSessionId)).config.modeRef;
559
+ const ref = resolveModeSelector(selector, availableModes)?.ref;
560
+ if (!ref && selector.includes('@'))
561
+ throw new RuntimeError('PLUGIN_VERSION_UNAVAILABLE', `Worker Mode ${selector} is unavailable`);
562
+ return ref && ref !== activeMode.ref ? workers.acquire(ref, runId, agentSessionId) : worker;
563
+ }
564
+ function freezeWorker(runId, parent, team, agentSessionId, member) {
565
+ let selector = member.modeRef;
566
+ let depth = (parent.agentDepth ?? 0) + 1;
567
+ let ancestor = team.members.find(({ id }) => id === member.parent);
568
+ while (ancestor) {
569
+ selector ??= ancestor.modeRef;
570
+ depth++;
571
+ const ancestorParent = ancestor.parent;
572
+ ancestor = team.members.find(({ id }) => id === ancestorParent);
573
+ }
574
+ const ref = selector ? resolveModeSelector(selector, availableModes)?.ref : parent.modeRef;
575
+ if (!ref)
576
+ throw new RuntimeError('INVALID_TEAM_CONFIG', `Unknown worker Mode: ${selector}`);
577
+ return workerRuntime(runId, agentSessionId, ref).then((runtime) => runtime.freeze(parent, team, agentSessionId, depth));
578
+ }
579
+ const loop = createRunLoop({
580
+ ...dependencies,
581
+ journal,
582
+ state: store.stateReader,
583
+ environment,
584
+ agent: {
585
+ ...agent,
586
+ async resume(input, signal) {
587
+ return (await workerRuntime(input.runId, input.agentSessionId)).agent.resume(input, signal);
588
+ },
589
+ async steer(agentSessionId, commandId, command) {
590
+ return (await workerRuntime(command.runId, agentSessionId)).agent.steer(agentSessionId, commandId, command);
591
+ },
592
+ },
593
+ tools: store.toolReader,
594
+ surface: store.surfaceReader,
595
+ freezeWorkerConfig: freezeWorker,
596
+ verifyPluginVersions: verifyRunVersions,
597
+ completionPolicy: createContinuationCompletionPolicy({ semanticJudge }),
598
+ createCheckpoint: (input, prior) => createRunCheckpoint(store.surfaceReader, input, prior),
599
+ async onWorkerStart(input) {
600
+ const { parentAgentSessionId, ...details } = input;
601
+ const runtime = await workerRuntime(input.runId, input.agentSessionId);
602
+ const sameParentMode = parentAgentSessionId &&
603
+ (await environment.load(input.runId, parentAgentSessionId)).config.modeRef ===
604
+ (await environment.load(input.runId, input.agentSessionId)).config.modeRef;
605
+ await runtime.start({ ...details, ...(sameParentMode ? { parentAgentSessionId } : {}) });
606
+ },
607
+ async onWorkerComplete(input) {
608
+ try {
609
+ const { config } = await environment.load(input.runId, input.agentSessionId);
610
+ const runtime = matchesModeSelector(config.modeRef, activeMode.ref, availableModes)
611
+ ? worker
612
+ : workers.find(input.runId, input.agentSessionId);
613
+ await runtime?.complete(input);
614
+ }
615
+ finally {
616
+ await workers.release(input.runId, input.agentSessionId);
617
+ }
618
+ },
475
619
  });
476
620
  steerMemberImpl = loop.steerMember;
477
621
  stopMemberImpl = loop.stopMember;
@@ -481,7 +625,9 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
481
625
  await journal.append(`team:${runId}:notify:${messageId}`, [
482
626
  journal.event('run.team.message.sent', scope, { messageId, from, to, text }),
483
627
  ]);
484
- void loop.wakeTeam(runId);
628
+ void workers
629
+ .wake(runId)
630
+ .catch((error) => reportDiagnostic(logger, error, randomUUID(), 'TEAM_WAKE_FAILED', { runId }));
485
631
  };
486
632
  syncWorkspaceSubpathsImpl = async ({ runId, sessionId }, subpaths) => {
487
633
  if (!saturnSandbox || !subpaths.length)
@@ -496,6 +642,7 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
496
642
  let closing = false;
497
643
  let closeTask;
498
644
  async function cleanupRunProcesses(runId, terminalStatus) {
645
+ await workers.release(runId);
499
646
  executor.clearFileSnapshots(runId);
500
647
  const processes = await processManager?.stopRun(runId);
501
648
  for (const process of processes ?? []) {
@@ -620,13 +767,22 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
620
767
  state: store.stateReader,
621
768
  environment,
622
769
  tools: store.toolReader,
623
- executor,
770
+ executor: {
771
+ async executeBatch(input) {
772
+ return (await workerRuntime(input.runId, input.agentSessionId)).executor.executeBatch(input);
773
+ },
774
+ async recover(input) {
775
+ return (await workerRuntime(input.runId, input.agentSessionId)).executor.recover(input);
776
+ },
777
+ },
624
778
  clock,
625
779
  hash,
626
780
  loop,
627
781
  signal: stop.signal,
628
782
  }, schedule, runIds);
629
783
  }
784
+ let stopRunsTask;
785
+ const stopRuns = () => (stopRunsTask ??= loop.stop());
630
786
  async function shutdown() {
631
787
  closing = true;
632
788
  const stopLifecycle = lifecycle.stop();
@@ -634,7 +790,7 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
634
790
  clearTimeout(timer);
635
791
  deadlines.clear();
636
792
  try {
637
- await loop.stop();
793
+ await stopRuns();
638
794
  }
639
795
  finally {
640
796
  stop.abort();
@@ -727,24 +883,11 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
727
883
  : {}),
728
884
  };
729
885
  },
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
- },
886
+ recoverRuns,
887
+ stopRuns,
888
+ wakeTeam: loop.wakeTeam,
889
+ worker,
890
+ activePlugins: () => lifecycle.activePlugins(),
748
891
  handle(request, requestSignal) {
749
892
  if (closing)
750
893
  return Promise.reject(new RuntimeError('HOST_CLOSING', 'Host is shutting down'));
@@ -763,6 +906,8 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
763
906
  async function handle(request, requestSignal) {
764
907
  const { command, commandId } = request;
765
908
  switch (command.type) {
909
+ case 'session.mode.select':
910
+ throw new RuntimeError('UNSUPPORTED', 'Session Mode selection belongs to the Host');
766
911
  case 'run.submit': {
767
912
  return lifecycle.withAdmission(async () => {
768
913
  const identity = { version: 2, hash: hash({ version: 2, command }) };
@@ -786,12 +931,13 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
786
931
  const defaults = catalog?.runDefaults;
787
932
  const defaultToolSet = tools.defaultVersion(resolvedModel.capabilities);
788
933
  let team = input.config?.team;
789
- if (input.teamPreset !== undefined) {
934
+ const presetName = input.teamPreset ?? (team === undefined ? activeMode.team?.defaultPreset : undefined);
935
+ if (presetName !== undefined) {
790
936
  if (input.config?.team !== undefined)
791
937
  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];
938
+ if (!catalog?.teamPresets || !Object.hasOwn(catalog.teamPresets, presetName))
939
+ throw new RuntimeError('INVALID_CONFIG', `Unknown team preset "${presetName}"${input.teamPreset === undefined ? ` configured as team.default_preset for Mode ${activeMode.ref}` : ''}`);
940
+ const preset = catalog.teamPresets[presetName];
795
941
  const userPrompt = input.content
796
942
  .flatMap((part) => (part.type === 'text' ? [part.text] : []))
797
943
  .join('\n')
@@ -811,7 +957,9 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
811
957
  if (team && teamHint)
812
958
  throw new RuntimeError('INVALID_CONFIG', 'team and teamHint are mutually exclusive');
813
959
  if (team) {
814
- validateTeamConfig(team);
960
+ validateTeamConfig(team, activeMode.team?.maxDepth !== undefined ? { maxDepth: activeMode.team.maxDepth } : undefined);
961
+ if (team.members.some(({ modeRef }) => modeRef !== undefined))
962
+ throw new RuntimeError('INVALID_TEAM_CONFIG', 'Team member modeRef is supported by spawn_team');
815
963
  if (activeMode.ref === 'ctf@1' || activeMode.ref.startsWith('ctf@')) {
816
964
  for (const member of team.members) {
817
965
  if (member.parent !== 'main')
@@ -826,7 +974,7 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
826
974
  validateTeamHintConfig(teamHint);
827
975
  if (input.config?.modeRef !== undefined &&
828
976
  !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}`);
977
+ throw new RuntimeError('MODE_MISMATCH', `Session is using mode ${activeMode.ref}; cannot submit run for mode ${input.config.modeRef}`);
830
978
  const { planner: _ignoredPlanner, ...restInputConfig } = input.config ?? {};
831
979
  const effectivePermissionMode = input.permissionMode ?? toolLayers.permissionMode ?? defaults?.permission_mode;
832
980
  const selectedConfig = {
@@ -855,6 +1003,7 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
855
1003
  ...(activeMode.team?.maxActiveDepth1 !== undefined
856
1004
  ? { teamMaxActiveDepth1: activeMode.team.maxActiveDepth1 }
857
1005
  : {}),
1006
+ teamDefaultConcurrency: activeMode.team?.defaultConcurrency ?? defaultTeamConcurrency,
858
1007
  ...(activeMode.team?.maxConcurrency !== undefined
859
1008
  ? { teamMaxConcurrency: activeMode.team.maxConcurrency }
860
1009
  : {}),
@@ -955,7 +1104,7 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
955
1104
  if (state.status === 'failed') {
956
1105
  const { route, config: original, workingDirectory } = await store.environmentReader.load(runId);
957
1106
  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}`);
1107
+ throw new RuntimeError('MODE_MISMATCH', `Session is using mode ${activeMode.ref}; checkpoint run belongs to mode ${original.modeRef}`);
959
1108
  const terminal = (await store.receipt(`run:${runId}:terminal`))?.events.find((event) => event.type === 'run.failed');
960
1109
  const checkpoint = terminal?.payload.error.checkpoint;
961
1110
  if (!checkpoint)
@@ -1019,7 +1168,8 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
1019
1168
  case 'tool.reconcile': {
1020
1169
  const call = await store.toolReader.read(command.toolCallId);
1021
1170
  return withRun(call.runId, async () => {
1022
- await executor.reconcile(command.toolCallId, command.decision, commandId);
1171
+ const runtime = await workerRuntime(call.runId, call.agentSessionId);
1172
+ await runtime.executor.reconcile(command.toolCallId, command.decision, commandId);
1023
1173
  await maybeResume(call.runId, `reconcile:${commandId}:resume`);
1024
1174
  return {
1025
1175
  toolCallId: command.toolCallId,
@@ -1067,7 +1217,7 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
1067
1217
  return (await store.sessionList(command));
1068
1218
  case 'session.export': {
1069
1219
  const { platformCredentials, ...page } = await store.sessionExport(command);
1070
- const exportSecrets = [...secrets, ...platformCredentials];
1220
+ const exportSecrets = [...shared.secrets, ...platformCredentials];
1071
1221
  return {
1072
1222
  ...page,
1073
1223
  records: page.records.map((record) => ({
@@ -1165,7 +1315,14 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
1165
1315
  case 'run.timeline':
1166
1316
  return runTimeline(store, command);
1167
1317
  case 'surface.compact':
1168
- return compactSurface({ ...dependencies, environment, surfaceReader: store.surfaceReader, gateway, logger }, commandId, command);
1318
+ return compactSurface({
1319
+ ...dependencies,
1320
+ environment,
1321
+ stateReader: store.stateReader,
1322
+ surfaceReader: store.surfaceReader,
1323
+ gateway,
1324
+ logger,
1325
+ }, commandId, command);
1169
1326
  case 'context.query': {
1170
1327
  const { route } = await environment.load(command.runId);
1171
1328
  const snapshot = await store.contextReader.read(route.agentSessionId, command.runId);