@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.
- 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 +1 -0
- package/dist/composition.d.ts +20 -56
- package/dist/composition.js +232 -75
- package/dist/context-extensions.d.ts +10 -0
- package/dist/context-extensions.js +5 -0
- package/dist/cordis/plugin-lifecycle.d.ts +1 -0
- package/dist/cordis/plugin-lifecycle.js +3 -0
- 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 +1 -1
- package/dist/cordis/tools/builtin-agent-tools-plugin.js +15 -1
- package/dist/cordis/tools/index.d.ts +3 -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 +13 -0
- package/dist/index.js +1 -1
- package/dist/mode-configuration.d.ts +5 -0
- package/dist/modes.js +25 -9
- package/dist/provider-catalog.d.ts +5 -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/package.json +9 -9
|
@@ -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/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.8",
|
|
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.8",
|
|
12
|
+
"@saturn-universe/core": "0.1.2-dev.8",
|
|
13
|
+
"@saturn-universe/model": "0.1.2-dev.8",
|
|
14
|
+
"@saturn-universe/plugin-sdk": "0.1.2-dev.8",
|
|
15
|
+
"@saturn-universe/protocol": "0.1.2-dev.8",
|
|
16
|
+
"@saturn-universe/runtime": "0.1.2-dev.8",
|
|
17
|
+
"@saturn-universe/storage": "0.1.2-dev.8",
|
|
18
|
+
"@saturn-universe/tools": "0.1.2-dev.8",
|
|
19
19
|
"import-meta-resolve": "4.2.0",
|
|
20
20
|
"pino": "10.4.0",
|
|
21
21
|
"semver": "7.7.4",
|