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

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.7',
175
175
  kind: 'saturn-registrar',
176
176
  apiVersion: 1,
177
- sdkVersion: '0.1.2-dev.6',
177
+ sdkVersion: '0.1.2-dev.7',
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.7",
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 path from 'node:path';
4
5
  import { RuntimeError, canonicalJson, configForDerivedAgent, earlierDeadline, isTerminalRunStatus, matchesModeSelector, normalizeFileUriForPlatform, reportDiagnostic, 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,46 @@ 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 shared = {
44
+ hostConfiguration,
45
+ processManager,
46
+ secrets,
47
+ cleanupSandboxOrphans: (cleanup) => (sandboxCleanup ??= cleanup()),
48
+ };
49
+ return createSessionModeRuntime({
50
+ store,
51
+ activeMode,
52
+ availableModes,
53
+ processManager,
54
+ logger,
55
+ mount: (mode, plugins) => composeModeRuntime(store, root, { ...options, mode }, diagnosticDestination, shared, plugins),
56
+ });
57
+ }
58
+ async function composeModeRuntime(store, root, options, diagnosticDestination, shared, plugins) {
26
59
  const resources = {};
27
60
  try {
28
- return await assembleRuntime(resources, store, root, options, diagnosticDestination);
61
+ return await assembleRuntime(resources, store, root, options, diagnosticDestination, shared, plugins);
29
62
  }
30
63
  catch (error) {
31
64
  try {
@@ -36,9 +69,9 @@ export async function composeRuntime(store, root, options = {}, diagnosticDestin
36
69
  }
37
70
  }
38
71
  }
39
- async function assembleRuntime(resources, store, root, options, diagnosticDestination) {
72
+ async function assembleRuntime(resources, store, root, options, diagnosticDestination, shared, plugins) {
40
73
  const readConfiguration = () => loadHostConfiguration(root, options.configFile);
41
- const hostConfiguration = await readConfiguration();
74
+ const hostConfiguration = shared.hostConfiguration;
42
75
  const { catalog, configSource, trustedMcp, mcpServers, mcpServerMeta, mcpJsonError } = hostConfiguration;
43
76
  const credentialMap = await resolveCredentialMap(root);
44
77
  const entryProfile = options.profile ?? process.env.SATURN_PROVIDER_PROFILE;
@@ -66,7 +99,10 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
66
99
  }
67
100
  const toolLayers = resolveModeToolLayers(activeMode, catalog?.workspaceTools);
68
101
  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);
102
+ for (const secret of secrets)
103
+ if (!shared.secrets.includes(secret))
104
+ shared.secrets.push(secret);
105
+ const externalPlugins = plugins ?? (await loadModePlugins(activeMode, hostConfiguration, logger));
70
106
  const pluginStatuses = new Map();
71
107
  const skillService = await createSkillRegistryService(root, activeMode, catalog);
72
108
  const hash = (value) => createHash('sha256').update(canonicalJson(value)).digest('hex');
@@ -114,6 +150,7 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
114
150
  ...(options.hostPluginTimeoutMs !== undefined ? { timeoutMs: options.hostPluginTimeoutMs } : {}),
115
151
  activeMode,
116
152
  sandbox: {
153
+ cleanupOrphans: shared.cleanupSandboxOrphans,
117
154
  ...(options.allowUnsafeSandboxFallback ? { allowUnsafeFallback: true } : {}),
118
155
  ...(options.sandboxRunner ? { runner: options.sandboxRunner } : {}),
119
156
  },
@@ -125,6 +162,8 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
125
162
  registerSecret(value) {
126
163
  if (value.trim() && !secrets.includes(value))
127
164
  secrets.push(value);
165
+ if (value.trim() && !shared.secrets.includes(value))
166
+ shared.secrets.push(value);
128
167
  },
129
168
  redactValue(value) {
130
169
  return redactExportValue(value, secrets);
@@ -202,13 +241,7 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
202
241
  hash,
203
242
  resultReader: createToolResultReader(store.toolReader),
204
243
  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
- },
244
+ sharedProcessManager: shared.processManager,
212
245
  previousDataReview: (runId) => store.hasNumericReview(runId),
213
246
  stopMember: (ctx, memberId, reason) => {
214
247
  if (!stopMemberImpl)
@@ -727,24 +760,8 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
727
760
  : {}),
728
761
  };
