@saturn-universe/runtime-host 0.1.2-dev.1 → 0.1.2-dev.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/builtin-plugins/saturn-plugin-ctf/index.mjs +2 -2
- package/dist/builtin-plugins/saturn-plugin-ctf/package.json +1 -1
- package/dist/command-dispatch.js +2 -1
- package/dist/composition.d.ts +20 -56
- package/dist/composition.js +316 -89
- package/dist/context-extensions.d.ts +132 -10
- package/dist/context-extensions.js +30 -4
- package/dist/cordis/plugin-lifecycle.d.ts +1 -0
- package/dist/cordis/plugin-lifecycle.js +3 -0
- package/dist/cordis/plugin-loader.d.ts +1 -1
- package/dist/cordis/plugin-loader.js +45 -10
- package/dist/cordis/sandbox-plugin.d.ts +1 -0
- package/dist/cordis/sandbox-plugin.js +1 -0
- package/dist/cordis/tools/builtin-agent-tools-plugin.d.ts +2 -2
- package/dist/cordis/tools/builtin-agent-tools-plugin.js +27 -3
- package/dist/cordis/tools/index.d.ts +5 -1
- package/dist/cordis/tools/index.js +3 -3
- package/dist/cordis/tools/process-manager-plugin.d.ts +1 -1
- package/dist/cordis/tools/process-manager-plugin.js +8 -8
- package/dist/cordis/tools/tools-core-plugin.js +54 -11
- package/dist/env-probe.js +33 -20
- package/dist/host-configuration.d.ts +4 -0
- package/dist/host-configuration.js +25 -1
- package/dist/index.js +9 -2
- package/dist/mode-configuration.d.ts +197 -0
- package/dist/mode-configuration.js +109 -0
- package/dist/modes.js +52 -10
- package/dist/provider-catalog.d.ts +83 -12
- package/dist/provider-catalog.js +30 -46
- package/dist/run-budget.d.ts +30 -7
- package/dist/run-budget.js +49 -5
- package/dist/runtime-tuning.d.ts +23 -0
- package/dist/runtime-tuning.js +68 -0
- package/dist/sandbox-manager.d.ts +2 -0
- package/dist/sandbox-manager.js +18 -12
- package/dist/session-mode-runtime.d.ts +99 -0
- package/dist/session-mode-runtime.js +306 -0
- package/dist/skills-runtime.d.ts +5 -2
- package/dist/skills-runtime.js +8 -5
- package/package.json +9 -9
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { RuntimeError } from '@saturn-universe/core';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
const positive = z.number().int().positive().safe();
|
|
4
|
+
const nonnegative = z.number().int().nonnegative().safe();
|
|
5
|
+
const ratio = z.number().gt(0).lte(1);
|
|
6
|
+
const emptyRatio = z.number().gte(0).lte(1);
|
|
7
|
+
export const modeRetrySchema = z
|
|
8
|
+
.strictObject({
|
|
9
|
+
model_max_attempts_per_call: positive.optional(),
|
|
10
|
+
tool_max_attempts_per_call: positive.optional(),
|
|
11
|
+
base_delay_ms: positive.optional(),
|
|
12
|
+
max_delay_ms: positive.optional(),
|
|
13
|
+
})
|
|
14
|
+
.refine(({ base_delay_ms, max_delay_ms }) => base_delay_ms === undefined || max_delay_ms === undefined || base_delay_ms <= max_delay_ms);
|
|
15
|
+
export const modeCompactionSchema = z.strictObject({
|
|
16
|
+
enabled: z.boolean().optional(),
|
|
17
|
+
threshold_ratio: ratio.optional(),
|
|
18
|
+
max_headroom_tokens: nonnegative.optional(),
|
|
19
|
+
headroom_ratio: emptyRatio.optional(),
|
|
20
|
+
min_recent_steps: nonnegative.optional(),
|
|
21
|
+
tail_window_ratio: emptyRatio.optional(),
|
|
22
|
+
preflight_window_ratio: ratio.optional(),
|
|
23
|
+
max_halvings: nonnegative.optional(),
|
|
24
|
+
min_prefix_chars: nonnegative.optional(),
|
|
25
|
+
summary_timeout_ms: positive.optional(),
|
|
26
|
+
});
|
|
27
|
+
export function readModeRetry(raw) {
|
|
28
|
+
const { model_max_attempts_per_call, tool_max_attempts_per_call, base_delay_ms, max_delay_ms } = raw;
|
|
29
|
+
return {
|
|
30
|
+
...(model_max_attempts_per_call !== undefined
|
|
31
|
+
? { modelMaxAttemptsPerCall: model_max_attempts_per_call }
|
|
32
|
+
: {}),
|
|
33
|
+
...(tool_max_attempts_per_call !== undefined
|
|
34
|
+
? { toolMaxAttemptsPerCall: tool_max_attempts_per_call }
|
|
35
|
+
: {}),
|
|
36
|
+
...(base_delay_ms !== undefined ? { baseDelayMs: base_delay_ms } : {}),
|
|
37
|
+
...(max_delay_ms !== undefined ? { maxDelayMs: max_delay_ms } : {}),
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
export function resolveRetryPolicy(mode, explicit) {
|
|
41
|
+
const policy = {
|
|
42
|
+
modelMaxAttemptsPerCall: 3,
|
|
43
|
+
toolMaxAttemptsPerCall: 1,
|
|
44
|
+
baseDelayMs: 2000,
|
|
45
|
+
maxDelayMs: 5000,
|
|
46
|
+
...mode,
|
|
47
|
+
...explicit,
|
|
48
|
+
};
|
|
49
|
+
if (Object.values(policy).some((value) => !Number.isSafeInteger(value) || value < 1) ||
|
|
50
|
+
policy.baseDelayMs > policy.maxDelayMs) {
|
|
51
|
+
throw new RuntimeError('INVALID_CONFIG', 'Retry values must be positive integers and base delay must not exceed max delay');
|
|
52
|
+
}
|
|
53
|
+
return policy;
|
|
54
|
+
}
|
|
55
|
+
export function readModeCompaction(raw) {
|
|
56
|
+
return {
|
|
57
|
+
...(raw.enabled !== undefined ? { enabled: raw.enabled } : {}),
|
|
58
|
+
...(raw.threshold_ratio !== undefined ? { thresholdRatio: raw.threshold_ratio } : {}),
|
|
59
|
+
...(raw.max_headroom_tokens !== undefined ? { maxHeadroomTokens: raw.max_headroom_tokens } : {}),
|
|
60
|
+
...(raw.headroom_ratio !== undefined ? { headroomRatio: raw.headroom_ratio } : {}),
|
|
61
|
+
...(raw.min_recent_steps !== undefined ? { minRecentSteps: raw.min_recent_steps } : {}),
|
|
62
|
+
...(raw.tail_window_ratio !== undefined ? { tailWindowRatio: raw.tail_window_ratio } : {}),
|
|
63
|
+
...(raw.preflight_window_ratio !== undefined ? { preflightWindowRatio: raw.preflight_window_ratio } : {}),
|
|
64
|
+
...(raw.max_halvings !== undefined ? { maxHalvings: raw.max_halvings } : {}),
|
|
65
|
+
...(raw.min_prefix_chars !== undefined ? { minPrefixChars: raw.min_prefix_chars } : {}),
|
|
66
|
+
...(raw.summary_timeout_ms !== undefined ? { summaryTimeoutMs: raw.summary_timeout_ms } : {}),
|
|
67
|
+
};
|
|
68
|
+
}
|
|
@@ -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;
|
package/dist/sandbox-manager.js
CHANGED
|
@@ -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
|
|
1059
|
-
|
|
1060
|
-
.catch(() => []);
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
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,99 @@
|
|
|
1
|
+
import type { AgentSessionId, RunConfig, TeamConfig, ToolDefinition, 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, createToolExecutor } from '@saturn-universe/tools';
|
|
5
|
+
import type { createAgentLoop, createRunLoop } from '@saturn-universe/runtime';
|
|
6
|
+
import type { PluginLifecycle } from './cordis/plugin-lifecycle.js';
|
|
7
|
+
import type { LoadedHostPlugin } from './cordis/plugin-loader.js';
|
|
8
|
+
type PluginStatus = ReturnType<PluginLifecycle['status']>;
|
|
9
|
+
type RunDependencies = Parameters<typeof createRunLoop>[0];
|
|
10
|
+
export interface WorkerModeRuntime {
|
|
11
|
+
readonly agent: ReturnType<typeof createAgentLoop>;
|
|
12
|
+
readonly executor: ReturnType<typeof createToolExecutor>;
|
|
13
|
+
readonly freeze: (parent: RunConfig, team: TeamConfig, agentSessionId: AgentSessionId, depth: number) => Promise<RunConfig>;
|
|
14
|
+
readonly verify: (config: RunConfig) => Promise<void>;
|
|
15
|
+
readonly verifyTool: (definition: ToolDefinition) => Promise<unknown>;
|
|
16
|
+
readonly start: NonNullable<RunDependencies['onWorkerStart']>;
|
|
17
|
+
readonly complete: NonNullable<RunDependencies['onWorkerComplete']>;
|
|
18
|
+
}
|
|
19
|
+
export interface WorkerModeMounts {
|
|
20
|
+
acquire(modeRef: string, runId: RunId, agentSessionId: AgentSessionId): Promise<WorkerModeRuntime>;
|
|
21
|
+
find(runId: RunId, agentSessionId: AgentSessionId): WorkerModeRuntime | undefined;
|
|
22
|
+
release(runId: RunId, agentSessionId?: AgentSessionId): Promise<void>;
|
|
23
|
+
wake(runId: RunId): Promise<void>;
|
|
24
|
+
}
|
|
25
|
+
interface ModeRuntime {
|
|
26
|
+
readonly status: Omit<HostStatusFields, 'epoch' | 'cursor'> & {
|
|
27
|
+
readonly configuredProfiles: number;
|
|
28
|
+
readonly plugins: PluginStatus;
|
|
29
|
+
readonly driverFailures: readonly {
|
|
30
|
+
runId: string;
|
|
31
|
+
code: string;
|
|
32
|
+
diagnosticId: string;
|
|
33
|
+
}[];
|
|
34
|
+
};
|
|
35
|
+
handle(request: HostProtocolRequest, signal?: AbortSignal): Promise<JsonValue>;
|
|
36
|
+
recoverRuns(runIds: readonly RunId[]): Promise<void>;
|
|
37
|
+
activePlugins(): readonly LoadedHostPlugin[];
|
|
38
|
+
reloadPlugins(): Promise<PluginStatus>;
|
|
39
|
+
reloadPlugin(id: string): Promise<PluginStatus>;
|
|
40
|
+
deactivatePlugin(id: string): Promise<PluginStatus>;
|
|
41
|
+
pluginGenerations(): PluginStatus;
|
|
42
|
+
drainPlugins(): Promise<PluginStatus>;
|
|
43
|
+
close(): Promise<void>;
|
|
44
|
+
stopRuns(): Promise<void>;
|
|
45
|
+
wakeTeam(runId: RunId): Promise<void> | undefined;
|
|
46
|
+
readonly worker: WorkerModeRuntime;
|
|
47
|
+
}
|
|
48
|
+
export declare function createSessionModeRuntime({ store, activeMode, availableModes, processManager, logger, mount, }: {
|
|
49
|
+
store: SqliteStore;
|
|
50
|
+
activeMode: ModeDefinition;
|
|
51
|
+
availableModes: readonly ModeDefinition[];
|
|
52
|
+
processManager: ProcessManager;
|
|
53
|
+
logger: LoggerPort;
|
|
54
|
+
mount: (modeRef: string, workers: WorkerModeMounts, plugins?: readonly LoadedHostPlugin[]) => Promise<ModeRuntime>;
|
|
55
|
+
}): Promise<{
|
|
56
|
+
readonly status: ModeRuntime["status"];
|
|
57
|
+
recover: () => Promise<void>;
|
|
58
|
+
handle: (request: HostProtocolRequest, signal?: AbortSignal) => Promise<JsonValue> | Promise<Readonly<{
|
|
59
|
+
sessionId: SessionId;
|
|
60
|
+
mode: {
|
|
61
|
+
ref: string;
|
|
62
|
+
displayName: string;
|
|
63
|
+
description: string;
|
|
64
|
+
};
|
|
65
|
+
cursor: import("@saturn-universe/core").EventPosition;
|
|
66
|
+
}>>;
|
|
67
|
+
reloadPlugins: () => Promise<{
|
|
68
|
+
id: string;
|
|
69
|
+
version: string;
|
|
70
|
+
kind: "saturn-registrar" | "cordis";
|
|
71
|
+
status: "active" | "draining";
|
|
72
|
+
}[]>;
|
|
73
|
+
reloadPlugin: (id: string) => Promise<{
|
|
74
|
+
id: string;
|
|
75
|
+
version: string;
|
|
76
|
+
kind: "saturn-registrar" | "cordis";
|
|
77
|
+
status: "active" | "draining";
|
|
78
|
+
}[]>;
|
|
79
|
+
deactivatePlugin: (id: string) => Promise<{
|
|
80
|
+
id: string;
|
|
81
|
+
version: string;
|
|
82
|
+
kind: "saturn-registrar" | "cordis";
|
|
83
|
+
status: "active" | "draining";
|
|
84
|
+
}[]>;
|
|
85
|
+
pluginGenerations: () => {
|
|
86
|
+
id: string;
|
|
87
|
+
version: string;
|
|
88
|
+
kind: "saturn-registrar" | "cordis";
|
|
89
|
+
status: "active" | "draining";
|
|
90
|
+
}[];
|
|
91
|
+
drainPlugins: () => Promise<{
|
|
92
|
+
id: string;
|
|
93
|
+
version: string;
|
|
94
|
+
kind: "saturn-registrar" | "cordis";
|
|
95
|
+
status: "active" | "draining";
|
|
96
|
+
}[]>;
|
|
97
|
+
close(): Promise<void>;
|
|
98
|
+
}>;
|
|
99
|
+
export {};
|
|
@@ -0,0 +1,306 @@
|
|
|
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
|
+
const workerMounts = new Map();
|
|
7
|
+
let queue = Promise.resolve();
|
|
8
|
+
let mountQueue = Promise.resolve();
|
|
9
|
+
let closing = false;
|
|
10
|
+
let closeTask;
|
|
11
|
+
function resolve(selector) {
|
|
12
|
+
const mode = resolveModeSelector(selector, availableModes);
|
|
13
|
+
if (!mode)
|
|
14
|
+
throw new RuntimeError('INVALID_CONFIG', `Unknown mode: ${selector}`);
|
|
15
|
+
return mode;
|
|
16
|
+
}
|
|
17
|
+
function serializeMount(work) {
|
|
18
|
+
const pending = mountQueue.then(work);
|
|
19
|
+
mountQueue = pending.then(() => undefined, () => undefined);
|
|
20
|
+
return pending;
|
|
21
|
+
}
|
|
22
|
+
const workers = {
|
|
23
|
+
acquire: (ref, runId, agentSessionId) => serializeMount(async () => {
|
|
24
|
+
const entries = workerMounts.get(runId) ?? new Map();
|
|
25
|
+
const existing = entries.get(agentSessionId);
|
|
26
|
+
if (existing)
|
|
27
|
+
return existing.mount.runtime.worker;
|
|
28
|
+
const mount = await open(ref);
|
|
29
|
+
mount.workers++;
|
|
30
|
+
entries.set(agentSessionId, { ref, mount });
|
|
31
|
+
workerMounts.set(runId, entries);
|
|
32
|
+
return mount.runtime.worker;
|
|
33
|
+
}),
|
|
34
|
+
find: (runId, agentSessionId) => workerMounts.get(runId)?.get(agentSessionId)?.mount.runtime.worker,
|
|
35
|
+
release: (runId, agentSessionId) => !workerMounts.has(runId)
|
|
36
|
+
? Promise.resolve()
|
|
37
|
+
: serializeMount(async () => {
|
|
38
|
+
const entries = workerMounts.get(runId);
|
|
39
|
+
if (!entries)
|
|
40
|
+
return;
|
|
41
|
+
for (const [id, { ref, mount }] of entries) {
|
|
42
|
+
if (agentSessionId !== undefined && id !== agentSessionId)
|
|
43
|
+
continue;
|
|
44
|
+
entries.delete(id);
|
|
45
|
+
if (--mount.workers === 0 && mount.sessions.size === 0 && !closing) {
|
|
46
|
+
await retire(ref, mount).catch((error) => reportDiagnostic(logger, error, randomUUID(), 'MODE_CLEANUP_FAILED', { modeRef: ref }));
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
if (entries.size === 0)
|
|
50
|
+
workerMounts.delete(runId);
|
|
51
|
+
}),
|
|
52
|
+
async wake(runId) {
|
|
53
|
+
const { config } = await store.environmentReader.load(runId);
|
|
54
|
+
const ref = resolveModeSelector(config.modeRef, availableModes)?.ref ?? defaultRef;
|
|
55
|
+
await mounts.get(ref)?.runtime.wakeTeam(runId);
|
|
56
|
+
},
|
|
57
|
+
};
|
|
58
|
+
async function open(modeRef, plugins) {
|
|
59
|
+
const existing = mounts.get(modeRef);
|
|
60
|
+
if (existing)
|
|
61
|
+
return existing;
|
|
62
|
+
const opened = {
|
|
63
|
+
runtime: await mount(modeRef, workers, plugins),
|
|
64
|
+
sessions: new Set(),
|
|
65
|
+
workers: 0,
|
|
66
|
+
};
|
|
67
|
+
mounts.set(modeRef, opened);
|
|
68
|
+
return opened;
|
|
69
|
+
}
|
|
70
|
+
async function retire(modeRef, mounted) {
|
|
71
|
+
mounts.delete(modeRef);
|
|
72
|
+
await mounted.runtime.close();
|
|
73
|
+
}
|
|
74
|
+
const initial = await open(defaultRef);
|
|
75
|
+
const initialStatus = initial.runtime.status;
|
|
76
|
+
function serialize(work) {
|
|
77
|
+
if (closing)
|
|
78
|
+
return Promise.reject(new RuntimeError('HOST_CLOSING', 'Host is shutting down'));
|
|
79
|
+
const pending = queue.then(work);
|
|
80
|
+
queue = pending.then(() => undefined, () => undefined);
|
|
81
|
+
return pending;
|
|
82
|
+
}
|
|
83
|
+
function currentRuntime() {
|
|
84
|
+
const runtime = (mounts.get(defaultRef) ?? mounts.values().next().value)?.runtime;
|
|
85
|
+
if (!runtime)
|
|
86
|
+
throw new RuntimeError('MODE_UNAVAILABLE', 'No Mode is mounted');
|
|
87
|
+
return runtime;
|
|
88
|
+
}
|
|
89
|
+
async function restore(modeRef, plugins) {
|
|
90
|
+
try {
|
|
91
|
+
return await open(modeRef, plugins);
|
|
92
|
+
}
|
|
93
|
+
catch (error) {
|
|
94
|
+
reportDiagnostic(logger, error, randomUUID(), 'MODE_ROLLBACK_FAILED', { modeRef });
|
|
95
|
+
throw new RuntimeError('MODE_ROLLBACK_FAILED', 'Could not restore Mode ' + modeRef);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
async function useMount(ref, sessionId) {
|
|
99
|
+
const unusedDefault = mounts.get(defaultRef);
|
|
100
|
+
if (ref !== defaultRef &&
|
|
101
|
+
!mounts.has(ref) &&
|
|
102
|
+
unusedDefault?.sessions.size === 0 &&
|
|
103
|
+
unusedDefault.workers === 0) {
|
|
104
|
+
// Cold recovery may start with a default scope that has no session users yet.
|
|
105
|
+
const plugins = unusedDefault.runtime.activePlugins();
|
|
106
|
+
try {
|
|
107
|
+
await retire(defaultRef, unusedDefault);
|
|
108
|
+
await open(ref);
|
|
109
|
+
}
|
|
110
|
+
catch (error) {
|
|
111
|
+
await restore(defaultRef, plugins);
|
|
112
|
+
throw error;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
const mounted = await open(ref);
|
|
116
|
+
mounted.sessions.add(sessionId);
|
|
117
|
+
return mounted.runtime;
|
|
118
|
+
}
|
|
119
|
+
async function sessionRuntime(sessionId) {
|
|
120
|
+
const { session } = await store.sessionModeState(sessionId);
|
|
121
|
+
return serializeMount(() => useMount(session.modeRef ?? defaultRef, sessionId));
|
|
122
|
+
}
|
|
123
|
+
async function runRuntime(runId, resume = false) {
|
|
124
|
+
const { route, config } = await store.environmentReader.load(runId);
|
|
125
|
+
const canonical = config.modeRef && resolveModeSelector(config.modeRef, availableModes)?.ref;
|
|
126
|
+
if (isTerminalRunStatus((await store.stateReader.run(runId)).status)) {
|
|
127
|
+
return resume
|
|
128
|
+
? sessionRuntime(route.sessionId)
|
|
129
|
+
: (mounts.get(canonical || defaultRef)?.runtime ?? currentRuntime());
|
|
130
|
+
}
|
|
131
|
+
// Pre-Mode logs used a legacy non-versioned name. A removed versioned Mode cannot
|
|
132
|
+
// safely execute its Run's frozen tools or sandbox settings on a different mount.
|
|
133
|
+
const ref = canonical || (config.modeRef?.includes('@') ? config.modeRef : defaultRef);
|
|
134
|
+
return serializeMount(() => useMount(ref, route.sessionId));
|
|
135
|
+
}
|
|
136
|
+
async function select(commandId, command) {
|
|
137
|
+
const { sessionId } = command;
|
|
138
|
+
const commandHash = createHash('sha256').update(canonicalJson(command)).digest('hex');
|
|
139
|
+
const previous = await store.receipt(commandId, commandHash);
|
|
140
|
+
if (previous) {
|
|
141
|
+
const selection = previous.events.find((event) => event.type === 'session.mode.selected');
|
|
142
|
+
if (!selection)
|
|
143
|
+
throw new RuntimeError('IDEMPOTENCY_CONFLICT', 'Command ID belongs to a different command');
|
|
144
|
+
const { ref, displayName, description } = resolve(selection.payload.modeRef);
|
|
145
|
+
return { sessionId, mode: { ref, displayName, description }, cursor: previous.lastPosition };
|
|
146
|
+
}
|
|
147
|
+
const { session, busy, lastSeq } = await store.sessionModeState(sessionId);
|
|
148
|
+
if (session.status !== 'open')
|
|
149
|
+
throw new RuntimeError('INVALID_TRANSITION', 'Session is archived');
|
|
150
|
+
if (busy)
|
|
151
|
+
throw new RuntimeError('SESSION_BUSY', 'A Run is active in the session');
|
|
152
|
+
const { ref, displayName, description } = resolve(command.modeRef);
|
|
153
|
+
const previousRef = session.modeRef ?? defaultRef;
|
|
154
|
+
const priorMount = mounts.get(previousRef);
|
|
155
|
+
const targetWasMounted = mounts.has(ref);
|
|
156
|
+
const shouldRetire = priorMount &&
|
|
157
|
+
previousRef !== ref &&
|
|
158
|
+
priorMount.workers === 0 &&
|
|
159
|
+
priorMount.sessions.size === Number(priorMount.sessions.has(sessionId));
|
|
160
|
+
const priorPlugins = shouldRetire ? priorMount.runtime.activePlugins() : undefined;
|
|
161
|
+
let target;
|
|
162
|
+
try {
|
|
163
|
+
// Retire the last user's scope before activating the next one, including plugins that
|
|
164
|
+
// bind the same host resource. Other sessions keep an independent reference to their Mode.
|
|
165
|
+
if (shouldRetire)
|
|
166
|
+
await retire(previousRef, priorMount);
|
|
167
|
+
target = await open(ref);
|
|
168
|
+
const receipt = await store.commit({
|
|
169
|
+
commandId,
|
|
170
|
+
commandHash,
|
|
171
|
+
correlationId: commandId,
|
|
172
|
+
actor: { kind: 'user', id: 'local' },
|
|
173
|
+
expected: [{ stream: { kind: 'session', id: sessionId }, lastSeq }],
|
|
174
|
+
events: [
|
|
175
|
+
{
|
|
176
|
+
id: randomUUID(),
|
|
177
|
+
type: 'session.mode.selected',
|
|
178
|
+
eventVersion: 1,
|
|
179
|
+
scope: { kind: 'session', workspaceId: session.workspaceId, sessionId },
|
|
180
|
+
occurredAt: new Date().toISOString(),
|
|
181
|
+
causationId: null,
|
|
182
|
+
payload: { modeRef: ref },
|
|
183
|
+
},
|
|
184
|
+
],
|
|
185
|
+
hostEpoch: store.epoch,
|
|
186
|
+
});
|
|
187
|
+
priorMount?.sessions.delete(sessionId);
|
|
188
|
+
target.sessions.add(sessionId);
|
|
189
|
+
return { sessionId, mode: { ref, displayName, description }, cursor: receipt.lastPosition };
|
|
190
|
+
}
|
|
191
|
+
catch (error) {
|
|
192
|
+
if (target && !targetWasMounted) {
|
|
193
|
+
mounts.delete(ref);
|
|
194
|
+
await target.runtime.close().catch((cleanupError) => {
|
|
195
|
+
reportDiagnostic(logger, cleanupError, randomUUID(), 'MODE_CLEANUP_FAILED', { modeRef: ref });
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
if (priorPlugins) {
|
|
199
|
+
const restored = await restore(previousRef, priorPlugins);
|
|
200
|
+
if (priorMount?.sessions.has(sessionId))
|
|
201
|
+
restored.sessions.add(sessionId);
|
|
202
|
+
}
|
|
203
|
+
if (error instanceof RuntimeError)
|
|
204
|
+
throw error;
|
|
205
|
+
reportDiagnostic(logger, error, randomUUID(), 'MODE_ACTIVATION_FAILED', { modeRef: ref });
|
|
206
|
+
throw new RuntimeError('MODE_ACTIVATION_FAILED', `Could not activate Mode ${ref}`);
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
function handle(request, signal) {
|
|
210
|
+
const { command, commandId } = request;
|
|
211
|
+
switch (command.type) {
|
|
212
|
+
case 'session.mode.select':
|
|
213
|
+
return serialize(() => serializeMount(() => select(commandId, command)));
|
|
214
|
+
case 'run.submit':
|
|
215
|
+
return serialize(async () => {
|
|
216
|
+
const runtime = await sessionRuntime(command.input.sessionId);
|
|
217
|
+
return runtime.handle(request, signal);
|
|
218
|
+
});
|
|
219
|
+
case 'run.resume':
|
|
220
|
+
case 'run.steer':
|
|
221
|
+
case 'run.cancel':
|
|
222
|
+
case 'surface.compact':
|
|
223
|
+
return serialize(async () => {
|
|
224
|
+
const runtime = await runRuntime(command.runId, command.type === 'run.resume');
|
|
225
|
+
return runtime.handle(request, signal);
|
|
226
|
+
});
|
|
227
|
+
case 'tool.approval.resolve':
|
|
228
|
+
case 'tool.reconcile':
|
|
229
|
+
return serialize(async () => {
|
|
230
|
+
const call = await store.toolReader.read(command.type === 'tool.reconcile' ? command.toolCallId : command.decision.toolCallId);
|
|
231
|
+
const runtime = await runRuntime(call.runId);
|
|
232
|
+
return runtime.handle(request, signal);
|
|
233
|
+
});
|
|
234
|
+
case 'session.btw':
|
|
235
|
+
return serialize(async () => {
|
|
236
|
+
signal?.throwIfAborted();
|
|
237
|
+
return { pending: (await sessionRuntime(command.sessionId)).handle(request, signal) };
|
|
238
|
+
}).then(({ pending }) => pending);
|
|
239
|
+
case 'run.progress':
|
|
240
|
+
return serialize(async () => (await runRuntime(command.runId)).handle(request, signal));
|
|
241
|
+
case 'session.create':
|
|
242
|
+
case 'workspace.create':
|
|
243
|
+
return serialize(() => currentRuntime().handle(request, signal));
|
|
244
|
+
default:
|
|
245
|
+
return queue.then(() => {
|
|
246
|
+
if (closing)
|
|
247
|
+
throw new RuntimeError('HOST_CLOSING', 'Host is shutting down');
|
|
248
|
+
signal?.throwIfAborted();
|
|
249
|
+
return currentRuntime().handle(request, signal);
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
return {
|
|
254
|
+
get status() {
|
|
255
|
+
const defaultStatus = mounts.get(defaultRef)?.runtime.status;
|
|
256
|
+
const driverFailures = [...mounts.values()].flatMap(({ runtime }) => runtime.status.driverFailures);
|
|
257
|
+
if (defaultStatus)
|
|
258
|
+
return { ...defaultStatus, driverFailures };
|
|
259
|
+
const { sandbox: _sandbox, boardUrl: _board, ...status } = initialStatus;
|
|
260
|
+
return { ...status, plugins: [], driverFailures };
|
|
261
|
+
},
|
|
262
|
+
recover: () => serialize(async () => {
|
|
263
|
+
const processes = await processManager.recover();
|
|
264
|
+
for (const runId of new Set(processes.map(({ scope }) => scope.runId))) {
|
|
265
|
+
try {
|
|
266
|
+
if (!isTerminalRunStatus((await store.stateReader.run(runId)).status))
|
|
267
|
+
continue;
|
|
268
|
+
}
|
|
269
|
+
catch (error) {
|
|
270
|
+
if (!(error instanceof RuntimeError) || error.code !== 'NOT_FOUND')
|
|
271
|
+
throw error;
|
|
272
|
+
logger.info({ code: 'ORPHAN_PROCESS_RUN', runId }, 'Cleaning up a process scope absent from the database');
|
|
273
|
+
}
|
|
274
|
+
await processManager.stopRun(runId);
|
|
275
|
+
}
|
|
276
|
+
for (const runId of await store.recoverableRuns()) {
|
|
277
|
+
const runtime = await runRuntime(runId);
|
|
278
|
+
await runtime.recoverRuns([runId]);
|
|
279
|
+
}
|
|
280
|
+
}),
|
|
281
|
+
handle,
|
|
282
|
+
reloadPlugins: () => serialize(async () => (await serializeMount(() => open(defaultRef))).runtime.reloadPlugins()),
|
|
283
|
+
reloadPlugin: (id) => serialize(async () => (await serializeMount(() => open(defaultRef))).runtime.reloadPlugin(id)),
|
|
284
|
+
deactivatePlugin: (id) => serialize(async () => (await serializeMount(() => open(defaultRef))).runtime.deactivatePlugin(id)),
|
|
285
|
+
pluginGenerations: () => mounts.get(defaultRef)?.runtime.pluginGenerations() ?? [],
|
|
286
|
+
drainPlugins: () => serialize(async () => (await serializeMount(() => open(defaultRef))).runtime.drainPlugins()),
|
|
287
|
+
close() {
|
|
288
|
+
closing = true;
|
|
289
|
+
return (closeTask ??= (async () => {
|
|
290
|
+
await queue;
|
|
291
|
+
try {
|
|
292
|
+
await mountQueue;
|
|
293
|
+
const stopped = await Promise.allSettled([...mounts.values()].map(({ runtime }) => runtime.stopRuns()));
|
|
294
|
+
await mountQueue;
|
|
295
|
+
const results = await Promise.allSettled([...mounts.values()].map(({ runtime }) => runtime.close()));
|
|
296
|
+
const failed = [...stopped, ...results].find((result) => result.status === 'rejected');
|
|
297
|
+
if (failed)
|
|
298
|
+
throw failed.reason;
|
|
299
|
+
}
|
|
300
|
+
finally {
|
|
301
|
+
await processManager.close();
|
|
302
|
+
}
|
|
303
|
+
})());
|
|
304
|
+
},
|
|
305
|
+
};
|
|
306
|
+
}
|
package/dist/skills-runtime.d.ts
CHANGED
|
@@ -8,6 +8,9 @@ export interface SkillRegistryService {
|
|
|
8
8
|
get(name: string): DiscoveredSkill | undefined;
|
|
9
9
|
indexSkills(disabledSkills?: readonly string[]): readonly DiscoveredSkillSummary[];
|
|
10
10
|
}
|
|
11
|
-
export declare function resolveModeSkillDirs(
|
|
12
|
-
export declare function createSkillRegistryService(workspaceRoot: string, activeMode: ModeDefinition, catalog?: ProviderCatalog,
|
|
11
|
+
export declare function resolveModeSkillDirs(activeMode: ModeDefinition, packageRoot?: string): readonly ModeSkillDirectory[];
|
|
12
|
+
export declare function createSkillRegistryService(workspaceRoot: string, activeMode: ModeDefinition, catalog?: ProviderCatalog, options?: {
|
|
13
|
+
readonly env?: NodeJS.ProcessEnv;
|
|
14
|
+
readonly packageRoot?: string | undefined;
|
|
15
|
+
}): Promise<SkillRegistryService>;
|
|
13
16
|
export declare function createNativeSkillTool(service: SkillRegistryService): ToolBinding;
|
package/dist/skills-runtime.js
CHANGED
|
@@ -43,14 +43,17 @@ function errorObservation(code, message) {
|
|
|
43
43
|
},
|
|
44
44
|
};
|
|
45
45
|
}
|
|
46
|
-
export function resolveModeSkillDirs(
|
|
47
|
-
return
|
|
46
|
+
export function resolveModeSkillDirs(activeMode, packageRoot) {
|
|
47
|
+
return packageRoot
|
|
48
|
+
? [{ dir: path.join(packageRoot, 'skills'), source: `mode:${activeMode.ref}`, packageRoot }]
|
|
49
|
+
: [];
|
|
48
50
|
}
|
|
49
|
-
export async function createSkillRegistryService(workspaceRoot, activeMode, catalog,
|
|
50
|
-
const modeSkillDirs = resolveModeSkillDirs(activeMode,
|
|
51
|
+
export async function createSkillRegistryService(workspaceRoot, activeMode, catalog, options = {}) {
|
|
52
|
+
const modeSkillDirs = resolveModeSkillDirs(activeMode, options.packageRoot);
|
|
51
53
|
const skills = await discoverAgentSkills(workspaceRoot, {
|
|
52
|
-
env,
|
|
54
|
+
env: options.env ?? process.env,
|
|
53
55
|
modeSkillDirs,
|
|
56
|
+
scopeModePackages: true,
|
|
54
57
|
...(catalog?.skills ? { explicitSkills: catalog.skills } : {}),
|
|
55
58
|
});
|
|
56
59
|
const byName = new Map(skills.map((skill) => [skill.name, skill]));
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@saturn-universe/runtime-host",
|
|
3
|
-
"version": "0.1.2-dev.
|
|
3
|
+
"version": "0.1.2-dev.10",
|
|
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.
|
|
12
|
-
"@saturn-universe/core": "0.1.2-dev.
|
|
13
|
-
"@saturn-universe/model": "0.1.2-dev.
|
|
14
|
-
"@saturn-universe/plugin-sdk": "0.1.2-dev.
|
|
15
|
-
"@saturn-universe/protocol": "0.1.2-dev.
|
|
16
|
-
"@saturn-universe/runtime": "0.1.2-dev.
|
|
17
|
-
"@saturn-universe/storage": "0.1.2-dev.
|
|
18
|
-
"@saturn-universe/tools": "0.1.2-dev.
|
|
11
|
+
"@saturn-universe/context": "0.1.2-dev.10",
|
|
12
|
+
"@saturn-universe/core": "0.1.2-dev.10",
|
|
13
|
+
"@saturn-universe/model": "0.1.2-dev.10",
|
|
14
|
+
"@saturn-universe/plugin-sdk": "0.1.2-dev.10",
|
|
15
|
+
"@saturn-universe/protocol": "0.1.2-dev.10",
|
|
16
|
+
"@saturn-universe/runtime": "0.1.2-dev.10",
|
|
17
|
+
"@saturn-universe/storage": "0.1.2-dev.10",
|
|
18
|
+
"@saturn-universe/tools": "0.1.2-dev.10",
|
|
19
19
|
"import-meta-resolve": "4.2.0",
|
|
20
20
|
"pino": "10.4.0",
|
|
21
21
|
"semver": "7.7.4",
|