@saturn-universe/runtime-host 0.0.0-stage → 0.1.0
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/LICENSE +661 -0
- package/dist/builtin-plugins/saturn-plugin-ctf/README.md +13 -0
- package/dist/builtin-plugins/saturn-plugin-ctf/index.mjs +1473 -0
- package/dist/builtin-plugins/saturn-plugin-ctf/package.json +10 -0
- package/dist/builtin-plugins/saturn-plugin-ctf/src/board.mjs +321 -0
- package/dist/builtin-plugins/saturn-plugin-ctf/src/ledger.mjs +1143 -0
- package/dist/builtin-plugins/saturn-plugin-ctf/src/platform/ctfd.mjs +154 -0
- package/dist/builtin-plugins/saturn-plugin-ctf/src/platform/ctfplus.mjs +769 -0
- package/dist/builtin-plugins/saturn-plugin-ctf/src/platform/gzctf.mjs +130 -0
- package/dist/builtin-plugins/saturn-plugin-ctf/src/platform/http.mjs +336 -0
- package/dist/builtin-plugins/saturn-plugin-ctf/src/platform/index.mjs +133 -0
- package/dist/builtin-plugins/saturn-plugin-ctf/src/platform/lease.mjs +153 -0
- package/dist/builtin-plugins/saturn-plugin-ctf/src/server.mjs +336 -0
- package/dist/builtin-plugins/saturn-plugin-ctf/src/view.mjs +714 -0
- package/dist/command-dispatch.d.ts +10 -0
- package/dist/command-dispatch.js +65 -0
- package/dist/completion-judge.d.ts +10 -0
- package/dist/completion-judge.js +156 -0
- package/dist/composition.d.ts +108 -0
- package/dist/composition.js +1180 -0
- package/dist/configuration.d.ts +49 -0
- package/dist/configuration.js +51 -0
- package/dist/context-extensions.d.ts +681 -0
- package/dist/context-extensions.js +289 -0
- package/dist/cordis/context-core-plugin.d.ts +35 -0
- package/dist/cordis/context-core-plugin.js +296 -0
- package/dist/cordis/env-probe-plugin.d.ts +27 -0
- package/dist/cordis/env-probe-plugin.js +114 -0
- package/dist/cordis/host-context.d.ts +65 -0
- package/dist/cordis/host-context.js +199 -0
- package/dist/cordis/model-responses-plugin.d.ts +81 -0
- package/dist/cordis/model-responses-plugin.js +209 -0
- package/dist/cordis/plugin-contributions.d.ts +47 -0
- package/dist/cordis/plugin-contributions.js +119 -0
- package/dist/cordis/plugin-lifecycle.d.ts +57 -0
- package/dist/cordis/plugin-lifecycle.js +222 -0
- package/dist/cordis/plugin-loader.d.ts +18 -0
- package/dist/cordis/plugin-loader.js +310 -0
- package/dist/cordis/plugin-sdk-adapter.d.ts +17 -0
- package/dist/cordis/plugin-sdk-adapter.js +283 -0
- package/dist/cordis/required-host-plugin.d.ts +6 -0
- package/dist/cordis/required-host-plugin.js +1 -0
- package/dist/cordis/runtime-hooks-plugin.d.ts +23 -0
- package/dist/cordis/runtime-hooks-plugin.js +103 -0
- package/dist/cordis/sandbox-plugin.d.ts +18 -0
- package/dist/cordis/sandbox-plugin.js +21 -0
- package/dist/cordis/scoped-layers.d.ts +63 -0
- package/dist/cordis/scoped-layers.js +170 -0
- package/dist/cordis/tools/builtin-agent-tools-plugin.d.ts +11 -0
- package/dist/cordis/tools/builtin-agent-tools-plugin.js +171 -0
- package/dist/cordis/tools/index.d.ts +17 -0
- package/dist/cordis/tools/index.js +40 -0
- package/dist/cordis/tools/mcp-tools-plugin.d.ts +7 -0
- package/dist/cordis/tools/mcp-tools-plugin.js +116 -0
- package/dist/cordis/tools/process-manager-plugin.d.ts +11 -0
- package/dist/cordis/tools/process-manager-plugin.js +39 -0
- package/dist/cordis/tools/sandbox-target-tools-plugin.d.ts +13 -0
- package/dist/cordis/tools/sandbox-target-tools-plugin.js +255 -0
- package/dist/cordis/tools/tool-guidance.d.ts +4 -0
- package/dist/cordis/tools/tool-guidance.js +30 -0
- package/dist/cordis/tools/tools-core-plugin.d.ts +128 -0
- package/dist/cordis/tools/tools-core-plugin.js +486 -0
- package/dist/cordis/tools/web-fetch.d.ts +17 -0
- package/dist/cordis/tools/web-fetch.js +529 -0
- package/dist/cordis/tools/web-search-tools-plugin.d.ts +10 -0
- package/dist/cordis/tools/web-search-tools-plugin.js +191 -0
- package/dist/cordis/tools/workspace-tools-plugin.d.ts +8 -0
- package/dist/cordis/tools/workspace-tools-plugin.js +145 -0
- package/dist/env-probe.d.ts +8 -0
- package/dist/env-probe.js +172 -0
- package/dist/host-configuration.d.ts +27 -0
- package/dist/host-configuration.js +185 -0
- package/dist/host-tools.d.ts +19 -0
- package/dist/host-tools.js +30 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +140 -0
- package/dist/ipc.d.ts +24 -0
- package/dist/ipc.js +162 -0
- package/dist/logger.d.ts +11 -0
- package/dist/logger.js +84 -0
- package/dist/mcp-configuration.d.ts +17 -0
- package/dist/mcp-configuration.js +50 -0
- package/dist/modes.d.ts +27 -0
- package/dist/modes.js +472 -0
- package/dist/ownership.d.ts +7 -0
- package/dist/ownership.js +100 -0
- package/dist/plugin-configuration.d.ts +9 -0
- package/dist/plugin-configuration.js +21 -0
- package/dist/plugin-tool-grants.d.ts +18 -0
- package/dist/plugin-tool-grants.js +21 -0
- package/dist/process-workspaces.d.ts +4 -0
- package/dist/process-workspaces.js +28 -0
- package/dist/progress.d.ts +30 -0
- package/dist/progress.js +699 -0
- package/dist/provider-catalog.d.ts +754 -0
- package/dist/provider-catalog.js +471 -0
- package/dist/run-budget.d.ts +24 -0
- package/dist/run-budget.js +47 -0
- package/dist/run-checkpoint.d.ts +2 -0
- package/dist/run-checkpoint.js +52 -0
- package/dist/sandbox-manager.d.ts +111 -0
- package/dist/sandbox-manager.js +1519 -0
- package/dist/session-paths.d.ts +15 -0
- package/dist/session-paths.js +40 -0
- package/dist/side-question.d.ts +14 -0
- package/dist/side-question.js +89 -0
- package/dist/skills-runtime.d.ts +13 -0
- package/dist/skills-runtime.js +243 -0
- package/dist/token-estimator.d.ts +3 -0
- package/dist/token-estimator.js +73 -0
- package/dist/tool-result.d.ts +2 -0
- package/dist/tool-result.js +91 -0
- package/dist/user-config.d.ts +23 -0
- package/dist/user-config.js +36 -0
- package/package.json +28 -3
- package/README.md +0 -3
|
@@ -0,0 +1,1180 @@
|
|
|
1
|
+
import { realpath, stat } from 'node:fs/promises';
|
|
2
|
+
import { randomUUID, createHash } from 'node:crypto';
|
|
3
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
4
|
+
import { RuntimeError, canonicalJson, configForDerivedAgent, earlierDeadline, isTerminalRunStatus, matchesModeSelector, normalizeFileUriForPlatform, reportDiagnostic, validateTeamConfig, validateTeamHintConfig, } from '@saturn-universe/core';
|
|
5
|
+
import { PROJECT_MCP_CONFIG_FILENAME, resolveCredentialMap } from '@saturn-universe/protocol';
|
|
6
|
+
import { createToolExecutor, dataReviewToolSet, isContainedPath } from '@saturn-universe/tools';
|
|
7
|
+
import { createCommandHandler, createContinuationCompletionPolicy, createRuntimeJournal, createAgentLoop, createRunLoop, recoverRuntime, compactSurface, } from '@saturn-universe/runtime';
|
|
8
|
+
import { createHostLogger, redactExportValue } from './logger.js';
|
|
9
|
+
import { createSemanticCompletionJudge } from './completion-judge.js';
|
|
10
|
+
import { loadHostConfiguration } from './host-configuration.js';
|
|
11
|
+
import { freezeContextExtensions } from './context-extensions.js';
|
|
12
|
+
import { createLiveText, runProgress, runTimeline } from './progress.js';
|
|
13
|
+
import { createSkillRegistryService } from './skills-runtime.js';
|
|
14
|
+
import { interactiveToolPolicies, isInteractiveToolPolicy } from './cordis/tools/tools-core-plugin.js';
|
|
15
|
+
import { createToolResultReader } from './tool-result.js';
|
|
16
|
+
import { createRunCheckpoint } from './run-checkpoint.js';
|
|
17
|
+
import { resolvePluginSessionPaths } from './session-paths.js';
|
|
18
|
+
import { answerSideQuestion } from './side-question.js';
|
|
19
|
+
import { startHostContext } from './cordis/host-context.js';
|
|
20
|
+
import { loadModePlugins } from './cordis/plugin-loader.js';
|
|
21
|
+
import { executionTarget, primaryRole } from './cordis/scoped-layers.js';
|
|
22
|
+
import { resolveActiveMode, resolveModeToolLayers } from './modes.js';
|
|
23
|
+
import { resolveRunDefaults, resolveWorkerReasoning, hardLimits } from './provider-catalog.js';
|
|
24
|
+
import { resolveWebSearchKey } from './user-config.js';
|
|
25
|
+
export async function composeRuntime(store, root, options = {}, diagnosticDestination) {
|
|
26
|
+
const resources = {};
|
|
27
|
+
try {
|
|
28
|
+
return await assembleRuntime(resources, store, root, options, diagnosticDestination);
|
|
29
|
+
}
|
|
30
|
+
catch (error) {
|
|
31
|
+
try {
|
|
32
|
+
await resources.hostContext?.dispose();
|
|
33
|
+
}
|
|
34
|
+
finally {
|
|
35
|
+
throw error;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
async function assembleRuntime(resources, store, root, options, diagnosticDestination) {
|
|
40
|
+
const readConfiguration = () => loadHostConfiguration(root, options.configFile);
|
|
41
|
+
const hostConfiguration = await readConfiguration();
|
|
42
|
+
const { catalog, configSource, trustedMcp, mcpServers, mcpServerMeta, mcpJsonError } = hostConfiguration;
|
|
43
|
+
const credentialMap = await resolveCredentialMap(root);
|
|
44
|
+
const entryProfile = options.profile ?? process.env.SATURN_PROVIDER_PROFILE;
|
|
45
|
+
const credential = (ref) => ref.startsWith('env:') ? credentialMap.values.get(ref.slice(4)) : undefined;
|
|
46
|
+
const webSearch = hostConfiguration.webSearch;
|
|
47
|
+
const webSearchKey = resolveWebSearchKey(webSearch, credentialMap.values);
|
|
48
|
+
const secrets = [
|
|
49
|
+
...credentialMap.secrets,
|
|
50
|
+
...(webSearchKey ? [webSearchKey] : []),
|
|
51
|
+
...(catalog?.profiles.map((p) => credentialMap.values.get(p.credentialRef.slice(4)) ?? '') ?? []),
|
|
52
|
+
];
|
|
53
|
+
const logger = createHostLogger(secrets, diagnosticDestination);
|
|
54
|
+
const { activeMode, availableModes, modeBudget, pluginToolGrants } = resolveActiveMode(catalog, options.mode);
|
|
55
|
+
for (const plugin of activeMode.plugins ?? []) {
|
|
56
|
+
const token = plugin.config?.board_token;
|
|
57
|
+
if (typeof token === 'string' && token.trim() && !secrets.includes(token)) {
|
|
58
|
+
secrets.push(token);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
const catalogBoardToken = catalog?.modes?.['ctf@1']?.board_token;
|
|
62
|
+
if (typeof catalogBoardToken === 'string' &&
|
|
63
|
+
catalogBoardToken.trim() &&
|
|
64
|
+
!secrets.includes(catalogBoardToken)) {
|
|
65
|
+
secrets.push(catalogBoardToken);
|
|
66
|
+
}
|
|
67
|
+
const toolLayers = resolveModeToolLayers(activeMode, catalog?.workspaceTools);
|
|
68
|
+
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);
|
|
70
|
+
const pluginStatuses = new Map();
|
|
71
|
+
const skillService = await createSkillRegistryService(root, activeMode, catalog);
|
|
72
|
+
const hash = (value) => createHash('sha256').update(canonicalJson(value)).digest('hex');
|
|
73
|
+
const clock = {
|
|
74
|
+
now: () => new Date().toISOString(),
|
|
75
|
+
async delay(ms, signal) {
|
|
76
|
+
signal.throwIfAborted();
|
|
77
|
+
let timer;
|
|
78
|
+
let abort = () => { };
|
|
79
|
+
try {
|
|
80
|
+
await new Promise((resolve, reject) => {
|
|
81
|
+
timer = setTimeout(resolve, ms);
|
|
82
|
+
abort = () => reject(signal.reason);
|
|
83
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
finally {
|
|
87
|
+
clearTimeout(timer);
|
|
88
|
+
signal.removeEventListener('abort', abort);
|
|
89
|
+
}
|
|
90
|
+
},
|
|
91
|
+
};
|
|
92
|
+
let notifyParentImpl;
|
|
93
|
+
let syncWorkspaceSubpathsImpl;
|
|
94
|
+
const workerLifecycleListeners = new Set();
|
|
95
|
+
async function emitWorkerLifecycle(event) {
|
|
96
|
+
for (const listener of [...workerLifecycleListeners]) {
|
|
97
|
+
try {
|
|
98
|
+
await listener(event);
|
|
99
|
+
}
|
|
100
|
+
catch (error) {
|
|
101
|
+
logger.error({
|
|
102
|
+
code: 'PLUGIN_WORKER_LIFECYCLE_FAILED',
|
|
103
|
+
memberId: event.memberId,
|
|
104
|
+
phase: event.phase,
|
|
105
|
+
message: redactExportValue(error instanceof Error ? error.message : 'Worker lifecycle listener failed', secrets),
|
|
106
|
+
}, 'Plugin worker lifecycle listener failed');
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
const hostContext = await startHostContext(store, root, {
|
|
111
|
+
...(options.hostPlugins ? { requiredPlugins: options.hostPlugins } : {}),
|
|
112
|
+
...(options.hostPluginTimeoutMs !== undefined ? { timeoutMs: options.hostPluginTimeoutMs } : {}),
|
|
113
|
+
activeMode,
|
|
114
|
+
sandbox: {
|
|
115
|
+
...(options.allowUnsafeSandboxFallback ? { allowUnsafeFallback: true } : {}),
|
|
116
|
+
...(options.sandboxRunner ? { runner: options.sandboxRunner } : {}),
|
|
117
|
+
},
|
|
118
|
+
skillService,
|
|
119
|
+
...(webSearch && webSearchKey ? { webSearch: { config: webSearch, apiKey: webSearchKey } } : {}),
|
|
120
|
+
externalPlugins,
|
|
121
|
+
logger,
|
|
122
|
+
pluginHostServices: {
|
|
123
|
+
registerSecret(value) {
|
|
124
|
+
if (value.trim() && !secrets.includes(value))
|
|
125
|
+
secrets.push(value);
|
|
126
|
+
},
|
|
127
|
+
redactValue(value) {
|
|
128
|
+
return redactExportValue(value, secrets);
|
|
129
|
+
},
|
|
130
|
+
resolveSessionPaths(pluginId, sessionId) {
|
|
131
|
+
return resolvePluginSessionPaths(root, sessionId, pluginId);
|
|
132
|
+
},
|
|
133
|
+
reportPluginStatus(pluginId, status) {
|
|
134
|
+
if (!status) {
|
|
135
|
+
pluginStatuses.delete(pluginId);
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
pluginStatuses.set(pluginId, redactExportValue(status, secrets));
|
|
139
|
+
},
|
|
140
|
+
async resolveWorkspaceAssignment({ runId, agentSessionId }) {
|
|
141
|
+
const main = await store.environmentReader.load(runId);
|
|
142
|
+
if (main.route.agentSessionId === agentSessionId)
|
|
143
|
+
return { role: 'main' };
|
|
144
|
+
const team = await store.stateReader.team?.(runId);
|
|
145
|
+
let member = team?.members.find((candidate) => candidate.agentSessionId === agentSessionId);
|
|
146
|
+
if (!member?.parent)
|
|
147
|
+
return undefined;
|
|
148
|
+
// The sandbox inherits a parent assignment when a leaf omits workSubpath.
|
|
149
|
+
while (member?.parent) {
|
|
150
|
+
const env = await store.environmentReader.load(runId, member.agentSessionId);
|
|
151
|
+
const workSubpath = env.config.team?.members.find(({ id }) => id === member?.id)?.workSubpath;
|
|
152
|
+
if (workSubpath) {
|
|
153
|
+
const normalized = workSubpath.trim().replaceAll('\\', '/').replace(/\/+$/, '');
|
|
154
|
+
if (normalized)
|
|
155
|
+
return { role: 'worker', workSubpath: normalized };
|
|
156
|
+
}
|
|
157
|
+
const parentId = member.parent;
|
|
158
|
+
member = team?.members.find(({ id }) => id === parentId);
|
|
159
|
+
}
|
|
160
|
+
return { role: 'worker' };
|
|
161
|
+
},
|
|
162
|
+
async syncWorkspaceSubpaths(context, subpaths) {
|
|
163
|
+
if (!syncWorkspaceSubpathsImpl)
|
|
164
|
+
return { synced: [], skipped: [], partial: false };
|
|
165
|
+
return syncWorkspaceSubpathsImpl(context, subpaths);
|
|
166
|
+
},
|
|
167
|
+
onWorkerLifecycle(listener) {
|
|
168
|
+
workerLifecycleListeners.add(listener);
|
|
169
|
+
return () => {
|
|
170
|
+
workerLifecycleListeners.delete(listener);
|
|
171
|
+
};
|
|
172
|
+
},
|
|
173
|
+
},
|
|
174
|
+
model: {
|
|
175
|
+
catalog,
|
|
176
|
+
entryProfile,
|
|
177
|
+
profile: options.profile,
|
|
178
|
+
taskProfile: options.taskProfile,
|
|
179
|
+
credential,
|
|
180
|
+
hash,
|
|
181
|
+
},
|
|
182
|
+
tools: {
|
|
183
|
+
config: {
|
|
184
|
+
...catalog,
|
|
185
|
+
...(mcpServers ? { mcpServers } : {}),
|
|
186
|
+
...(mcpServerMeta ? { mcpServerMeta } : {}),
|
|
187
|
+
mcpEnvLookup: (name) => credentialMap.values.get(name) ?? process.env[name],
|
|
188
|
+
mcpSecrets: secrets,
|
|
189
|
+
workspaceTools: toolLayers.workspaceTools,
|
|
190
|
+
processManager: toolLayers.processManager,
|
|
191
|
+
builtinAgentTools: toolLayers.builtinAgentTools,
|
|
192
|
+
...pluginToolGrants,
|
|
193
|
+
...(toolLayers.allowedTools ? { allowedTools: toolLayers.allowedTools } : {}),
|
|
194
|
+
...(toolLayers.deniedTools ? { deniedTools: toolLayers.deniedTools } : {}),
|
|
195
|
+
...(activeMode.sandbox?.workerAllowTargetServices !== undefined
|
|
196
|
+
? { workerAllowTargetServices: activeMode.sandbox.workerAllowTargetServices }
|
|
197
|
+
: {}),
|
|
198
|
+
},
|
|
199
|
+
trustedConfig: trustedMcp,
|
|
200
|
+
hash,
|
|
201
|
+
resultReader: createToolResultReader(store.toolReader),
|
|
202
|
+
suppressedGuidanceRoles,
|
|
203
|
+
processManager: {
|
|
204
|
+
async getRunDeadline(runId) {
|
|
205
|
+
const state = await store.stateReader.run(runId);
|
|
206
|
+
return state.deadlineAt ? Date.parse(state.deadlineAt) : undefined;
|
|
207
|
+
},
|
|
208
|
+
onRecordError: (processId) => logger.error({ code: 'PROCESS_RECORD_INVALID', processId }, 'Skipped an invalid process journal; the reservation will not be restarted'),
|
|
209
|
+
},
|
|
210
|
+
previousDataReview: (runId) => store.hasNumericReview(runId),
|
|
211
|
+
notifyParent: (delivery) => {
|
|
212
|
+
if (!notifyParentImpl) {
|
|
213
|
+
return Promise.reject(new RuntimeError('INVALID_RUN_STATE', 'Team notifier is not initialized'));
|
|
214
|
+
}
|
|
215
|
+
return notifyParentImpl(delivery);
|
|
216
|
+
},
|
|
217
|
+
},
|
|
218
|
+
});
|
|
219
|
+
resources.hostContext = hostContext;
|
|
220
|
+
const { lifecycle } = hostContext;
|
|
221
|
+
const reload = (pluginId) => lifecycle.replace(async (active) => {
|
|
222
|
+
const refreshed = await readConfiguration();
|
|
223
|
+
const refreshedMode = resolveActiveMode(refreshed.catalog, activeMode.ref).activeMode;
|
|
224
|
+
return loadModePlugins(refreshedMode, refreshed, logger, {
|
|
225
|
+
active,
|
|
226
|
+
...(pluginId === undefined ? {} : { pluginId }),
|
|
227
|
+
...(options.hostPluginTimeoutMs === undefined ? {} : { timeoutMs: options.hostPluginTimeoutMs }),
|
|
228
|
+
});
|
|
229
|
+
}, pluginId);
|
|
230
|
+
const { saturnTools: tools, saturnProcessManager: processManager, saturnSandbox, saturnModel, saturnContext, saturnHooks: hookRegistry, } = hostContext.ctx;
|
|
231
|
+
const { gateway, resolveFrozenModel } = saturnModel;
|
|
232
|
+
const { composer } = saturnContext;
|
|
233
|
+
const { registry } = tools;
|
|
234
|
+
const dependencies = {
|
|
235
|
+
commit: store,
|
|
236
|
+
reader: store,
|
|
237
|
+
receipt: (id, h) => store.receipt(id, h),
|
|
238
|
+
hash,
|
|
239
|
+
now: clock.now,
|
|
240
|
+
id: randomUUID,
|
|
241
|
+
epoch: store.epoch,
|
|
242
|
+
rootUri: pathToFileURL(root).href,
|
|
243
|
+
stateReader: store.stateReader,
|
|
244
|
+
};
|
|
245
|
+
const admission = createCommandHandler(dependencies);
|
|
246
|
+
const journal = createRuntimeJournal(dependencies);
|
|
247
|
+
async function checkWorkingDirectory(uri) {
|
|
248
|
+
let working;
|
|
249
|
+
try {
|
|
250
|
+
working = await realpath(fileURLToPath(normalizeFileUriForPlatform(uri, process.platform)));
|
|
251
|
+
if (!(await stat(working)).isDirectory())
|
|
252
|
+
throw new Error('Not a directory');
|
|
253
|
+
}
|
|
254
|
+
catch {
|
|
255
|
+
throw new RuntimeError('INVALID_COMMAND', 'Working directory unavailable');
|
|
256
|
+
}
|
|
257
|
+
if (!isContainedPath(root, working))
|
|
258
|
+
throw new RuntimeError('INVALID_COMMAND', 'Working directory must be inside the workspace');
|
|
259
|
+
}
|
|
260
|
+
const environment = {
|
|
261
|
+
async load(runId, agentSessionId) {
|
|
262
|
+
const env = await store.environmentReader.load(runId, agentSessionId);
|
|
263
|
+
return {
|
|
264
|
+
...env,
|
|
265
|
+
workingDirectory: fileURLToPath(normalizeFileUriForPlatform(env.workingDirectory, process.platform)),
|
|
266
|
+
};
|
|
267
|
+
},
|
|
268
|
+
};
|
|
269
|
+
const hooks = (config, env) => hookRegistry.forBindings(config.pluginBindings?.hooks ?? [], executionTarget(env));
|
|
270
|
+
function freezeContributions(config, target) {
|
|
271
|
+
const { toolSnapshot, pluginBindings } = tools.freeze(config, target);
|
|
272
|
+
const bindings = {
|
|
273
|
+
tools: pluginBindings.tools,
|
|
274
|
+
contextProviders: saturnContext.listBindings(target),
|
|
275
|
+
hooks: hookRegistry.list(target),
|
|
276
|
+
};
|
|
277
|
+
return { bindings, ...(toolSnapshot ? { toolSnapshot } : {}) };
|
|
278
|
+
}
|
|
279
|
+
function freezeDerived(config, primary) {
|
|
280
|
+
// Retain the admission-time alternatives for Agent sessions attached after this Run starts.
|
|
281
|
+
const sessionIds = [
|
|
282
|
+
...new Set([
|
|
283
|
+
...tools.agentSessionIds(),
|
|
284
|
+
...saturnContext.agentSessionIds(),
|
|
285
|
+
...hookRegistry.agentSessionIds(),
|
|
286
|
+
]),
|
|
287
|
+
].sort();
|
|
288
|
+
return ['worker', 'search'].flatMap((role) => {
|
|
289
|
+
const base = freezeContributions(config, { role });
|
|
290
|
+
const variants = sessionIds.flatMap((agentSessionId) => {
|
|
291
|
+
const view = freezeContributions(config, { role, agentSessionId });
|
|
292
|
+
return canonicalJson(view.bindings) === canonicalJson(base.bindings)
|
|
293
|
+
? []
|
|
294
|
+
: [{ role, agentSessionId, ...view }];
|
|
295
|
+
});
|
|
296
|
+
return canonicalJson(base.bindings) === canonicalJson(primary)
|
|
297
|
+
? variants
|
|
298
|
+
: [{ role, ...base }, ...variants];
|
|
299
|
+
});
|
|
300
|
+
}
|
|
301
|
+
const executor = createToolExecutor({
|
|
302
|
+
logger,
|
|
303
|
+
registry,
|
|
304
|
+
reader: store.toolReader,
|
|
305
|
+
artifactReader: store.artifactStore,
|
|
306
|
+
state: store.stateReader,
|
|
307
|
+
environment,
|
|
308
|
+
journal,
|
|
309
|
+
policy: tools.policy,
|
|
310
|
+
hooks,
|
|
311
|
+
isAgentIsolated: (runId, agentSessionId) => Boolean(saturnSandbox?.isAgentIsolated(runId, agentSessionId)),
|
|
312
|
+
clock,
|
|
313
|
+
hash,
|
|
314
|
+
id: randomUUID,
|
|
315
|
+
instanceId: randomUUID(),
|
|
316
|
+
epoch: store.epoch,
|
|
317
|
+
});
|
|
318
|
+
async function verifyConfigVersions(config) {
|
|
319
|
+
if (config.providerBinding || config.pluginBindings?.modelProvider)
|
|
320
|
+
resolveFrozenModel(config);
|
|
321
|
+
await registry.verifyBound(config);
|
|
322
|
+
const verifyExtensions = ({ contextProviders, hooks }) => {
|
|
323
|
+
for (const { id, version, scopeKey } of contextProviders)
|
|
324
|
+
saturnContext.resolveProvider(id, version, scopeKey);
|
|
325
|
+
for (const binding of hooks)
|
|
326
|
+
hookRegistry.resolve(binding);
|
|
327
|
+
};
|
|
328
|
+
if (config.pluginBindings)
|
|
329
|
+
verifyExtensions(config.pluginBindings);
|
|
330
|
+
const { toolSnapshot: _snapshot, ...base } = config;
|
|
331
|
+
for (const { bindings, toolSnapshot } of config.pluginBindings?.derived ?? []) {
|
|
332
|
+
await registry.verifyBound({
|
|
333
|
+
...base,
|
|
334
|
+
pluginBindings: bindings,
|
|
335
|
+
...(toolSnapshot ? { toolSnapshot } : {}),
|
|
336
|
+
});
|
|
337
|
+
verifyExtensions(bindings);
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
async function verifyRunVersions(runId) {
|
|
341
|
+
const { config, route } = await environment.load(runId);
|
|
342
|
+
await verifyConfigVersions(config);
|
|
343
|
+
const [owned, turns] = await Promise.all([
|
|
344
|
+
store.stateReader.ownedAgentSessions(runId),
|
|
345
|
+
store.stateReader.turns(runId),
|
|
346
|
+
]);
|
|
347
|
+
const others = new Set([
|
|
348
|
+
...owned.map(({ id }) => id),
|
|
349
|
+
...turns.map(({ agentSessionId }) => agentSessionId),
|
|
350
|
+
]);
|
|
351
|
+
others.delete(route.agentSessionId);
|
|
352
|
+
for (const agentSessionId of others)
|
|
353
|
+
await verifyConfigVersions((await environment.load(runId, agentSessionId)).config);
|
|
354
|
+
for (const turn of turns) {
|
|
355
|
+
for (const call of await store.toolReader.pending(turn.id)) {
|
|
356
|
+
if (call.definition &&
|
|
357
|
+
(call.approval?.status === 'pending' ||
|
|
358
|
+
call.approval?.status === 'approved' ||
|
|
359
|
+
call.status === 'running' ||
|
|
360
|
+
call.status === 'outcome_unknown'))
|
|
361
|
+
await registry.resolveFrozen(call.definition);
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
const liveProgress = createLiveText();
|
|
366
|
+
const agent = createAgentLoop({
|
|
367
|
+
logger,
|
|
368
|
+
environment,
|
|
369
|
+
state: store.stateReader,
|
|
370
|
+
surface: store.surfaceReader,
|
|
371
|
+
journal,
|
|
372
|
+
clock,
|
|
373
|
+
composer,
|
|
374
|
+
gateway,
|
|
375
|
+
hooks,
|
|
376
|
+
executor,
|
|
377
|
+
registry,
|
|
378
|
+
hash,
|
|
379
|
+
id: randomUUID,
|
|
380
|
+
liveText: liveProgress,
|
|
381
|
+
liveAgents: liveProgress,
|
|
382
|
+
checkpointOnContextPressure: true,
|
|
383
|
+
});
|
|
384
|
+
const stop = new AbortController();
|
|
385
|
+
const semanticJudge = createSemanticCompletionJudge({
|
|
386
|
+
gateway,
|
|
387
|
+
hash,
|
|
388
|
+
id: randomUUID,
|
|
389
|
+
signal: stop.signal,
|
|
390
|
+
});
|
|
391
|
+
const loop = createRunLoop({
|
|
392
|
+
...dependencies,
|
|
393
|
+
journal,
|
|
394
|
+
state: store.stateReader,
|
|
395
|
+
environment,
|
|
396
|
+
agent,
|
|
397
|
+
tools: store.toolReader,
|
|
398
|
+
surface: store.surfaceReader,
|
|
399
|
+
freezeWorkerConfig: (config, team, agentSessionId, workerOpts) => tools.freezeWorker(config, team, agentSessionId, config.workerReasoningEffort ? resolveFrozenModel(config).capabilities : undefined, workerOpts),
|
|
400
|
+
verifyPluginVersions: verifyRunVersions,
|
|
401
|
+
completionPolicy: createContinuationCompletionPolicy({ semanticJudge }),
|
|
402
|
+
createCheckpoint: (input, prior) => createRunCheckpoint(store.surfaceReader, input, prior),
|
|
403
|
+
onWorkerStart: async (workerInput) => {
|
|
404
|
+
const workerEnv = await environment.load(workerInput.runId, workerInput.agentSessionId);
|
|
405
|
+
const sessionId = workerEnv.route.sessionId;
|
|
406
|
+
if (saturnSandbox)
|
|
407
|
+
await saturnSandbox.ensureWorkerSandbox({ ...workerInput, sessionId });
|
|
408
|
+
await emitWorkerLifecycle({
|
|
409
|
+
phase: 'started',
|
|
410
|
+
runId: workerInput.runId,
|
|
411
|
+
sessionId,
|
|
412
|
+
memberId: workerInput.memberId,
|
|
413
|
+
...(workerInput.parentMemberId !== undefined ? { parentMemberId: workerInput.parentMemberId } : {}),
|
|
414
|
+
...(workerInput.workSubpath !== undefined ? { workSubpath: workerInput.workSubpath } : {}),
|
|
415
|
+
});
|
|
416
|
+
},
|
|
417
|
+
onWorkerComplete: async (workerInput) => {
|
|
418
|
+
const workerEnv = await environment
|
|
419
|
+
.load(workerInput.runId, workerInput.agentSessionId)
|
|
420
|
+
.catch(() => undefined);
|
|
421
|
+
const sessionId = workerEnv?.route.sessionId;
|
|
422
|
+
let usage;
|
|
423
|
+
try {
|
|
424
|
+
const turns = await store.stateReader.turns(workerInput.runId);
|
|
425
|
+
const workerTurns = turns.filter((turn) => turn.agentSessionId === workerInput.agentSessionId);
|
|
426
|
+
let inputTokens = 0;
|
|
427
|
+
let outputTokens = 0;
|
|
428
|
+
let sawUsage = false;
|
|
429
|
+
for (const turn of workerTurns) {
|
|
430
|
+
for (const attempt of await store.stateReader.modelAttempts(turn.id)) {
|
|
431
|
+
const u = attempt.status === 'responded'
|
|
432
|
+
? attempt.response.usage
|
|
433
|
+
: attempt.status === 'failed'
|
|
434
|
+
? attempt.chargedUsage
|
|
435
|
+
: undefined;
|
|
436
|
+
if (u) {
|
|
437
|
+
inputTokens += u.inputTokens;
|
|
438
|
+
outputTokens += u.outputTokens;
|
|
439
|
+
sawUsage = true;
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
if (sawUsage)
|
|
444
|
+
usage = { inputTokens, outputTokens };
|
|
445
|
+
}
|
|
446
|
+
catch {
|
|
447
|
+
// Worker token aggregation is best-effort telemetry.
|
|
448
|
+
}
|
|
449
|
+
if (saturnSandbox) {
|
|
450
|
+
await saturnSandbox.teardownWorker(workerInput.runId, workerInput.agentSessionId, workerInput.status);
|
|
451
|
+
}
|
|
452
|
+
await emitWorkerLifecycle({
|
|
453
|
+
phase: 'completed',
|
|
454
|
+
runId: workerInput.runId,
|
|
455
|
+
...(sessionId !== undefined ? { sessionId } : {}),
|
|
456
|
+
memberId: workerInput.memberId,
|
|
457
|
+
...(workerInput.parentMemberId !== undefined ? { parentMemberId: workerInput.parentMemberId } : {}),
|
|
458
|
+
...(workerInput.workSubpath !== undefined ? { workSubpath: workerInput.workSubpath } : {}),
|
|
459
|
+
status: workerInput.status,
|
|
460
|
+
...(usage ? { usage } : {}),
|
|
461
|
+
});
|
|
462
|
+
},
|
|
463
|
+
});
|
|
464
|
+
notifyParentImpl = async ({ runId, from, to, messageId, text }) => {
|
|
465
|
+
const { route } = await environment.load(runId);
|
|
466
|
+
const scope = { kind: 'run', workspaceId: route.workspaceId, sessionId: route.sessionId, runId };
|
|
467
|
+
await journal.append(`team:${runId}:notify:${messageId}`, [
|
|
468
|
+
journal.event('run.team.message.sent', scope, { messageId, from, to, text }),
|
|
469
|
+
]);
|
|
470
|
+
void loop.wakeTeam(runId);
|
|
471
|
+
};
|
|
472
|
+
syncWorkspaceSubpathsImpl = async ({ runId, sessionId }, subpaths) => {
|
|
473
|
+
if (!saturnSandbox || !subpaths.length)
|
|
474
|
+
return { synced: [], skipped: [], partial: false };
|
|
475
|
+
return saturnSandbox.syncMainWorkspaceSubpaths(runId, subpaths, sessionId);
|
|
476
|
+
};
|
|
477
|
+
const tasks = new Set();
|
|
478
|
+
const requests = new Set();
|
|
479
|
+
const failures = [];
|
|
480
|
+
const deadlines = new Map();
|
|
481
|
+
const scheduled = new Map();
|
|
482
|
+
let closing = false;
|
|
483
|
+
let closeTask;
|
|
484
|
+
async function cleanupRunProcesses(runId, terminalStatus) {
|
|
485
|
+
executor.clearFileSnapshots(runId);
|
|
486
|
+
const processes = await processManager?.stopRun(runId);
|
|
487
|
+
for (const process of processes ?? []) {
|
|
488
|
+
if (process.status === 'unknown' || !process.terminationConfirmed)
|
|
489
|
+
logger.error({ code: 'PROCESS_CLEANUP_UNCONFIRMED', runId, processId: process.processId }, 'Managed process cleanup requires inspection');
|
|
490
|
+
}
|
|
491
|
+
await saturnSandbox?.teardownRun(runId, terminalStatus);
|
|
492
|
+
}
|
|
493
|
+
function track(work, runId) {
|
|
494
|
+
const tracked = work
|
|
495
|
+
.catch((error) => {
|
|
496
|
+
const diagnosticId = randomUUID();
|
|
497
|
+
failures.push({
|
|
498
|
+
runId,
|
|
499
|
+
code: error instanceof RuntimeError ? error.code : 'DRIVER_FAILED',
|
|
500
|
+
diagnosticId,
|
|
501
|
+
});
|
|
502
|
+
if (failures.length > 100)
|
|
503
|
+
failures.shift();
|
|
504
|
+
reportDiagnostic(logger, error, diagnosticId, 'DRIVER_FAILED', { runId });
|
|
505
|
+
})
|
|
506
|
+
.finally(() => tasks.delete(tracked));
|
|
507
|
+
tasks.add(tracked);
|
|
508
|
+
}
|
|
509
|
+
function schedule(runId, prepare) {
|
|
510
|
+
if (closing)
|
|
511
|
+
return;
|
|
512
|
+
const current = scheduled.get(runId);
|
|
513
|
+
if (current) {
|
|
514
|
+
current.rerun = true;
|
|
515
|
+
if (prepare)
|
|
516
|
+
current.prepareRerun = prepare;
|
|
517
|
+
return current.work;
|
|
518
|
+
}
|
|
519
|
+
clearTimeout(deadlines.get(runId));
|
|
520
|
+
deadlines.delete(runId);
|
|
521
|
+
const entry = { work: Promise.resolve(), rerun: false };
|
|
522
|
+
const releaseRun = lifecycle.trackRun(runId);
|
|
523
|
+
const prepareRun = async (signal) => {
|
|
524
|
+
if (saturnSandbox) {
|
|
525
|
+
const mainEnv = await environment.load(runId);
|
|
526
|
+
await saturnSandbox.ensureMainSandbox(runId, mainEnv.route.agentSessionId, mainEnv.route.sessionId);
|
|
527
|
+
}
|
|
528
|
+
await prepare?.(signal);
|
|
529
|
+
};
|
|
530
|
+
const work = loop
|
|
531
|
+
.drive(runId, stop.signal, prepareRun)
|
|
532
|
+
.catch(async (error) => {
|
|
533
|
+
await cleanupRunProcesses(runId, 'failed').catch(() => { });
|
|
534
|
+
throw error;
|
|
535
|
+
})
|
|
536
|
+
.then(async () => {
|
|
537
|
+
const state = await store.stateReader.run(runId);
|
|
538
|
+
if (isTerminalRunStatus(state.status))
|
|
539
|
+
await cleanupRunProcesses(runId, state.status);
|
|
540
|
+
clearTimeout(deadlines.get(runId));
|
|
541
|
+
deadlines.delete(runId);
|
|
542
|
+
if (!closing && state.status === 'paused' && !state.pluginBlock) {
|
|
543
|
+
const blockedDeadlines = await Promise.all(state.blockedTurnIds.map(async (turnId) => {
|
|
544
|
+
const result = await store.stateReader.turnResult(turnId);
|
|
545
|
+
if (result?.status === 'paused' && result.reason === 'approval')
|
|
546
|
+
return;
|
|
547
|
+
return (await store.stateReader.turn(turnId)).deadlineAt;
|
|
548
|
+
}));
|
|
549
|
+
const nextDeadline = [state.deadlineAt, ...blockedDeadlines].reduce((min, value) => earlierDeadline(min, value), undefined);
|
|
550
|
+
if (!closing && nextDeadline)
|
|
551
|
+
deadlines.set(runId, setTimeout(() => {
|
|
552
|
+
deadlines.delete(runId);
|
|
553
|
+
schedule(runId);
|
|
554
|
+
}, Math.min(2147483647, Math.max(0, Date.parse(nextDeadline) - Date.parse(clock.now())))));
|
|
555
|
+
}
|
|
556
|
+
})
|
|
557
|
+
.finally(async () => {
|
|
558
|
+
if (scheduled.get(runId) !== entry)
|
|
559
|
+
return;
|
|
560
|
+
scheduled.delete(runId);
|
|
561
|
+
if (closing)
|
|
562
|
+
return;
|
|
563
|
+
const state = await store.stateReader.run(runId);
|
|
564
|
+
if (entry.rerun && ['running', 'paused'].includes(state.status) && !state.pluginBlock)
|
|
565
|
+
schedule(runId, entry.prepareRerun);
|
|
566
|
+
})
|
|
567
|
+
.finally(releaseRun);
|
|
568
|
+
entry.work = work;
|
|
569
|
+
scheduled.set(runId, entry);
|
|
570
|
+
track(work, runId);
|
|
571
|
+
return work;
|
|
572
|
+
}
|
|
573
|
+
async function maybeResume(runId, key) {
|
|
574
|
+
if (closing)
|
|
575
|
+
return;
|
|
576
|
+
const state = await store.stateReader.run(runId);
|
|
577
|
+
if (['running', 'paused'].includes(state.status) &&
|
|
578
|
+
((await store.stateReader.team?.(runId))?.members.length ?? 0) > 1) {
|
|
579
|
+
// The Team driver claims a free slot before appending the eligible Turn's resume event.
|
|
580
|
+
const checked = loop.wakeTeam(runId);
|
|
581
|
+
if (checked || state.status === 'running') {
|
|
582
|
+
schedule(runId);
|
|
583
|
+
await checked;
|
|
584
|
+
return;
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
if (state.status !== 'paused')
|
|
588
|
+
return;
|
|
589
|
+
try {
|
|
590
|
+
if (!(await loop.resumeAutomatically(runId, key)))
|
|
591
|
+
return;
|
|
592
|
+
}
|
|
593
|
+
catch (error) {
|
|
594
|
+
if (error instanceof RuntimeError && ['RUN_BLOCKED', 'PLUGIN_VERSION_UNAVAILABLE'].includes(error.code))
|
|
595
|
+
return;
|
|
596
|
+
if (!(error instanceof RuntimeError) ||
|
|
597
|
+
!['INVALID_TRANSITION', 'VERSION_CONFLICT', 'PROJECTION_FAILED'].includes(error.code) ||
|
|
598
|
+
(await store.stateReader.run(runId)).status === 'paused')
|
|
599
|
+
throw error;
|
|
600
|
+
}
|
|
601
|
+
schedule(runId);
|
|
602
|
+
}
|
|
603
|
+
function recoverRuns(runIds) {
|
|
604
|
+
return recoverRuntime({
|
|
605
|
+
reader: store,
|
|
606
|
+
state: store.stateReader,
|
|
607
|
+
environment,
|
|
608
|
+
tools: store.toolReader,
|
|
609
|
+
executor,
|
|
610
|
+
clock,
|
|
611
|
+
hash,
|
|
612
|
+
loop,
|
|
613
|
+
signal: stop.signal,
|
|
614
|
+
}, schedule, runIds);
|
|
615
|
+
}
|
|
616
|
+
async function shutdown() {
|
|
617
|
+
closing = true;
|
|
618
|
+
const stopLifecycle = lifecycle.stop();
|
|
619
|
+
for (const timer of deadlines.values())
|
|
620
|
+
clearTimeout(timer);
|
|
621
|
+
deadlines.clear();
|
|
622
|
+
try {
|
|
623
|
+
await loop.stop();
|
|
624
|
+
}
|
|
625
|
+
finally {
|
|
626
|
+
stop.abort();
|
|
627
|
+
try {
|
|
628
|
+
await Promise.allSettled(requests);
|
|
629
|
+
await stopLifecycle;
|
|
630
|
+
const failed = (await Promise.allSettled(tasks)).find((task) => task.status === 'rejected');
|
|
631
|
+
if (failed)
|
|
632
|
+
throw failed.reason;
|
|
633
|
+
}
|
|
634
|
+
finally {
|
|
635
|
+
await hostContext.dispose();
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
}
|
|
639
|
+
async function withRun(runId, work) {
|
|
640
|
+
const release = lifecycle.trackRun(runId);
|
|
641
|
+
try {
|
|
642
|
+
return await work();
|
|
643
|
+
}
|
|
644
|
+
finally {
|
|
645
|
+
release();
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
const runtime = {
|
|
649
|
+
get status() {
|
|
650
|
+
const ctfBoardUrl = pluginStatuses.get('ctf')?.boardUrl;
|
|
651
|
+
const fallbackBoardUrl = [...pluginStatuses.values()].find((entry) => typeof entry.boardUrl === 'string' && entry.boardUrl.length > 0)?.boardUrl;
|
|
652
|
+
const boardUrl = typeof ctfBoardUrl === 'string' && ctfBoardUrl.length > 0
|
|
653
|
+
? ctfBoardUrl
|
|
654
|
+
: typeof fallbackBoardUrl === 'string'
|
|
655
|
+
? fallbackBoardUrl
|
|
656
|
+
: undefined;
|
|
657
|
+
return {
|
|
658
|
+
...saturnModel.statusSummary(),
|
|
659
|
+
configSource,
|
|
660
|
+
plugins: lifecycle.status(),
|
|
661
|
+
workspaceTools: toolLayers.workspaceTools,
|
|
662
|
+
...(saturnSandbox ? { sandbox: saturnSandbox.status() } : {}),
|
|
663
|
+
...(boardUrl ? { boardUrl } : {}),
|
|
664
|
+
activeMode: {
|
|
665
|
+
ref: activeMode.ref,
|
|
666
|
+
displayName: activeMode.displayName,
|
|
667
|
+
description: activeMode.description,
|
|
668
|
+
},
|
|
669
|
+
availableModes: availableModes.map(({ ref, displayName, description }) => ({
|
|
670
|
+
ref,
|
|
671
|
+
displayName,
|
|
672
|
+
description,
|
|
673
|
+
})),
|
|
674
|
+
modes: Object.keys(catalog?.modes ?? {}),
|
|
675
|
+
skills: Object.keys(catalog?.skills ?? {}),
|
|
676
|
+
discoveredSkills: skillService.summaries(),
|
|
677
|
+
teamPresets: Object.keys(catalog?.teamPresets ?? {}),
|
|
678
|
+
...(tools.mcpServers.length || mcpJsonError
|
|
679
|
+
? {
|
|
680
|
+
mcpServers: [
|
|
681
|
+
...tools.mcpServers,
|
|
682
|
+
...(mcpJsonError
|
|
683
|
+
? [
|
|
684
|
+
{
|
|
685
|
+
id: PROJECT_MCP_CONFIG_FILENAME,
|
|
686
|
+
scope: 'project',
|
|
687
|
+
discovery: 'unavailable',
|
|
688
|
+
toolCount: 0,
|
|
689
|
+
error: mcpJsonError,
|
|
690
|
+
},
|
|
691
|
+
]
|
|
692
|
+
: []),
|
|
693
|
+
],
|
|
694
|
+
}
|
|
695
|
+
: {}),
|
|
696
|
+
driverFailures: failures,
|
|
697
|
+
...(catalog?.taskProfiles ? { taskProfiles: catalog.taskProfiles } : {}),
|
|
698
|
+
...(catalog?.runDefaults
|
|
699
|
+
? {
|
|
700
|
+
runDefaults: {
|
|
701
|
+
...(catalog.runDefaults.permission_mode
|
|
702
|
+
? { permissionMode: catalog.runDefaults.permission_mode }
|
|
703
|
+
: {}),
|
|
704
|
+
...(catalog.runDefaults.reasoning_effort
|
|
705
|
+
? { reasoningEffort: catalog.runDefaults.reasoning_effort }
|
|
706
|
+
: {}),
|
|
707
|
+
...(catalog.runDefaults.worker_reasoning_effort
|
|
708
|
+
? { workerReasoningEffort: catalog.runDefaults.worker_reasoning_effort }
|
|
709
|
+
: {}),
|
|
710
|
+
...(catalog.runDefaults.mode_ref ? { modeRef: catalog.runDefaults.mode_ref } : {}),
|
|
711
|
+
},
|
|
712
|
+
}
|
|
713
|
+
: {}),
|
|
714
|
+
};
|
|
715
|
+
},
|
|
716
|
+
async recover() {
|
|
717
|
+
const processes = await processManager?.recover();
|
|
718
|
+
for (const runId of new Set((processes ?? []).map(({ scope }) => scope.runId))) {
|
|
719
|
+
try {
|
|
720
|
+
const state = await store.stateReader.run(runId);
|
|
721
|
+
if (isTerminalRunStatus(state.status))
|
|
722
|
+
await cleanupRunProcesses(runId);
|
|
723
|
+
}
|
|
724
|
+
catch (error) {
|
|
725
|
+
if (!(error instanceof RuntimeError) || error.code !== 'NOT_FOUND')
|
|
726
|
+
throw error;
|
|
727
|
+
// A database restore does not roll back process side effects or their journals.
|
|
728
|
+
await cleanupRunProcesses(runId);
|
|
729
|
+
logger.info({ code: 'ORPHAN_PROCESS_RUN', runId }, 'Cleaned up a process scope absent from the restored database');
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
return recoverRuns();
|
|
733
|
+
},
|
|
734
|
+
handle(request, requestSignal) {
|
|
735
|
+
if (closing)
|
|
736
|
+
return Promise.reject(new RuntimeError('HOST_CLOSING', 'Host is shutting down'));
|
|
737
|
+
const task = handle(request, requestSignal).finally(() => requests.delete(task));
|
|
738
|
+
requests.add(task);
|
|
739
|
+
return task;
|
|
740
|
+
},
|
|
741
|
+
reloadPlugins: () => reload(),
|
|
742
|
+
reloadPlugin: (pluginId) => reload(pluginId),
|
|
743
|
+
deactivatePlugin: (pluginId) => lifecycle.deactivate(pluginId),
|
|
744
|
+
pluginGenerations: () => lifecycle.status(),
|
|
745
|
+
drainPlugins: () => lifecycle.drain(),
|
|
746
|
+
close: () => (closeTask ??= shutdown()),
|
|
747
|
+
};
|
|
748
|
+
return runtime;
|
|
749
|
+
async function handle(request, requestSignal) {
|
|
750
|
+
const { command, commandId } = request;
|
|
751
|
+
switch (command.type) {
|
|
752
|
+
case 'run.submit': {
|
|
753
|
+
return lifecycle.withAdmission(async () => {
|
|
754
|
+
const identity = { version: 2, hash: hash({ version: 2, command }) };
|
|
755
|
+
const previous = await store.receipt(commandId);
|
|
756
|
+
if (previous?.events.some((e) => e.type === 'run.created' && e.payload.submissionIdentityVersion === 2)) {
|
|
757
|
+
if (previous.events[0].metadata.commandHash !== identity.hash)
|
|
758
|
+
throw new RuntimeError('IDEMPOTENCY_CONFLICT', 'command ID already has another hash');
|
|
759
|
+
const run = previous.events.find((e) => e.type === 'run.created');
|
|
760
|
+
const turn = previous.events.find((e) => e.type === 'turn.queued');
|
|
761
|
+
return { runId: run.payload.runId, turnId: turn.payload.turnId };
|
|
762
|
+
}
|
|
763
|
+
const input = command.input;
|
|
764
|
+
for (const [name, value] of [
|
|
765
|
+
['profile', input.profile],
|
|
766
|
+
['taskProfile', input.taskProfile],
|
|
767
|
+
['teamPreset', input.teamPreset],
|
|
768
|
+
])
|
|
769
|
+
if (value !== undefined && !value.trim())
|
|
770
|
+
throw new RuntimeError('INVALID_CONFIG', `${name} must not be empty`);
|
|
771
|
+
const { model, resolvedModel, profileReasoningEffort } = saturnModel.selectRunModel(input);
|
|
772
|
+
const defaults = catalog?.runDefaults;
|
|
773
|
+
const defaultToolSet = tools.defaultVersion(resolvedModel.capabilities);
|
|
774
|
+
let team = input.config?.team;
|
|
775
|
+
if (input.teamPreset !== undefined) {
|
|
776
|
+
if (input.config?.team !== undefined)
|
|
777
|
+
throw new RuntimeError('INVALID_CONFIG', 'teamPreset and config.team are mutually exclusive');
|
|
778
|
+
if (!catalog?.teamPresets || !Object.hasOwn(catalog.teamPresets, input.teamPreset))
|
|
779
|
+
throw new RuntimeError('INVALID_CONFIG', 'Unknown team preset');
|
|
780
|
+
const preset = catalog.teamPresets[input.teamPreset];
|
|
781
|
+
const userPrompt = input.content
|
|
782
|
+
.flatMap((part) => (part.type === 'text' ? [part.text] : []))
|
|
783
|
+
.join('\n')
|
|
784
|
+
.trim();
|
|
785
|
+
team = {
|
|
786
|
+
...(preset.concurrency !== undefined ? { concurrency: preset.concurrency } : {}),
|
|
787
|
+
members: preset.members.map((member) => ({
|
|
788
|
+
id: member.id,
|
|
789
|
+
parent: member.parent,
|
|
790
|
+
task: member.task.split('{{prompt}}').join(userPrompt || '(empty)'),
|
|
791
|
+
...(member.sandbox_profile ? { sandboxProfile: member.sandbox_profile } : {}),
|
|
792
|
+
...(member.work_subpath ? { workSubpath: member.work_subpath } : {}),
|
|
793
|
+
})),
|
|
794
|
+
};
|
|
795
|
+
}
|
|
796
|
+
const teamHint = input.teamHint ?? input.config?.teamHint;
|
|
797
|
+
if (team && teamHint)
|
|
798
|
+
throw new RuntimeError('INVALID_CONFIG', 'team and teamHint are mutually exclusive');
|
|
799
|
+
if (team) {
|
|
800
|
+
validateTeamConfig(team);
|
|
801
|
+
if (activeMode.ref === 'ctf@1' || activeMode.ref.startsWith('ctf@')) {
|
|
802
|
+
for (const member of team.members) {
|
|
803
|
+
if (member.parent !== 'main')
|
|
804
|
+
continue;
|
|
805
|
+
if (typeof member.workSubpath !== 'string' || !member.workSubpath.trim()) {
|
|
806
|
+
throw new RuntimeError('INVALID_TEAM_CONFIG', `In ctf@1 mode, Depth-1 worker "${member.id}" must provide a non-empty workSubpath`);
|
|
807
|
+
}
|
|
808
|
+
}
|
|
809
|
+
}
|
|
810
|
+
}
|
|
811
|
+
if (teamHint)
|
|
812
|
+
validateTeamHintConfig(teamHint);
|
|
813
|
+
if (input.config?.modeRef !== undefined &&
|
|
814
|
+
!matchesModeSelector(input.config.modeRef, activeMode.ref, availableModes))
|
|
815
|
+
throw new RuntimeError('MODE_MISMATCH', `Host is running in mode ${activeMode.ref}; cannot submit run for mode ${input.config.modeRef}`);
|
|
816
|
+
const { planner: _ignoredPlanner, ...restInputConfig } = input.config ?? {};
|
|
817
|
+
const effectivePermissionMode = input.permissionMode ?? toolLayers.permissionMode ?? defaults?.permission_mode;
|
|
818
|
+
const selectedConfig = {
|
|
819
|
+
...resolveRunDefaults(model, defaultToolSet !== '1'
|
|
820
|
+
? {
|
|
821
|
+
tool_set_version: defaultToolSet,
|
|
822
|
+
...defaults,
|
|
823
|
+
}
|
|
824
|
+
: defaults, {
|
|
825
|
+
capabilities: resolvedModel.capabilities,
|
|
826
|
+
...(profileReasoningEffort ? { profileReasoningEffort } : {}),
|
|
827
|
+
modeBudget,
|
|
828
|
+
}),
|
|
829
|
+
...restInputConfig,
|
|
830
|
+
modeRef: activeMode.ref,
|
|
831
|
+
...(activeMode.team?.maxDepth !== undefined ? { teamMaxDepth: activeMode.team.maxDepth } : {}),
|
|
832
|
+
...(activeMode.team?.asyncCoordinator !== undefined
|
|
833
|
+
? { teamAsyncCoordinator: activeMode.team.asyncCoordinator }
|
|
834
|
+
: {}),
|
|
835
|
+
...(activeMode.team?.coordinatorPollIntervalMs !== undefined
|
|
836
|
+
? { coordinatorPollIntervalMs: activeMode.team.coordinatorPollIntervalMs }
|
|
837
|
+
: {}),
|
|
838
|
+
...(activeMode.team?.workerSoftCheckpointMs !== undefined
|
|
839
|
+
? { workerSoftCheckpointMs: activeMode.team.workerSoftCheckpointMs }
|
|
840
|
+
: {}),
|
|
841
|
+
...(activeMode.team?.maxActiveDepth1 !== undefined
|
|
842
|
+
? { teamMaxActiveDepth1: activeMode.team.maxActiveDepth1 }
|
|
843
|
+
: {}),
|
|
844
|
+
...(activeMode.team?.maxConcurrency !== undefined
|
|
845
|
+
? { teamMaxConcurrency: activeMode.team.maxConcurrency }
|
|
846
|
+
: {}),
|
|
847
|
+
model,
|
|
848
|
+
...(effectivePermissionMode
|
|
849
|
+
? { policyVersion: interactiveToolPolicies[effectivePermissionMode] }
|
|
850
|
+
: {}),
|
|
851
|
+
...(team ? { team } : {}),
|
|
852
|
+
...(teamHint ? { teamHint } : {}),
|
|
853
|
+
providerBinding: resolvedModel.binding,
|
|
854
|
+
};
|
|
855
|
+
if (!effectivePermissionMode && isInteractiveToolPolicy(selectedConfig.policyVersion))
|
|
856
|
+
throw new RuntimeError('INVALID_CONFIG', 'Select interactive tool permissions explicitly');
|
|
857
|
+
const dataReview = selectedConfig.toolSetVersion === dataReviewToolSet;
|
|
858
|
+
if (dataReview && (team || teamHint || input.skillRefs?.length || input.config?.modeRef))
|
|
859
|
+
throw new RuntimeError('INVALID_CONFIG', 'Data review accepts only its built-in tools');
|
|
860
|
+
const withContext = dataReview
|
|
861
|
+
? { ...selectedConfig, continuation: { enabled: false } }
|
|
862
|
+
: {
|
|
863
|
+
...selectedConfig,
|
|
864
|
+
...(await freezeContextExtensions(root, activeMode, catalog?.skills, input.skillRefs)),
|
|
865
|
+
};
|
|
866
|
+
if (input.workingDirectoryUri)
|
|
867
|
+
await checkWorkingDirectory(input.workingDirectoryUri);
|
|
868
|
+
saturnModel.requireActive(model);
|
|
869
|
+
resolveFrozenModel(withContext);
|
|
870
|
+
for (const key of Object.keys(hardLimits)) {
|
|
871
|
+
const value = withContext.limits[key];
|
|
872
|
+
if (value !== undefined && value > hardLimits[key])
|
|
873
|
+
throw new RuntimeError('INVALID_CONFIG', 'Run limits exceed hard maximum');
|
|
874
|
+
}
|
|
875
|
+
const prepareAgentConfig = (config, role, agentSessionId) => {
|
|
876
|
+
const effectiveRole = role === 'main' ? primaryRole(config) : role;
|
|
877
|
+
const { bindings, toolSnapshot } = freezeContributions(config, {
|
|
878
|
+
role: effectiveRole,
|
|
879
|
+
agentSessionId,
|
|
880
|
+
});
|
|
881
|
+
const derived = role === 'worker' ? [] : freezeDerived(config, bindings);
|
|
882
|
+
return {
|
|
883
|
+
...(role === 'worker' ? resolveWorkerReasoning(config, resolvedModel.capabilities) : config),
|
|
884
|
+
...(toolSnapshot ? { toolSnapshot } : {}),
|
|
885
|
+
pluginBindings: {
|
|
886
|
+
...bindings,
|
|
887
|
+
modelProvider: {
|
|
888
|
+
profileRef: model.profileRef,
|
|
889
|
+
providerId: resolvedModel.binding.profileId,
|
|
890
|
+
revision: resolvedModel.binding.profileRevision,
|
|
891
|
+
compatibilityKey: resolvedModel.binding.compatibilityKey,
|
|
892
|
+
},
|
|
893
|
+
...(derived.length ? { derived } : {}),
|
|
894
|
+
},
|
|
895
|
+
};
|
|
896
|
+
};
|
|
897
|
+
// Legacy receipts hash the resolved command, including its main Agent's bindings.
|
|
898
|
+
const previousMain = previous?.events.find((event) => event.type === 'run.agent.attached');
|
|
899
|
+
const result = (await admission.handle(commandId, {
|
|
900
|
+
type: 'run.submit',
|
|
901
|
+
input: {
|
|
902
|
+
workspaceId: input.workspaceId,
|
|
903
|
+
sessionId: input.sessionId,
|
|
904
|
+
content: input.content,
|
|
905
|
+
config: previousMain
|
|
906
|
+
? prepareAgentConfig(withContext, 'main', previousMain.payload.membership.agentSessionId)
|
|
907
|
+
: withContext,
|
|
908
|
+
...(input.workingDirectoryUri ? { workingDirectoryUri: input.workingDirectoryUri } : {}),
|
|
909
|
+
},
|
|
910
|
+
}, previous ? undefined : identity, prepareAgentConfig));
|
|
911
|
+
if (!previous)
|
|
912
|
+
schedule(result.runId);
|
|
913
|
+
return { runId: result.runId, turnId: result.turnId };
|
|
914
|
+
});
|
|
915
|
+
}
|
|
916
|
+
case 'run.steer':
|
|
917
|
+
await loop.steer(commandId, command);
|
|
918
|
+
return { runId: command.runId, accepted: true };
|
|
919
|
+
case 'run.cancel': {
|
|
920
|
+
return withRun(command.runId, async () => {
|
|
921
|
+
const { work } = await loop.requestCancel(command.runId, commandId, command.reason);
|
|
922
|
+
clearTimeout(deadlines.get(command.runId));
|
|
923
|
+
deadlines.delete(command.runId);
|
|
924
|
+
const done = lifecycle.trackRun(command.runId);
|
|
925
|
+
track(work.then(() => cleanupRunProcesses(command.runId, 'cancelled')).finally(done), command.runId);
|
|
926
|
+
return { runId: command.runId, cursor: await store.head() };
|
|
927
|
+
});
|
|
928
|
+
}
|
|
929
|
+
case 'run.resume': {
|
|
930
|
+
return withRun(command.runId, async () => {
|
|
931
|
+
const previous = await store.receipt(commandId);
|
|
932
|
+
const identity = { version: 2, hash: hash({ version: 2, command }) };
|
|
933
|
+
const created = previous?.events.find((event) => event.type === 'run.created');
|
|
934
|
+
if (created) {
|
|
935
|
+
if (created.metadata.commandHash !== identity.hash)
|
|
936
|
+
throw new RuntimeError('IDEMPOTENCY_CONFLICT', 'command ID already has another hash');
|
|
937
|
+
return { runId: created.payload.runId, cursor: await store.head() };
|
|
938
|
+
}
|
|
939
|
+
const { runId } = command;
|
|
940
|
+
const state = await store.stateReader.run(runId);
|
|
941
|
+
if (state.status === 'failed') {
|
|
942
|
+
const { route, config: original, workingDirectory } = await store.environmentReader.load(runId);
|
|
943
|
+
if (original.modeRef && !matchesModeSelector(original.modeRef, activeMode.ref, availableModes))
|
|
944
|
+
throw new RuntimeError('MODE_MISMATCH', `Host is running in mode ${activeMode.ref}; checkpoint run belongs to mode ${original.modeRef}`);
|
|
945
|
+
const terminal = (await store.receipt(`run:${runId}:terminal`))?.events.find((event) => event.type === 'run.failed');
|
|
946
|
+
const checkpoint = terminal?.payload.error.checkpoint;
|
|
947
|
+
if (!checkpoint)
|
|
948
|
+
throw new RuntimeError('INVALID_TRANSITION', 'This Run has no resumable checkpoint');
|
|
949
|
+
const surface = await store.surfaceReader.read(route.agentSessionId);
|
|
950
|
+
const originalInput = surface.items.find(({ message }) => message.id === checkpoint.originalInputId)?.message;
|
|
951
|
+
if (originalInput?.role !== 'user')
|
|
952
|
+
throw new RuntimeError('INVALID_HISTORY', 'Checkpoint input is missing');
|
|
953
|
+
await verifyConfigVersions(original);
|
|
954
|
+
saturnModel.verifyCheckpointCredential(original);
|
|
955
|
+
await checkWorkingDirectory(workingDirectory);
|
|
956
|
+
const result = (await admission.handle(commandId, {
|
|
957
|
+
type: 'run.submit',
|
|
958
|
+
input: {
|
|
959
|
+
workspaceId: route.workspaceId,
|
|
960
|
+
sessionId: route.sessionId,
|
|
961
|
+
workingDirectoryUri: workingDirectory,
|
|
962
|
+
config: { ...original, checkpoint },
|
|
963
|
+
content: originalInput.content,
|
|
964
|
+
},
|
|
965
|
+
}, identity, (config, role, agentSessionId) => role === 'worker'
|
|
966
|
+
? resolveWorkerReasoning(configForDerivedAgent(config, role, agentSessionId), config.workerReasoningEffort ? resolveFrozenModel(config).capabilities : undefined)
|
|
967
|
+
: config));
|
|
968
|
+
schedule(result.runId);
|
|
969
|
+
return { runId: result.runId, cursor: await store.head() };
|
|
970
|
+
}
|
|
971
|
+
if (state.pluginBlock) {
|
|
972
|
+
await loop.checkPluginVersions(runId);
|
|
973
|
+
if (state.status === 'paused') {
|
|
974
|
+
try {
|
|
975
|
+
await loop.resume(runId, commandId);
|
|
976
|
+
}
|
|
977
|
+
catch (error) {
|
|
978
|
+
if (!(error instanceof RuntimeError) ||
|
|
979
|
+
error.code !== 'RUN_BLOCKED' ||
|
|
980
|
+
!state.unresolvedCallIds.length)
|
|
981
|
+
throw error;
|
|
982
|
+
await recoverRuns([runId]);
|
|
983
|
+
return { runId, cursor: await store.head() };
|
|
984
|
+
}
|
|
985
|
+
}
|
|
986
|
+
}
|
|
987
|
+
else
|
|
988
|
+
await loop.resume(runId, commandId);
|
|
989
|
+
schedule(runId);
|
|
990
|
+
return { runId: command.runId, cursor: await store.head() };
|
|
991
|
+
});
|
|
992
|
+
}
|
|
993
|
+
case 'tool.approval.resolve': {
|
|
994
|
+
const call = await store.toolReader.read(command.decision.toolCallId);
|
|
995
|
+
return withRun(call.runId, async () => {
|
|
996
|
+
await executor.resolveApproval(command.decision, commandId, command.resume);
|
|
997
|
+
if (command.resume !== false)
|
|
998
|
+
await maybeResume(call.runId, `approval:${command.decision.approvalId}:resume`);
|
|
999
|
+
return {
|
|
1000
|
+
approvalId: command.decision.approvalId,
|
|
1001
|
+
cursor: await store.head(),
|
|
1002
|
+
};
|
|
1003
|
+
});
|
|
1004
|
+
}
|
|
1005
|
+
case 'tool.reconcile': {
|
|
1006
|
+
const call = await store.toolReader.read(command.toolCallId);
|
|
1007
|
+
return withRun(call.runId, async () => {
|
|
1008
|
+
await executor.reconcile(command.toolCallId, command.decision, commandId);
|
|
1009
|
+
await maybeResume(call.runId, `reconcile:${commandId}:resume`);
|
|
1010
|
+
return {
|
|
1011
|
+
toolCallId: command.toolCallId,
|
|
1012
|
+
cursor: await store.head(),
|
|
1013
|
+
};
|
|
1014
|
+
});
|
|
1015
|
+
}
|
|
1016
|
+
case 'session.query':
|
|
1017
|
+
return (await store.sessionDetails(command.sessionId));
|
|
1018
|
+
case 'session.btw': {
|
|
1019
|
+
const signal = requestSignal ? AbortSignal.any([requestSignal, stop.signal]) : stop.signal;
|
|
1020
|
+
signal.throwIfAborted();
|
|
1021
|
+
const { sessionId, agentSessionId, question } = command;
|
|
1022
|
+
const details = await store.sessionDetails(sessionId);
|
|
1023
|
+
if (details.id !== sessionId)
|
|
1024
|
+
throw new RuntimeError('NOT_FOUND', 'Agent session does not belong to the requested session');
|
|
1025
|
+
if (!details.latestRun)
|
|
1026
|
+
throw new RuntimeError('BTW_NO_CONTEXT', 'The session has no conversation to ask about');
|
|
1027
|
+
const { route, config } = await environment
|
|
1028
|
+
.load(details.latestRun.id, agentSessionId)
|
|
1029
|
+
.catch(async (error) => {
|
|
1030
|
+
if (!agentSessionId || !(error instanceof RuntimeError) || error.code !== 'NOT_FOUND')
|
|
1031
|
+
throw error;
|
|
1032
|
+
const satellite = await store.sessionDetails(agentSessionId);
|
|
1033
|
+
if (satellite.member?.parentSessionId !== sessionId || !satellite.latestRun)
|
|
1034
|
+
throw error;
|
|
1035
|
+
return environment.load(satellite.latestRun.id, agentSessionId);
|
|
1036
|
+
});
|
|
1037
|
+
const { runId } = route;
|
|
1038
|
+
const snapshot = await store.contextReader.read(route.agentSessionId, runId);
|
|
1039
|
+
const turn = snapshot.surface.items
|
|
1040
|
+
.filter((item) => item.active && item.message.runId === runId)
|
|
1041
|
+
.at(-1);
|
|
1042
|
+
if (!turn)
|
|
1043
|
+
throw new RuntimeError('BTW_NO_CONTEXT', 'The agent has no committed conversation to ask about');
|
|
1044
|
+
const turnId = turn.message.turnId;
|
|
1045
|
+
const previous = (await store.stateReader.modelAttempts(turnId))
|
|
1046
|
+
.filter(({ request }) => request.context.surfaceSeq + 2 <= snapshot.surface.lastStreamSeq)
|
|
1047
|
+
.at(-1)?.request;
|
|
1048
|
+
signal.throwIfAborted();
|
|
1049
|
+
const assembly = await composer.assembleSideContext({ ...route, turnId, config, signal }, snapshot, previous);
|
|
1050
|
+
return answerSideQuestion({ gateway, hash, signal, requestId: randomUUID() }, { assembly, config, route, turnId, question });
|
|
1051
|
+
}
|
|
1052
|
+
case 'session.list':
|
|
1053
|
+
return (await store.sessionList(command));
|
|
1054
|
+
case 'session.export': {
|
|
1055
|
+
const { platformCredentials, ...page } = await store.sessionExport(command);
|
|
1056
|
+
const exportSecrets = [...secrets, ...platformCredentials];
|
|
1057
|
+
return {
|
|
1058
|
+
...page,
|
|
1059
|
+
records: page.records.map((record) => ({
|
|
1060
|
+
...record,
|
|
1061
|
+
payload: redactExportValue(record.payload, exportSecrets),
|
|
1062
|
+
})),
|
|
1063
|
+
};
|
|
1064
|
+
}
|
|
1065
|
+
case 'session.usage': {
|
|
1066
|
+
const usage = await store.sessionUsage(command.sessionId);
|
|
1067
|
+
const targetModel = usage.model ?? saturnModel.defaultModel;
|
|
1068
|
+
let contextWindow;
|
|
1069
|
+
if (targetModel) {
|
|
1070
|
+
try {
|
|
1071
|
+
contextWindow = saturnModel.providers.resolve(targetModel).capabilities.contextWindow;
|
|
1072
|
+
}
|
|
1073
|
+
catch {
|
|
1074
|
+
// Model may no longer be registered; omit contextWindow cleanly.
|
|
1075
|
+
}
|
|
1076
|
+
}
|
|
1077
|
+
const latestRunId = (await store.sessionDetails(command.sessionId).catch(() => undefined))?.latestRun
|
|
1078
|
+
?.id;
|
|
1079
|
+
let liveOutputTokensPerSec;
|
|
1080
|
+
if (latestRunId) {
|
|
1081
|
+
const mainEnv = await store.environmentReader.load(latestRunId).catch(() => undefined);
|
|
1082
|
+
if (mainEnv) {
|
|
1083
|
+
liveOutputTokensPerSec = liveProgress.sessionMetrics(mainEnv.route.agentSessionId)?.outputTokensPerSec;
|
|
1084
|
+
}
|
|
1085
|
+
}
|
|
1086
|
+
const report = {
|
|
1087
|
+
...usage,
|
|
1088
|
+
...(targetModel ? { modelId: targetModel.modelId } : {}),
|
|
1089
|
+
...(contextWindow !== undefined ? { contextWindow } : {}),
|
|
1090
|
+
...(targetModel ? saturnModel.pricingForModel(targetModel) : {}),
|
|
1091
|
+
...(liveOutputTokensPerSec !== undefined
|
|
1092
|
+
? {
|
|
1093
|
+
latest: {
|
|
1094
|
+
inputTokens: usage.latest?.inputTokens ?? 0,
|
|
1095
|
+
cachedInputTokens: usage.latest?.cachedInputTokens ?? 0,
|
|
1096
|
+
outputTokens: usage.latest?.outputTokens ?? 0,
|
|
1097
|
+
reasoningTokens: usage.latest?.reasoningTokens ?? 0,
|
|
1098
|
+
outputTokensPerSec: liveOutputTokensPerSec,
|
|
1099
|
+
},
|
|
1100
|
+
}
|
|
1101
|
+
: {}),
|
|
1102
|
+
};
|
|
1103
|
+
return report;
|
|
1104
|
+
}
|
|
1105
|
+
case 'session.history': {
|
|
1106
|
+
const started = performance.now();
|
|
1107
|
+
const page = await store.sessionHistory(command);
|
|
1108
|
+
if (!command.before)
|
|
1109
|
+
logger.info({
|
|
1110
|
+
sessionId: command.sessionId,
|
|
1111
|
+
historyFirstPageMs: Math.round(performance.now() - started),
|
|
1112
|
+
}, 'Session history loaded');
|
|
1113
|
+
return page;
|
|
1114
|
+
}
|
|
1115
|
+
case 'session.history.message':
|
|
1116
|
+
return await store.sessionHistory(command);
|
|
1117
|
+
case 'run.model': {
|
|
1118
|
+
const { config } = await store.environmentReader.load(command.runId);
|
|
1119
|
+
return saturnModel.modelDisplay(config.model, config.responses.reasoning?.effort);
|
|
1120
|
+
}
|
|
1121
|
+
case 'run.query': {
|
|
1122
|
+
const details = (await store.runDetails(command.runId));
|
|
1123
|
+
return details;
|
|
1124
|
+
}
|
|
1125
|
+
case 'team.query':
|
|
1126
|
+
case 'team.inbox': {
|
|
1127
|
+
const team = await store.stateReader.team?.(command.runId);
|
|
1128
|
+
if (!team)
|
|
1129
|
+
throw new RuntimeError('TEAM_NOT_FOUND', 'Run has no team');
|
|
1130
|
+
if (command.type === 'team.query') {
|
|
1131
|
+
const { runId, concurrency, members, tasks } = team;
|
|
1132
|
+
const { route } = await store.environmentReader.load(runId);
|
|
1133
|
+
const result = {
|
|
1134
|
+
runId,
|
|
1135
|
+
sessionId: route.sessionId,
|
|
1136
|
+
concurrency,
|
|
1137
|
+
members,
|
|
1138
|
+
tasks,
|
|
1139
|
+
};
|
|
1140
|
+
return result;
|
|
1141
|
+
}
|
|
1142
|
+
const { memberId } = command;
|
|
1143
|
+
if (memberId && !team.members.some((member) => member.id === memberId))
|
|
1144
|
+
throw new RuntimeError('TEAM_MEMBER_NOT_FOUND', 'Unknown team member');
|
|
1145
|
+
const inbox = memberId ? team.inbox.filter((message) => message.to === memberId) : team.inbox;
|
|
1146
|
+
const result = { runId: team.runId, inbox };
|
|
1147
|
+
return result;
|
|
1148
|
+
}
|
|
1149
|
+
case 'run.progress':
|
|
1150
|
+
return runProgress(store, command, liveProgress);
|
|
1151
|
+
case 'run.timeline':
|
|
1152
|
+
return runTimeline(store, command);
|
|
1153
|
+
case 'surface.compact':
|
|
1154
|
+
return compactSurface({ ...dependencies, environment, surfaceReader: store.surfaceReader, gateway, logger }, commandId, command);
|
|
1155
|
+
case 'context.query': {
|
|
1156
|
+
const { route } = await environment.load(command.runId);
|
|
1157
|
+
const snapshot = await store.contextReader.read(route.agentSessionId, command.runId);
|
|
1158
|
+
const result = {
|
|
1159
|
+
generation: snapshot.generation,
|
|
1160
|
+
throughPosition: snapshot.throughPosition,
|
|
1161
|
+
surfaceSeq: snapshot.surface.lastStreamSeq,
|
|
1162
|
+
pendingRequestIds: snapshot.surface.pendingRequestIds,
|
|
1163
|
+
runState: snapshot.runState,
|
|
1164
|
+
...(snapshot.activeRequest
|
|
1165
|
+
? {
|
|
1166
|
+
activeRequest: {
|
|
1167
|
+
id: snapshot.activeRequest.id,
|
|
1168
|
+
assemblyHash: snapshot.activeRequest.context.assemblyHash,
|
|
1169
|
+
selectedMessageIds: snapshot.activeRequest.context.selectedMessageIds,
|
|
1170
|
+
},
|
|
1171
|
+
}
|
|
1172
|
+
: {}),
|
|
1173
|
+
};
|
|
1174
|
+
return result;
|
|
1175
|
+
}
|
|
1176
|
+
default:
|
|
1177
|
+
return admission.handle(commandId, command);
|
|
1178
|
+
}
|
|
1179
|
+
}
|
|
1180
|
+
}
|