729
762
  },
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
- },
763
+ recoverRuns,
764
+ activePlugins: () => lifecycle.activePlugins(),
748
765
  handle(request, requestSignal) {
749
766
  if (closing)
750
767
  return Promise.reject(new RuntimeError('HOST_CLOSING', 'Host is shutting down'));
@@ -763,6 +780,8 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
763
780
  async function handle(request, requestSignal) {
764
781
  const { command, commandId } = request;
765
782
  switch (command.type) {
783
+ case 'session.mode.select':
784
+ throw new RuntimeError('UNSUPPORTED', 'Session Mode selection belongs to the Host');
766
785
  case 'run.submit': {
767
786
  return lifecycle.withAdmission(async () => {
768
787
  const identity = { version: 2, hash: hash({ version: 2, command }) };
@@ -826,7 +845,7 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
826
845
  validateTeamHintConfig(teamHint);
827
846
  if (input.config?.modeRef !== undefined &&
828
847
  !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}`);
848
+ throw new RuntimeError('MODE_MISMATCH', `Session is using mode ${activeMode.ref}; cannot submit run for mode ${input.config.modeRef}`);
830
849
  const { planner: _ignoredPlanner, ...restInputConfig } = input.config ?? {};
831
850
  const effectivePermissionMode = input.permissionMode ?? toolLayers.permissionMode ?? defaults?.permission_mode;
832
851
  const selectedConfig = {
@@ -955,7 +974,7 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
955
974
  if (state.status === 'failed') {
956
975
  const { route, config: original, workingDirectory } = await store.environmentReader.load(runId);
957
976
  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}`);
977
+ throw new RuntimeError('MODE_MISMATCH', `Session is using mode ${activeMode.ref}; checkpoint run belongs to mode ${original.modeRef}`);
959
978
  const terminal = (await store.receipt(`run:${runId}:terminal`))?.events.find((event) => event.type === 'run.failed');
960
979
  const checkpoint = terminal?.payload.error.checkpoint;
961
980
  if (!checkpoint)
@@ -1067,7 +1086,7 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
1067
1086
  return (await store.sessionList(command));
1068
1087
  case 'session.export': {
1069
1088
  const { platformCredentials, ...page } = await store.sessionExport(command);
1070
- const exportSecrets = [...secrets, ...platformCredentials];
1089
+ const exportSecrets = [...shared.secrets, ...platformCredentials];
1071
1090
  return {
1072
1091
  ...page,
1073
1092
  records: page.records.map((record) => ({
@@ -25,6 +25,7 @@ export declare class PluginLifecycle {
25
25
  kind: "saturn-registrar" | "cordis";
26
26
  status: "active" | "draining";
27
27
  }[];
28
+ activePlugins(): LoadedHostPlugin[];
28
29
  withAdmission<T>(work: () => Promise<T>): Promise<T>;
29
30
  trackRun(runId: RunId): () => void;
30
31
  replace(load: (active: ReadonlyMap<string, LoadedHostPlugin>) => Promise<readonly LoadedHostPlugin[]>, pluginId?: string): Promise<{
@@ -51,6 +51,9 @@ export class PluginLifecycle {
51
51
  ...[...this.draining].map((generation) => summary(generation, 'draining')),
52
52
  ].sort((a, b) => a.id.localeCompare(b.id));
53
53
  }
54
+ activePlugins() {
55
+ return [...this.active.values()].map(({ plugin }) => plugin);
56
+ }
54
57
  withAdmission(work) {
55
58
  return this.enqueue(work);
56
59
  }
@@ -10,6 +10,7 @@ declare module '@deepseek-ai/cordis' {
10
10
  export interface SandboxPluginOptions {
11
11
  readonly allowUnsafeFallback?: boolean;
12
12
  readonly runner?: ContainerRunner;
13
+ readonly cleanupOrphans?: (cleanup: () => Promise<void>) => Promise<void>;
13
14
  }
14
15
  export declare function createSandboxPlugin(root: string, activeMode: ModeDefinition, options?: SandboxPluginOptions): {
15
16
  name: string;
@@ -10,6 +10,7 @@ export function createSandboxPlugin(root, activeMode, options = {}) {
10
10
  logger: ctx.saturnPluginHost.logger,
11
11
  ...(options.allowUnsafeFallback ? { allowUnsafeFallback: true } : {}),
12
12
  ...(options.runner ? { runner: options.runner } : {}),
13
+ ...(options.cleanupOrphans ? { cleanupOrphans: options.cleanupOrphans } : {}),
13
14
  });
14
15
  await manager.activate(startupSignal);
15
16
  ctx.effect(() => async () => {
@@ -1,5 +1,5 @@
1
1
  import type { RunId, ToolBinding } from '@saturn-universe/core';
2
- import type { ProcessManagerOptions, TeamMemberAction, TeamNotifyParentDelivery } from '@saturn-universe/tools';
2
+ import type { ProcessManager, ProcessManagerOptions, TeamMemberAction, TeamNotifyParentDelivery } from '@saturn-universe/tools';
3
3
  import type { SkillRegistryService } from '../../skills-runtime.js';
4
4
  import type { RequiredHostPlugin } from '../required-host-plugin.js';
5
5
  import type { ToolConfiguration } from './tools-core-plugin.js';
@@ -9,6 +9,7 @@ export interface HostToolOptions {
9
9
  hash: (value: unknown) => string;
10
10
  resultReader?: ToolBinding;
11
11
  processManager?: Omit<ProcessManagerOptions, 'directory'>;
12
+ sharedProcessManager?: ProcessManager;
12
13
  previousDataReview?: (runId: RunId) => Promise<boolean>;
13
14
  suppressedGuidanceRoles?: ReadonlySet<'main' | 'worker'>;
14
15
  skillService?: SkillRegistryService;
@@ -4,7 +4,7 @@ import { createProcessManagerPlugin } from './process-manager-plugin.js';
4
4
  import { createToolsCorePlugin } from './tools-core-plugin.js';
5
5
  import { createWorkspaceToolsPlugin } from './workspace-tools-plugin.js';
6
6
  export function createToolPlugins(root, options, startupDependencies = [], withContext = false) {
7
- const { config, trustedConfig, hash, resultReader, processManager, previousDataReview, suppressedGuidanceRoles, skillService, notifyParent, steerMember, stopMember, } = options;
7
+ const { config, trustedConfig, hash, resultReader, processManager, sharedProcessManager, previousDataReview, suppressedGuidanceRoles, skillService, notifyParent, steerMember, stopMember, } = options;
8
8
  const effectiveWorkspaceTools = Boolean(config.workspaceTools);
9
9
  const effectiveProcessManager = config.processManager ?? effectiveWorkspaceTools;
10
10
  const effectiveBuiltinAgentTools = config.builtinAgentTools !== false;
@@ -16,7 +16,7 @@ export function createToolPlugins(root, options, startupDependencies = [], withC
16
16
  ...(effectiveProcessManager
17
17
  ? [
18
18
  guidanceOwner({
19
- ...createProcessManagerPlugin(root, processManager ?? {}),
19
+ ...createProcessManagerPlugin(root, processManager ?? {}, sharedProcessManager),
20
20
  inject: [...startupDependencies, 'saturnTools'],
21
21
  }),
22
22
  ]
@@ -5,7 +5,7 @@ declare module '@deepseek-ai/cordis' {
5
5
  saturnProcessManager?: ProcessManager;
6
6
  }
7
7
  }
8
- export declare function createProcessManagerPlugin(root: string, options: Omit<ProcessManagerOptions, 'directory'>): {
8
+ export declare function createProcessManagerPlugin(root: string, options: Omit<ProcessManagerOptions, 'directory'>, shared?: ProcessManager): {
9
9
  name: string;
10
10
  apply(ctx: Context): void;
11
11
  };
@@ -21,17 +21,17 @@ function processGuidance(visible) {
21
21
  'A timeout or unknown result does not prove the process stopped. Check any existing handle and actual side effects before retrying. Never launch a blind duplicate.',
22
22
  ].join('\n');
23
23
  }
24
- export function createProcessManagerPlugin(root, options) {
24
+ export function createProcessManagerPlugin(root, options, shared) {
25
25
  return {
26
26
  name: 'process-manager',
27
27
  apply(ctx) {
28
- const manager = createProcessManager({
29
- ...options,
30
- directory: path.join(root, '.saturn', 'processes'),
31
- });
32
- ctx.effect(() => async () => {
33
- await manager.close();
34
- });
28
+ const manager = shared ??
29
+ createProcessManager({
30
+ ...options,
31
+ directory: path.join(root, '.saturn', 'processes'),
32
+ });
33
+ if (!shared)
34
+ ctx.effect(() => () => manager.close());
35
35
  ctx.provide('saturnProcessManager', manager);
36
36
  registerToolGuidance(ctx, 'process-tool-guidance', -20, processGuidance);
37
37
  },
package/dist/index.js CHANGED
@@ -133,7 +133,7 @@ function failure(requestId, error) {
133
133
  code: error instanceof RuntimeError ? error.code : 'INTERNAL',
134
134
  message: `Command failed [diagnosticId: ${randomUUID()}]`,
135
135
  retryable: error instanceof RuntimeError &&
136
- ['VERSION_CONFLICT', 'STORAGE_BUSY', 'HOST_BUSY'].includes(error.code),
136
+ ['VERSION_CONFLICT', 'STORAGE_BUSY', 'HOST_BUSY', 'SESSION_BUSY'].includes(error.code),
137
137
  },
138
138
  };
139
139
  }
@@ -4,6 +4,7 @@ export interface SandboxMetaRecord {
4
4
  readonly version: 1;
5
5
  readonly workspaceRoot: string;
6
6
  readonly workspaceHash: string;
7
+ readonly modeRef?: string;
7
8
  readonly sessionId?: string;
8
9
  readonly runId: string;
9
10
  readonly role: 'main' | 'worker' | 'target';
@@ -44,6 +45,7 @@ export interface SandboxManagerOptions {
44
45
  readonly allowUnsafeFallback?: boolean;
45
46
  readonly runner?: ContainerRunner;
46
47
  readonly checkKvmAvailable?: () => boolean;
48
+ readonly cleanupOrphans?: (cleanup: () => Promise<void>) => Promise<void>;
47
49
  }
48
50
  export interface SandboxTargetStartInput {
49
51
  readonly runId: RunId;
@@ -565,6 +565,10 @@ export function createSandboxManager(options) {
565
565
  for (const metaPath of metas) {
566
566
  try {
567
567
  const parsed = JSON.parse(await readFile(metaPath, 'utf8'));
568
+ if (parsed.modeRef ? parsed.modeRef !== mode.ref : !parsed.expiresAt) {
569
+ anyRunning = true;
570
+ break;
571
+ }
568
572
  hasMeta = true;
569
573
  if (parsed.status === 'running' ||
570
574
  (parsed.runId && runMemberSessions.get(parsed.runId)?.size)) {
@@ -712,6 +716,7 @@ export function createSandboxManager(options) {
712
716
  version: 1,
713
717
  workspaceRoot: root,
714
718
  workspaceHash,
719
+ modeRef: mode.ref,
715
720
  ...(effectiveSessionId !== undefined ? { sessionId: effectiveSessionId } : {}),
716
721
  runId: params.runId,
717
722
  role: params.role,
@@ -1055,18 +1060,18 @@ export function createSandboxManager(options) {
1055
1060
  return;
1056
1061
  }
1057
1062
  signal?.throwIfAborted();
1058
- const orphans = await runner
1059
- .listManagedContainers({ 'saturn.managed': 'true', 'saturn.workspace': workspaceHash })
1060
- .catch(() => []);
1061
- for (const orphan of orphans) {
1062
- await runner.removeContainer(orphan.id).catch(() => { });
1063
- }
1064
- const orphanNetworks = await runner
1065
- .listManagedNetworks?.({ 'saturn.managed': 'true', 'saturn.workspace': workspaceHash })
1066
- .catch(() => []);
1067
- for (const orphanNet of orphanNetworks ?? []) {
1068
- await runner.removeNetwork?.(orphanNet.name).catch(() => { });
1069
- }
1063
+ const cleanup = async () => {
1064
+ const labels = { 'saturn.managed': 'true', 'saturn.workspace': workspaceHash };
1065
+ const orphans = await runner.listManagedContainers(labels).catch(() => []);
1066
+ for (const orphan of orphans) {
1067
+ await runner.removeContainer(orphan.id).catch(() => { });
1068
+ }
1069
+ const orphanNetworks = await runner.listManagedNetworks?.(labels).catch(() => []);
1070
+ for (const orphanNet of orphanNetworks ?? []) {
1071
+ await runner.removeNetwork?.(orphanNet.name).catch(() => { });
1072
+ }
1073
+ };
1074
+ await (options.cleanupOrphans ? options.cleanupOrphans(cleanup) : cleanup());
1070
1075
  signal?.throwIfAborted();
1071
1076
  if (!resolvedImage || !(await runner.hasImage(resolvedImage))) {
1072
1077
  applyFallbackOrThrow('SANDBOX_IMAGE_MISSING', `Sandbox image "${resolvedImage ?? '(unspecified)'}" is missing locally`);
@@ -1364,6 +1369,7 @@ export function createSandboxManager(options) {
1364
1369
  version: 1,
1365
1370
  workspaceRoot: root,
1366
1371
  workspaceHash,
1372
+ modeRef: mode.ref,
1367
1373
  runId: input.runId,
1368
1374
  role: 'target',
1369
1375
  memberId: `target:${targetName}`,
@@ -0,0 +1,79 @@
1
+ import type { HostProtocolRequest, JsonValue, LoggerPort, ModeDefinition, RunId, SessionId } from '@saturn-universe/core';
2
+ import type { HostStatusFields } from '@saturn-universe/protocol';
3
+ import type { SqliteStore } from '@saturn-universe/storage';
4
+ import type { ProcessManager } from '@saturn-universe/tools';
5
+ import type { PluginLifecycle } from './cordis/plugin-lifecycle.js';
6
+ import type { LoadedHostPlugin } from './cordis/plugin-loader.js';
7
+ type PluginStatus = ReturnType<PluginLifecycle['status']>;
8
+ interface ModeRuntime {
9
+ readonly status: Omit<HostStatusFields, 'epoch' | 'cursor'> & {
10
+ readonly configuredProfiles: number;
11
+ readonly plugins: PluginStatus;
12
+ readonly driverFailures: readonly {
13
+ runId: string;
14
+ code: string;
15
+ diagnosticId: string;
16
+ }[];
17
+ };
18
+ handle(request: HostProtocolRequest, signal?: AbortSignal): Promise<JsonValue>;
19
+ recoverRuns(runIds: readonly RunId[]): Promise<void>;
20
+ activePlugins(): readonly LoadedHostPlugin[];
21
+ reloadPlugins(): Promise<PluginStatus>;
22
+ reloadPlugin(id: string): Promise<PluginStatus>;
23
+ deactivatePlugin(id: string): Promise<PluginStatus>;
24
+ pluginGenerations(): PluginStatus;
25
+ drainPlugins(): Promise<PluginStatus>;
26
+ close(): Promise<void>;
27
+ }
28
+ export declare function createSessionModeRuntime({ store, activeMode, availableModes, processManager, logger, mount, }: {
29
+ store: SqliteStore;
30
+ activeMode: ModeDefinition;
31
+ availableModes: readonly ModeDefinition[];
32
+ processManager: ProcessManager;
33
+ logger: LoggerPort;
34
+ mount: (modeRef: string, plugins?: readonly LoadedHostPlugin[]) => Promise<ModeRuntime>;
35
+ }): Promise<{
36
+ readonly status: ModeRuntime["status"];
37
+ recover: () => Promise<void>;
38
+ handle: (request: HostProtocolRequest, signal?: AbortSignal) => Promise<JsonValue> | Promise<Readonly<{
39
+ sessionId: SessionId;
40
+ mode: {
41
+ ref: string;
42
+ displayName: string;
43
+ description: string;
44
+ };
45
+ cursor: import("@saturn-universe/core").EventPosition;
46
+ }>>;
47
+ reloadPlugins: () => Promise<{
48
+ id: string;
49
+ version: string;
50
+ kind: "saturn-registrar" | "cordis";
51
+ status: "active" | "draining";
52
+ }[]>;
53
+ reloadPlugin: (id: string) => Promise<{
54
+ id: string;
55
+ version: string;
56
+ kind: "saturn-registrar" | "cordis";
57
+ status: "active" | "draining";
58
+ }[]>;
59
+ deactivatePlugin: (id: string) => Promise<{
60
+ id: string;
61
+ version: string;
62
+ kind: "saturn-registrar" | "cordis";
63
+ status: "active" | "draining";
64
+ }[]>;
65
+ pluginGenerations: () => {
66
+ id: string;
67
+ version: string;
68
+ kind: "saturn-registrar" | "cordis";
69
+ status: "active" | "draining";
70
+ }[];
71
+ drainPlugins: () => Promise<{
72
+ id: string;
73
+ version: string;
74
+ kind: "saturn-registrar" | "cordis";
75
+ status: "active" | "draining";
76
+ }[]>;
77
+ close(): Promise<void>;
78
+ }>;
79
+ export {};
@@ -0,0 +1,252 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { canonicalJson, isTerminalRunStatus, reportDiagnostic, resolveModeSelector, RuntimeError, } from '@saturn-universe/core';
3
+ export async function createSessionModeRuntime({ store, activeMode, availableModes, processManager, logger, mount, }) {
4
+ const defaultRef = activeMode.ref;
5
+ const mounts = new Map();
6
+ let queue = Promise.resolve();
7
+ let closing = false;
8
+ let closeTask;
9
+ function resolve(selector) {
10
+ const mode = resolveModeSelector(selector, availableModes);
11
+ if (!mode)
12
+ throw new RuntimeError('INVALID_CONFIG', `Unknown mode: ${selector}`);
13
+ return mode;
14
+ }
15
+ async function open(modeRef, plugins) {
16
+ const existing = mounts.get(modeRef);
17
+ if (existing)
18
+ return existing;
19
+ const opened = { runtime: await mount(modeRef, plugins), sessions: new Set() };
20
+ mounts.set(modeRef, opened);
21
+ return opened;
22
+ }
23
+ async function retire(modeRef, mounted) {
24
+ mounts.delete(modeRef);
25
+ await mounted.runtime.close();
26
+ }
27
+ const initial = await open(defaultRef);
28
+ const initialStatus = initial.runtime.status;
29
+ function serialize(work) {
30
+ if (closing)
31
+ return Promise.reject(new RuntimeError('HOST_CLOSING', 'Host is shutting down'));
32
+ const pending = queue.then(work);
33
+ queue = pending.then(() => undefined, () => undefined);
34
+ return pending;
35
+ }
36
+ function currentRuntime() {
37
+ const runtime = (mounts.get(defaultRef) ?? mounts.values().next().value)?.runtime;
38
+ if (!runtime)
39
+ throw new RuntimeError('MODE_UNAVAILABLE', 'No Mode is mounted');
40
+ return runtime;
41
+ }
42
+ async function restore(modeRef, plugins) {
43
+ try {
44
+ return await open(modeRef, plugins);
45
+ }
46
+ catch (error) {
47
+ reportDiagnostic(logger, error, randomUUID(), 'MODE_ROLLBACK_FAILED', { modeRef });
48
+ throw new RuntimeError('MODE_ROLLBACK_FAILED', 'Could not restore Mode ' + modeRef);
49
+ }
50
+ }
51
+ async function useMount(ref, sessionId) {
52
+ const unusedDefault = mounts.get(defaultRef);
53
+ if (ref !== defaultRef && !mounts.has(ref) && unusedDefault?.sessions.size === 0) {
54
+ // Cold recovery may start with a default scope that has no session users yet.
55
+ const plugins = unusedDefault.runtime.activePlugins();
56
+ try {
57
+ await retire(defaultRef, unusedDefault);
58
+ await open(ref);
59
+ }
60
+ catch (error) {
61
+ await restore(defaultRef, plugins);
62
+ throw error;
63
+ }
64
+ }
65
+ const mounted = await open(ref);
66
+ mounted.sessions.add(sessionId);
67
+ return mounted.runtime;
68
+ }
69
+ async function sessionRuntime(sessionId) {
70
+ const { session } = await store.sessionModeState(sessionId);
71
+ return useMount(session.modeRef ?? defaultRef, sessionId);
72
+ }
73
+ async function runRuntime(runId, resume = false) {
74
+ const { route, config } = await store.environmentReader.load(runId);
75
+ const canonical = config.modeRef && resolveModeSelector(config.modeRef, availableModes)?.ref;
76
+ if (isTerminalRunStatus((await store.stateReader.run(runId)).status)) {
77
+ return resume
78
+ ? sessionRuntime(route.sessionId)
79
+ : (mounts.get(canonical || defaultRef)?.runtime ?? currentRuntime());
80
+ }
81
+ // Pre-Mode logs used a legacy non-versioned name. A removed versioned Mode cannot
82
+ // safely execute its Run's frozen tools or sandbox settings on a different mount.
83
+ const ref = canonical || (config.modeRef?.includes('@') ? config.modeRef : defaultRef);
84
+ return useMount(ref, route.sessionId);
85
+ }
86
+ async function select(commandId, command) {
87
+ const { sessionId } = command;
88
+ const commandHash = createHash('sha256').update(canonicalJson(command)).digest('hex');
89
+ const previous = await store.receipt(commandId, commandHash);
90
+ if (previous) {
91
+ const selection = previous.events.find((event) => event.type === 'session.mode.selected');
92
+ if (!selection)
93
+ throw new RuntimeError('IDEMPOTENCY_CONFLICT', 'Command ID belongs to a different command');
94
+ const { ref, displayName, description } = resolve(selection.payload.modeRef);
95
+ return { sessionId, mode: { ref, displayName, description }, cursor: previous.lastPosition };
96
+ }
97
+ const { session, busy, lastSeq } = await store.sessionModeState(sessionId);
98
+ if (session.status !== 'open')
99
+ throw new RuntimeError('INVALID_TRANSITION', 'Session is archived');
100
+ if (busy)
101
+ throw new RuntimeError('SESSION_BUSY', 'A Run is active in the session');
102
+ const { ref, displayName, description } = resolve(command.modeRef);
103
+ const previousRef = session.modeRef ?? defaultRef;
104
+ const priorMount = mounts.get(previousRef);
105
+ const targetWasMounted = mounts.has(ref);
106
+ const shouldRetire = priorMount &&
107
+ previousRef !== ref &&
108
+ priorMount.sessions.size === Number(priorMount.sessions.has(sessionId));
109
+ const priorPlugins = shouldRetire ? priorMount.runtime.activePlugins() : undefined;
110
+ let target;
111
+ try {
112
+ // Retire the last user's scope before activating the next one, including plugins that
113
+ // bind the same host resource. Other sessions keep an independent reference to their Mode.
114
+ if (shouldRetire)
115
+ await retire(previousRef, priorMount);
116
+ target = await open(ref);
117
+ const receipt = await store.commit({
118
+ commandId,
119
+ commandHash,
120
+ correlationId: commandId,
121
+ actor: { kind: 'user', id: 'local' },
122
+ expected: [{ stream: { kind: 'session', id: sessionId }, lastSeq }],
123
+ events: [
124
+ {
125
+ id: randomUUID(),
126
+ type: 'session.mode.selected',
127
+ eventVersion: 1,
128
+ scope: { kind: 'session', workspaceId: session.workspaceId, sessionId },
129
+ occurredAt: new Date().toISOString(),
130
+ causationId: null,
131
+ payload: { modeRef: ref },
132
+ },
133
+ ],
134
+ hostEpoch: store.epoch,
135
+ });
136
+ priorMount?.sessions.delete(sessionId);
137
+ target.sessions.add(sessionId);
138
+ return { sessionId, mode: { ref, displayName, description }, cursor: receipt.lastPosition };
139
+ }
140
+ catch (error) {
141
+ if (target && !targetWasMounted) {
142
+ mounts.delete(ref);
143
+ await target.runtime.close().catch((cleanupError) => {
144
+ reportDiagnostic(logger, cleanupError, randomUUID(), 'MODE_CLEANUP_FAILED', { modeRef: ref });
145
+ });
146
+ }
147
+ if (priorPlugins) {
148
+ const restored = await restore(previousRef, priorPlugins);
149
+ if (priorMount?.sessions.has(sessionId))
150
+ restored.sessions.add(sessionId);
151
+ }
152
+ if (error instanceof RuntimeError)
153
+ throw error;
154
+ reportDiagnostic(logger, error, randomUUID(), 'MODE_ACTIVATION_FAILED', { modeRef: ref });
155
+ throw new RuntimeError('MODE_ACTIVATION_FAILED', `Could not activate Mode ${ref}`);
156
+ }
157
+ }
158
+ function handle(request, signal) {
159
+ const { command, commandId } = request;
160
+ switch (command.type) {
161
+ case 'session.mode.select':
162
+ return serialize(() => select(commandId, command));
163
+ case 'run.submit':
164
+ return serialize(async () => {
165
+ const runtime = await sessionRuntime(command.input.sessionId);
166
+ return runtime.handle(request, signal);
167
+ });
168
+ case 'run.resume':
169
+ case 'run.steer':
170
+ case 'run.cancel':
171
+ case 'surface.compact':
172
+ return serialize(async () => {
173
+ const runtime = await runRuntime(command.runId, command.type === 'run.resume');
174
+ return runtime.handle(request, signal);
175
+ });
176
+ case 'tool.approval.resolve':
177
+ case 'tool.reconcile':
178
+ return serialize(async () => {
179
+ const call = await store.toolReader.read(command.type === 'tool.reconcile' ? command.toolCallId : command.decision.toolCallId);
180
+ const runtime = await runRuntime(call.runId);
181
+ return runtime.handle(request, signal);
182
+ });
183
+ case 'session.btw':
184
+ return serialize(async () => {
185
+ signal?.throwIfAborted();
186
+ return { pending: (await sessionRuntime(command.sessionId)).handle(request, signal) };
187
+ }).then(({ pending }) => pending);
188
+ case 'run.progress':
189
+ return serialize(async () => (await runRuntime(command.runId)).handle(request, signal));
190
+ case 'session.create':
191
+ case 'workspace.create':
192
+ return serialize(() => currentRuntime().handle(request, signal));
193
+ default:
194
+ return queue.then(() => {
195
+ if (closing)
196
+ throw new RuntimeError('HOST_CLOSING', 'Host is shutting down');
197
+ signal?.throwIfAborted();
198
+ return currentRuntime().handle(request, signal);
199
+ });
200
+ }
201
+ }
202
+ return {
203
+ get status() {
204
+ const defaultStatus = mounts.get(defaultRef)?.runtime.status;
205
+ const driverFailures = [...mounts.values()].flatMap(({ runtime }) => runtime.status.driverFailures);
206
+ if (defaultStatus)
207
+ return { ...defaultStatus, driverFailures };
208
+ const { sandbox: _sandbox, boardUrl: _board, ...status } = initialStatus;
209
+ return { ...status, plugins: [], driverFailures };
210
+ },
211
+ recover: () => serialize(async () => {
212
+ const processes = await processManager.recover();
213
+ for (const runId of new Set(processes.map(({ scope }) => scope.runId))) {
214
+ try {
215
+ if (!isTerminalRunStatus((await store.stateReader.run(runId)).status))
216
+ continue;
217
+ }
218
+ catch (error) {
219
+ if (!(error instanceof RuntimeError) || error.code !== 'NOT_FOUND')
220
+ throw error;
221
+ logger.info({ code: 'ORPHAN_PROCESS_RUN', runId }, 'Cleaning up a process scope absent from the database');
222
+ }
223
+ await processManager.stopRun(runId);
224
+ }
225
+ for (const runId of await store.recoverableRuns()) {
226
+ const runtime = await runRuntime(runId);
227
+ await runtime.recoverRuns([runId]);
228
+ }
229
+ }),
230
+ handle,
231
+ reloadPlugins: () => serialize(async () => (await open(defaultRef)).runtime.reloadPlugins()),
232
+ reloadPlugin: (id) => serialize(async () => (await open(defaultRef)).runtime.reloadPlugin(id)),
233
+ deactivatePlugin: (id) => serialize(async () => (await open(defaultRef)).runtime.deactivatePlugin(id)),
234
+ pluginGenerations: () => mounts.get(defaultRef)?.runtime.pluginGenerations() ?? [],
235
+ drainPlugins: () => serialize(async () => (await open(defaultRef)).runtime.drainPlugins()),
236
+ close() {
237
+ closing = true;
238
+ return (closeTask ??= (async () => {
239
+ await queue;
240
+ try {
241
+ const results = await Promise.allSettled([...mounts.values()].map(({ runtime }) => runtime.close()));
242
+ const failed = results.find((result) => result.status === 'rejected');
243
+ if (failed)
244
+ throw failed.reason;
245
+ }
246
+ finally {
247
+ await processManager.close();
248
+ }
249
+ })());
250
+ },
251
+ };
252
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@saturn-universe/runtime-host",
3
- "version": "0.1.2-dev.6",
3
+ "version": "0.1.2-dev.7",
4
4
  "license": "AGPL-3.0-only",
5
5
  "type": "module",
6
6
  "files": [
@@ -8,14 +8,14 @@
8
8
  ],
9
9
  "dependencies": {
10
10
  "@deepseek-ai/cordis": "4.1.0",
11
- "@saturn-universe/context": "0.1.2-dev.6",
12
- "@saturn-universe/core": "0.1.2-dev.6",
13
- "@saturn-universe/model": "0.1.2-dev.6",
14
- "@saturn-universe/plugin-sdk": "0.1.2-dev.6",
15
- "@saturn-universe/protocol": "0.1.2-dev.6",
16
- "@saturn-universe/runtime": "0.1.2-dev.6",
17
- "@saturn-universe/storage": "0.1.2-dev.6",
18
- "@saturn-universe/tools": "0.1.2-dev.6",
11
+ "@saturn-universe/context": "0.1.2-dev.7",
12
+ "@saturn-universe/core": "0.1.2-dev.7",
13
+ "@saturn-universe/model": "0.1.2-dev.7",
14
+ "@saturn-universe/plugin-sdk": "0.1.2-dev.7",
15
+ "@saturn-universe/protocol": "0.1.2-dev.7",
16
+ "@saturn-universe/runtime": "0.1.2-dev.7",
17
+ "@saturn-universe/storage": "0.1.2-dev.7",
18
+ "@saturn-universe/tools": "0.1.2-dev.7",
19
19
  "import-meta-resolve": "4.2.0",
20
20
  "pino": "10.4.0",
21
21
  "semver": "7.7.4",