@saturn-universe/runtime-host 0.1.2-dev.7 → 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/composition.js +184 -46
- package/dist/context-extensions.d.ts +10 -0
- package/dist/context-extensions.js +5 -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 +1 -0
- package/dist/cordis/tools/index.js +2 -2
- package/dist/cordis/tools/tools-core-plugin.js +13 -0
- package/dist/mode-configuration.d.ts +5 -0
- package/dist/modes.js +25 -9
- package/dist/provider-catalog.d.ts +5 -0
- package/dist/session-mode-runtime.d.ts +23 -3
- package/dist/session-mode-runtime.js +64 -10
- package/package.json +9 -9
|
@@ -171,10 +171,10 @@ function matchesScopeFilters(item, categorySet, idSet) {
|
|
|
171
171
|
|
|
172
172
|
export default {
|
|
173
173
|
id: 'ctf',
|
|
174
|
-
version: '0.1.2-dev.
|
|
174
|
+
version: '0.1.2-dev.8',
|
|
175
175
|
kind: 'saturn-registrar',
|
|
176
176
|
apiVersion: 1,
|
|
177
|
-
sdkVersion: '0.1.2-dev.
|
|
177
|
+
sdkVersion: '0.1.2-dev.8',
|
|
178
178
|
async setup(api, config = {}) {
|
|
179
179
|
const { boardToken, boardPublicHost, ...boardSettings } = settingsFor(config);
|
|
180
180
|
if (boardToken) api.registerSecret?.(boardToken);
|
package/dist/composition.js
CHANGED
|
@@ -2,7 +2,7 @@ import { realpath, stat } from 'node:fs/promises';
|
|
|
2
2
|
import { randomUUID, createHash } from 'node:crypto';
|
|
3
3
|
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
4
4
|
import path from 'node:path';
|
|
5
|
-
import { RuntimeError, canonicalJson, configForDerivedAgent, earlierDeadline, isTerminalRunStatus, matchesModeSelector, normalizeFileUriForPlatform, reportDiagnostic, validateTeamConfig, validateTeamHintConfig, } from '@saturn-universe/core';
|
|
5
|
+
import { RuntimeError, canonicalJson, configForDerivedAgent, earlierDeadline, isTerminalRunStatus, matchesModeSelector, resolveModeSelector, isLimited, normalizeFileUriForPlatform, reportDiagnostic, defaultTeamConcurrency, validateTeamConfig, validateTeamHintConfig, } from '@saturn-universe/core';
|
|
6
6
|
import { PROJECT_MCP_CONFIG_FILENAME, resolveCredentialMap } from '@saturn-universe/protocol';
|
|
7
7
|
import { createProcessManager, createToolExecutor, dataReviewToolSet, isContainedPath, } from '@saturn-universe/tools';
|
|
8
8
|
import { createCommandHandler, createContinuationCompletionPolicy, createRuntimeJournal, createAgentLoop, createRunLoop, recoverRuntime, compactSurface, } from '@saturn-universe/runtime';
|
|
@@ -40,8 +40,21 @@ export async function composeRuntime(store, root, options = {}, diagnosticDestin
|
|
|
40
40
|
// Container ownership labels belong to the workspace. A later Mode mount must
|
|
41
41
|
// not run startup orphan cleanup against other scopes' live containers.
|
|
42
42
|
let sandboxCleanup;
|
|
43
|
+
const dependencies = {
|
|
44
|
+
commit: store,
|
|
45
|
+
reader: store,
|
|
46
|
+
receipt: (id, hash) => store.receipt(id, hash),
|
|
47
|
+
hash: (value) => createHash('sha256').update(canonicalJson(value)).digest('hex'),
|
|
48
|
+
now: () => new Date().toISOString(),
|
|
49
|
+
id: randomUUID,
|
|
50
|
+
epoch: store.epoch,
|
|
51
|
+
rootUri: pathToFileURL(root).href,
|
|
52
|
+
};
|
|
43
53
|
const shared = {
|
|
44
54
|
hostConfiguration,
|
|
55
|
+
dependencies,
|
|
56
|
+
journal: createRuntimeJournal({ ...dependencies, stateReader: store.stateReader }),
|
|
57
|
+
liveProgress: createLiveText(),
|
|
45
58
|
processManager,
|
|
46
59
|
secrets,
|
|
47
60
|
cleanupSandboxOrphans: (cleanup) => (sandboxCleanup ??= cleanup()),
|
|
@@ -52,13 +65,13 @@ export async function composeRuntime(store, root, options = {}, diagnosticDestin
|
|
|
52
65
|
availableModes,
|
|
53
66
|
processManager,
|
|
54
67
|
logger,
|
|
55
|
-
mount: (mode, plugins) => composeModeRuntime(store, root, { ...options, mode }, diagnosticDestination, shared, plugins),
|
|
68
|
+
mount: (mode, workers, plugins) => composeModeRuntime(store, root, { ...options, mode }, diagnosticDestination, shared, workers, plugins),
|
|
56
69
|
});
|
|
57
70
|
}
|
|
58
|
-
async function composeModeRuntime(store, root, options, diagnosticDestination, shared, plugins) {
|
|
71
|
+
async function composeModeRuntime(store, root, options, diagnosticDestination, shared, workers, plugins) {
|
|
59
72
|
const resources = {};
|
|
60
73
|
try {
|
|
61
|
-
return await assembleRuntime(resources, store, root, options, diagnosticDestination, shared, plugins);
|
|
74
|
+
return await assembleRuntime(resources, store, root, options, diagnosticDestination, shared, workers, plugins);
|
|
62
75
|
}
|
|
63
76
|
catch (error) {
|
|
64
77
|
try {
|
|
@@ -69,7 +82,7 @@ async function composeModeRuntime(store, root, options, diagnosticDestination, s
|
|
|
69
82
|
}
|
|
70
83
|
}
|
|
71
84
|
}
|
|
72
|
-
async function assembleRuntime(resources, store, root, options, diagnosticDestination, shared, plugins) {
|
|
85
|
+
async function assembleRuntime(resources, store, root, options, diagnosticDestination, shared, workers, plugins) {
|
|
73
86
|
const readConfiguration = () => loadHostConfiguration(root, options.configFile);
|
|
74
87
|
const hostConfiguration = shared.hostConfiguration;
|
|
75
88
|
const { catalog, configSource, trustedMcp, mcpServers, mcpServerMeta, mcpJsonError } = hostConfiguration;
|
|
@@ -105,9 +118,10 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
|
|
|
105
118
|
const externalPlugins = plugins ?? (await loadModePlugins(activeMode, hostConfiguration, logger));
|
|
106
119
|
const pluginStatuses = new Map();
|
|
107
120
|
const skillService = await createSkillRegistryService(root, activeMode, catalog);
|
|
108
|
-
const
|
|
121
|
+
const { dependencies, journal, liveProgress } = shared;
|
|
122
|
+
const { hash, now } = dependencies;
|
|
109
123
|
const clock = {
|
|
110
|
-
now
|
|
124
|
+
now,
|
|
111
125
|
async delay(ms, signal) {
|
|
112
126
|
signal.throwIfAborted();
|
|
113
127
|
let timer;
|
|
@@ -242,6 +256,7 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
|
|
|
242
256
|
resultReader: createToolResultReader(store.toolReader),
|
|
243
257
|
suppressedGuidanceRoles,
|
|
244
258
|
sharedProcessManager: shared.processManager,
|
|
259
|
+
resolveWorkerModeRef: (selector) => resolveModeSelector(selector, availableModes)?.ref,
|
|
245
260
|
previousDataReview: (runId) => store.hasNumericReview(runId),
|
|
246
261
|
stopMember: (ctx, memberId, reason) => {
|
|
247
262
|
if (!stopMemberImpl)
|
|
@@ -276,19 +291,7 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
|
|
|
276
291
|
const { gateway, resolveFrozenModel } = saturnModel;
|
|
277
292
|
const { composer } = saturnContext;
|
|
278
293
|
const { registry } = tools;
|
|
279
|
-
const dependencies = {
|
|
280
|
-
commit: store,
|
|
281
|
-
reader: store,
|
|
282
|
-
receipt: (id, h) => store.receipt(id, h),
|
|
283
|
-
hash,
|
|
284
|
-
now: clock.now,
|
|
285
|
-
id: randomUUID,
|
|
286
|
-
epoch: store.epoch,
|
|
287
|
-
rootUri: pathToFileURL(root).href,
|
|
288
|
-
stateReader: store.stateReader,
|
|
289
|
-
};
|
|
290
294
|
const admission = createCommandHandler(dependencies);
|
|
291
|
-
const journal = createRuntimeJournal(dependencies);
|
|
292
295
|
async function checkWorkingDirectory(uri) {
|
|
293
296
|
let working;
|
|
294
297
|
try {
|
|
@@ -394,8 +397,16 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
|
|
|
394
397
|
...turns.map(({ agentSessionId }) => agentSessionId),
|
|
395
398
|
]);
|
|
396
399
|
others.delete(route.agentSessionId);
|
|
397
|
-
|
|
398
|
-
|
|
400
|
+
const team = await store.stateReader.team?.(runId);
|
|
401
|
+
for (const agentSessionId of others) {
|
|
402
|
+
const { config } = await environment.load(runId, agentSessionId);
|
|
403
|
+
const member = team?.members.find((member) => member.agentSessionId === agentSessionId);
|
|
404
|
+
if (config.modeRef !== activeMode.ref &&
|
|
405
|
+
member &&
|
|
406
|
+
['completed', 'failed', 'interrupted', 'stopped'].includes(member.status))
|
|
407
|
+
continue;
|
|
408
|
+
await (await workerRuntime(runId, agentSessionId, config.modeRef)).verify(config);
|
|
409
|
+
}
|
|
399
410
|
for (const turn of turns) {
|
|
400
411
|
for (const call of await store.toolReader.pending(turn.id)) {
|
|
401
412
|
if (call.definition &&
|
|
@@ -403,11 +414,10 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
|
|
|
403
414
|
call.approval?.status === 'approved' ||
|
|
404
415
|
call.status === 'running' ||
|
|
405
416
|
call.status === 'outcome_unknown'))
|
|
406
|
-
await
|
|
417
|
+
await (await workerRuntime(runId, call.agentSessionId)).verifyTool(call.definition);
|
|
407
418
|
}
|
|
408
419
|
}
|
|
409
420
|
}
|
|
410
|
-
const liveProgress = createLiveText();
|
|
411
421
|
const agent = createAgentLoop({
|
|
412
422
|
logger,
|
|
413
423
|
environment,
|
|
@@ -433,19 +443,57 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
|
|
|
433
443
|
id: randomUUID,
|
|
434
444
|
signal: stop.signal,
|
|
435
445
|
});
|
|
436
|
-
const
|
|
437
|
-
...dependencies,
|
|
438
|
-
journal,
|
|
439
|
-
state: store.stateReader,
|
|
440
|
-
environment,
|
|
446
|
+
const worker = {
|
|
441
447
|
agent,
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
448
|
+
executor,
|
|
449
|
+
verify: verifyConfigVersions,
|
|
450
|
+
verifyTool: (definition) => registry.resolveFrozen(definition),
|
|
451
|
+
async freeze(parent, team, agentSessionId, depth) {
|
|
452
|
+
let config = parent;
|
|
453
|
+
const capabilities = resolveFrozenModel(parent).capabilities;
|
|
454
|
+
if (parent.modeRef !== activeMode.ref) {
|
|
455
|
+
const { contextExtensions: _context, pluginBindings, toolSnapshot: _snapshot, workerSoftCheckpointMs: _checkpoint, ...base } = parent;
|
|
456
|
+
const defaults = resolveRunDefaults(parent.model, catalog?.runDefaults, { modeBudget, capabilities });
|
|
457
|
+
const { wallTimeMs: modeWallTime, ...modeLimits } = defaults.limits;
|
|
458
|
+
const limits = {
|
|
459
|
+
...modeLimits,
|
|
460
|
+
...(parent.limits.wallTimeMs !== undefined ? { wallTimeMs: parent.limits.wallTimeMs } : {}),
|
|
461
|
+
};
|
|
462
|
+
for (const key of ['maxModelAttempts', 'maxToolCalls', 'maxSteps', 'maxTotalTokens']) {
|
|
463
|
+
const parentLimit = parent.limits[key];
|
|
464
|
+
if (isLimited(parentLimit))
|
|
465
|
+
limits[key] = isLimited(limits[key]) ? Math.min(limits[key], parentLimit) : parentLimit;
|
|
466
|
+
}
|
|
467
|
+
if (isLimited(modeWallTime)) {
|
|
468
|
+
const limit = limits.subagentWallTimeMs;
|
|
469
|
+
limits.subagentWallTimeMs = isLimited(limit) ? Math.min(limit, modeWallTime) : modeWallTime;
|
|
470
|
+
}
|
|
471
|
+
config = {
|
|
472
|
+
...base,
|
|
473
|
+
modeRef: activeMode.ref,
|
|
474
|
+
toolSetVersion: tools.defaultVersion(capabilities),
|
|
475
|
+
teamMaxDepth: Math.min(parent.teamMaxDepth ?? 1, activeMode.team?.maxDepth ?? 1),
|
|
476
|
+
...(activeMode.team?.workerSoftCheckpointMs !== undefined
|
|
477
|
+
? { workerSoftCheckpointMs: activeMode.team.workerSoftCheckpointMs }
|
|
478
|
+
: {}),
|
|
479
|
+
...(toolLayers.permissionMode
|
|
480
|
+
? { policyVersion: interactiveToolPolicies[toolLayers.permissionMode] }
|
|
481
|
+
: {}),
|
|
482
|
+
limits,
|
|
483
|
+
...(await freezeContextExtensions(root, activeMode, catalog?.skills)),
|
|
484
|
+
};
|
|
485
|
+
const { bindings } = freezeContributions(config, { role: 'worker', agentSessionId });
|
|
486
|
+
config = {
|
|
487
|
+
...config,
|
|
488
|
+
pluginBindings: {
|
|
489
|
+
...bindings,
|
|
490
|
+
...(pluginBindings?.modelProvider ? { modelProvider: pluginBindings.modelProvider } : {}),
|
|
491
|
+
},
|
|
492
|
+
};
|
|
493
|
+
}
|
|
494
|
+
return tools.freezeWorker(config, team, agentSessionId, capabilities, { depth });
|
|
495
|
+
},
|
|
496
|
+
start: async (workerInput) => {
|
|
449
497
|
const workerEnv = await environment.load(workerInput.runId, workerInput.agentSessionId);
|
|
450
498
|
const sessionId = workerEnv.route.sessionId;
|
|
451
499
|
if (saturnSandbox)
|
|
@@ -459,7 +507,7 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
|
|
|
459
507
|
...(workerInput.workSubpath !== undefined ? { workSubpath: workerInput.workSubpath } : {}),
|
|
460
508
|
});
|
|
461
509
|
},
|
|
462
|
-
|
|
510
|
+
complete: async (workerInput) => {
|
|
463
511
|
const workerEnv = await environment
|
|
464
512
|
.load(workerInput.runId, workerInput.agentSessionId)
|
|
465
513
|
.catch(() => undefined);
|
|
@@ -505,6 +553,69 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
|
|
|
505
553
|
...(usage ? { usage } : {}),
|
|
506
554
|
});
|
|
507
555
|
},
|
|
556
|
+
};
|
|
557
|
+
async function workerRuntime(runId, agentSessionId, modeRef) {
|
|
558
|
+
const selector = modeRef ?? (await environment.load(runId, agentSessionId)).config.modeRef;
|
|
559
|
+
const ref = resolveModeSelector(selector, availableModes)?.ref;
|
|
560
|
+
if (!ref && selector.includes('@'))
|
|
561
|
+
throw new RuntimeError('PLUGIN_VERSION_UNAVAILABLE', `Worker Mode ${selector} is unavailable`);
|
|
562
|
+
return ref && ref !== activeMode.ref ? workers.acquire(ref, runId, agentSessionId) : worker;
|
|
563
|
+
}
|
|
564
|
+
function freezeWorker(runId, parent, team, agentSessionId, member) {
|
|
565
|
+
let selector = member.modeRef;
|
|
566
|
+
let depth = (parent.agentDepth ?? 0) + 1;
|
|
567
|
+
let ancestor = team.members.find(({ id }) => id === member.parent);
|
|
568
|
+
while (ancestor) {
|
|
569
|
+
selector ??= ancestor.modeRef;
|
|
570
|
+
depth++;
|
|
571
|
+
const ancestorParent = ancestor.parent;
|
|
572
|
+
ancestor = team.members.find(({ id }) => id === ancestorParent);
|
|
573
|
+
}
|
|
574
|
+
const ref = selector ? resolveModeSelector(selector, availableModes)?.ref : parent.modeRef;
|
|
575
|
+
if (!ref)
|
|
576
|
+
throw new RuntimeError('INVALID_TEAM_CONFIG', `Unknown worker Mode: ${selector}`);
|
|
577
|
+
return workerRuntime(runId, agentSessionId, ref).then((runtime) => runtime.freeze(parent, team, agentSessionId, depth));
|
|
578
|
+
}
|
|
579
|
+
const loop = createRunLoop({
|
|
580
|
+
...dependencies,
|
|
581
|
+
journal,
|
|
582
|
+
state: store.stateReader,
|
|
583
|
+
environment,
|
|
584
|
+
agent: {
|
|
585
|
+
...agent,
|
|
586
|
+
async resume(input, signal) {
|
|
587
|
+
return (await workerRuntime(input.runId, input.agentSessionId)).agent.resume(input, signal);
|
|
588
|
+
},
|
|
589
|
+
async steer(agentSessionId, commandId, command) {
|
|
590
|
+
return (await workerRuntime(command.runId, agentSessionId)).agent.steer(agentSessionId, commandId, command);
|
|
591
|
+
},
|
|
592
|
+
},
|
|
593
|
+
tools: store.toolReader,
|
|
594
|
+
surface: store.surfaceReader,
|
|
595
|
+
freezeWorkerConfig: freezeWorker,
|
|
596
|
+
verifyPluginVersions: verifyRunVersions,
|
|
597
|
+
completionPolicy: createContinuationCompletionPolicy({ semanticJudge }),
|
|
598
|
+
createCheckpoint: (input, prior) => createRunCheckpoint(store.surfaceReader, input, prior),
|
|
599
|
+
async onWorkerStart(input) {
|
|
600
|
+
const { parentAgentSessionId, ...details } = input;
|
|
601
|
+
const runtime = await workerRuntime(input.runId, input.agentSessionId);
|
|
602
|
+
const sameParentMode = parentAgentSessionId &&
|
|
603
|
+
(await environment.load(input.runId, parentAgentSessionId)).config.modeRef ===
|
|
604
|
+
(await environment.load(input.runId, input.agentSessionId)).config.modeRef;
|
|
605
|
+
await runtime.start({ ...details, ...(sameParentMode ? { parentAgentSessionId } : {}) });
|
|
606
|
+
},
|
|
607
|
+
async onWorkerComplete(input) {
|
|
608
|
+
try {
|
|
609
|
+
const { config } = await environment.load(input.runId, input.agentSessionId);
|
|
610
|
+
const runtime = matchesModeSelector(config.modeRef, activeMode.ref, availableModes)
|
|
611
|
+
? worker
|
|
612
|
+
: workers.find(input.runId, input.agentSessionId);
|
|
613
|
+
await runtime?.complete(input);
|
|
614
|
+
}
|
|
615
|
+
finally {
|
|
616
|
+
await workers.release(input.runId, input.agentSessionId);
|
|
617
|
+
}
|
|
618
|
+
},
|
|
508
619
|
});
|
|
509
620
|
steerMemberImpl = loop.steerMember;
|
|
510
621
|
stopMemberImpl = loop.stopMember;
|
|
@@ -514,7 +625,9 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
|
|
|
514
625
|
await journal.append(`team:${runId}:notify:${messageId}`, [
|
|
515
626
|
journal.event('run.team.message.sent', scope, { messageId, from, to, text }),
|
|
516
627
|
]);
|
|
517
|
-
void
|
|
628
|
+
void workers
|
|
629
|
+
.wake(runId)
|
|
630
|
+
.catch((error) => reportDiagnostic(logger, error, randomUUID(), 'TEAM_WAKE_FAILED', { runId }));
|
|
518
631
|
};
|
|
519
632
|
syncWorkspaceSubpathsImpl = async ({ runId, sessionId }, subpaths) => {
|
|
520
633
|
if (!saturnSandbox || !subpaths.length)
|
|
@@ -529,6 +642,7 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
|
|
|
529
642
|
let closing = false;
|
|
530
643
|
let closeTask;
|
|
531
644
|
async function cleanupRunProcesses(runId, terminalStatus) {
|
|
645
|
+
await workers.release(runId);
|
|
532
646
|
executor.clearFileSnapshots(runId);
|
|
533
647
|
const processes = await processManager?.stopRun(runId);
|
|
534
648
|
for (const process of processes ?? []) {
|
|
@@ -653,13 +767,22 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
|
|
|
653
767
|
state: store.stateReader,
|
|
654
768
|
environment,
|
|
655
769
|
tools: store.toolReader,
|
|
656
|
-
executor
|
|
770
|
+
executor: {
|
|
771
|
+
async executeBatch(input) {
|
|
772
|
+
return (await workerRuntime(input.runId, input.agentSessionId)).executor.executeBatch(input);
|
|
773
|
+
},
|
|
774
|
+
async recover(input) {
|
|
775
|
+
return (await workerRuntime(input.runId, input.agentSessionId)).executor.recover(input);
|
|
776
|
+
},
|
|
777
|
+
},
|
|
657
778
|
clock,
|
|
658
779
|
hash,
|
|
659
780
|
loop,
|
|
660
781
|
signal: stop.signal,
|
|
661
782
|
}, schedule, runIds);
|
|
662
783
|
}
|
|
784
|
+
let stopRunsTask;
|
|
785
|
+
const stopRuns = () => (stopRunsTask ??= loop.stop());
|
|
663
786
|
async function shutdown() {
|
|
664
787
|
closing = true;
|
|
665
788
|
const stopLifecycle = lifecycle.stop();
|
|
@@ -667,7 +790,7 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
|
|
|
667
790
|
clearTimeout(timer);
|
|
668
791
|
deadlines.clear();
|
|
669
792
|
try {
|
|
670
|
-
await
|
|
793
|
+
await stopRuns();
|
|
671
794
|
}
|
|
672
795
|
finally {
|
|
673
796
|
stop.abort();
|
|
@@ -761,6 +884,9 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
|
|
|
761
884
|
};
|
|
762
885
|
},
|
|
763
886
|
recoverRuns,
|
|
887
|
+
stopRuns,
|
|
888
|
+
wakeTeam: loop.wakeTeam,
|
|
889
|
+
worker,
|
|
764
890
|
activePlugins: () => lifecycle.activePlugins(),
|
|
765
891
|
handle(request, requestSignal) {
|
|
766
892
|
if (closing)
|
|
@@ -805,12 +931,13 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
|
|
|
805
931
|
const defaults = catalog?.runDefaults;
|
|
806
932
|
const defaultToolSet = tools.defaultVersion(resolvedModel.capabilities);
|
|
807
933
|
let team = input.config?.team;
|
|
808
|
-
|
|
934
|
+
const presetName = input.teamPreset ?? (team === undefined ? activeMode.team?.defaultPreset : undefined);
|
|
935
|
+
if (presetName !== undefined) {
|
|
809
936
|
if (input.config?.team !== undefined)
|
|
810
937
|
throw new RuntimeError('INVALID_CONFIG', 'teamPreset and config.team are mutually exclusive');
|
|
811
|
-
if (!catalog?.teamPresets || !Object.hasOwn(catalog.teamPresets,
|
|
812
|
-
throw new RuntimeError('INVALID_CONFIG',
|
|
813
|
-
const preset = catalog.teamPresets[
|
|
938
|
+
if (!catalog?.teamPresets || !Object.hasOwn(catalog.teamPresets, presetName))
|
|
939
|
+
throw new RuntimeError('INVALID_CONFIG', `Unknown team preset "${presetName}"${input.teamPreset === undefined ? ` configured as team.default_preset for Mode ${activeMode.ref}` : ''}`);
|
|
940
|
+
const preset = catalog.teamPresets[presetName];
|
|
814
941
|
const userPrompt = input.content
|
|
815
942
|
.flatMap((part) => (part.type === 'text' ? [part.text] : []))
|
|
816
943
|
.join('\n')
|
|
@@ -830,7 +957,9 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
|
|
|
830
957
|
if (team && teamHint)
|
|
831
958
|
throw new RuntimeError('INVALID_CONFIG', 'team and teamHint are mutually exclusive');
|
|
832
959
|
if (team) {
|
|
833
|
-
validateTeamConfig(team);
|
|
960
|
+
validateTeamConfig(team, activeMode.team?.maxDepth !== undefined ? { maxDepth: activeMode.team.maxDepth } : undefined);
|
|
961
|
+
if (team.members.some(({ modeRef }) => modeRef !== undefined))
|
|
962
|
+
throw new RuntimeError('INVALID_TEAM_CONFIG', 'Team member modeRef is supported by spawn_team');
|
|
834
963
|
if (activeMode.ref === 'ctf@1' || activeMode.ref.startsWith('ctf@')) {
|
|
835
964
|
for (const member of team.members) {
|
|
836
965
|
if (member.parent !== 'main')
|
|
@@ -874,6 +1003,7 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
|
|
|
874
1003
|
...(activeMode.team?.maxActiveDepth1 !== undefined
|
|
875
1004
|
? { teamMaxActiveDepth1: activeMode.team.maxActiveDepth1 }
|
|
876
1005
|
: {}),
|
|
1006
|
+
teamDefaultConcurrency: activeMode.team?.defaultConcurrency ?? defaultTeamConcurrency,
|
|
877
1007
|
...(activeMode.team?.maxConcurrency !== undefined
|
|
878
1008
|
? { teamMaxConcurrency: activeMode.team.maxConcurrency }
|
|
879
1009
|
: {}),
|
|
@@ -1038,7 +1168,8 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
|
|
|
1038
1168
|
case 'tool.reconcile': {
|
|
1039
1169
|
const call = await store.toolReader.read(command.toolCallId);
|
|
1040
1170
|
return withRun(call.runId, async () => {
|
|
1041
|
-
await
|
|
1171
|
+
const runtime = await workerRuntime(call.runId, call.agentSessionId);
|
|
1172
|
+
await runtime.executor.reconcile(command.toolCallId, command.decision, commandId);
|
|
1042
1173
|
await maybeResume(call.runId, `reconcile:${commandId}:resume`);
|
|
1043
1174
|
return {
|
|
1044
1175
|
toolCallId: command.toolCallId,
|
|
@@ -1184,7 +1315,14 @@ async function assembleRuntime(resources, store, root, options, diagnosticDestin
|
|
|
1184
1315
|
case 'run.timeline':
|
|
1185
1316
|
return runTimeline(store, command);
|
|
1186
1317
|
case 'surface.compact':
|
|
1187
|
-
return compactSurface({
|
|
1318
|
+
return compactSurface({
|
|
1319
|
+
...dependencies,
|
|
1320
|
+
environment,
|
|
1321
|
+
stateReader: store.stateReader,
|
|
1322
|
+
surfaceReader: store.surfaceReader,
|
|
1323
|
+
gateway,
|
|
1324
|
+
logger,
|
|
1325
|
+
}, commandId, command);
|
|
1188
1326
|
case 'context.query': {
|
|
1189
1327
|
const { route } = await environment.load(command.runId);
|
|
1190
1328
|
const snapshot = await store.contextReader.read(route.agentSessionId, command.runId);
|
|
@@ -337,6 +337,11 @@ export declare const modeDefinitionSchema: z.ZodObject<{
|
|
|
337
337
|
}, z.core.$strict>>;
|
|
338
338
|
team: z.ZodOptional<z.ZodObject<{
|
|
339
339
|
max_depth: z.ZodOptional<z.ZodNumber>;
|
|
340
|
+
default_concurrency: z.ZodOptional<z.ZodNumber>;
|
|
341
|
+
default_preset: z.ZodOptional<z.ZodString>;
|
|
342
|
+
max_concurrency: z.ZodOptional<z.ZodNumber>;
|
|
343
|
+
max_active_depth1: z.ZodOptional<z.ZodNumber>;
|
|
344
|
+
worker_soft_checkpoint_ms: z.ZodOptional<z.ZodNumber>;
|
|
340
345
|
async_coordinator: z.ZodOptional<z.ZodBoolean>;
|
|
341
346
|
coordinator_poll_interval_ms: z.ZodOptional<z.ZodNumber>;
|
|
342
347
|
}, z.core.$strict>>;
|
|
@@ -650,6 +655,11 @@ export declare const modeDefinitionsSchema: z.ZodRecord<z.ZodString, z.ZodObject
|
|
|
650
655
|
}, z.core.$strict>>;
|
|
651
656
|
team: z.ZodOptional<z.ZodObject<{
|
|
652
657
|
max_depth: z.ZodOptional<z.ZodNumber>;
|
|
658
|
+
default_concurrency: z.ZodOptional<z.ZodNumber>;
|
|
659
|
+
default_preset: z.ZodOptional<z.ZodString>;
|
|
660
|
+
max_concurrency: z.ZodOptional<z.ZodNumber>;
|
|
661
|
+
max_active_depth1: z.ZodOptional<z.ZodNumber>;
|
|
662
|
+
worker_soft_checkpoint_ms: z.ZodOptional<z.ZodNumber>;
|
|
653
663
|
async_coordinator: z.ZodOptional<z.ZodBoolean>;
|
|
654
664
|
coordinator_poll_interval_ms: z.ZodOptional<z.ZodNumber>;
|
|
655
665
|
}, z.core.$strict>>;
|
|
@@ -132,6 +132,11 @@ export const modeSandboxSchema = z.strictObject({
|
|
|
132
132
|
});
|
|
133
133
|
const modeTeamSchema = z.strictObject({
|
|
134
134
|
max_depth: z.number().int().min(1).max(2).optional(),
|
|
135
|
+
default_concurrency: z.number().int().positive().optional(),
|
|
136
|
+
default_preset: identifier.optional(),
|
|
137
|
+
max_concurrency: z.number().int().positive().optional(),
|
|
138
|
+
max_active_depth1: z.number().int().positive().optional(),
|
|
139
|
+
worker_soft_checkpoint_ms: z.number().int().nonnegative().optional(),
|
|
135
140
|
async_coordinator: z.boolean().optional(),
|
|
136
141
|
coordinator_poll_interval_ms: z.number().int().min(0).optional(),
|
|
137
142
|
});
|
|
@@ -4,7 +4,7 @@ import { type TeamMemberAction, type TeamNotifyParentDelivery } from '@saturn-un
|
|
|
4
4
|
import type { ToolConfiguration } from './tools-core-plugin.js';
|
|
5
5
|
import { type SkillRegistryService } from '../../skills-runtime.js';
|
|
6
6
|
export declare function teamHintSections(hint: RunConfig['teamHint'], tools: readonly ToolSpec[]): PromptSection[];
|
|
7
|
-
export declare function createBuiltinAgentToolsPlugin(root: string, settings: ToolConfiguration['counter'], resultReader?: ToolBinding, previousDataReview?: (runId: RunId) => Promise<boolean>, suppressedGuidanceRoles?: ReadonlySet<'main' | 'worker'>, skillService?: SkillRegistryService, notifyParent?: (delivery: TeamNotifyParentDelivery) => Promise<void>, steerMember?: TeamMemberAction, stopMember?: TeamMemberAction): {
|
|
7
|
+
export declare function createBuiltinAgentToolsPlugin(root: string, settings: ToolConfiguration['counter'], resultReader?: ToolBinding, previousDataReview?: (runId: RunId) => Promise<boolean>, suppressedGuidanceRoles?: ReadonlySet<'main' | 'worker'>, skillService?: SkillRegistryService, notifyParent?: (delivery: TeamNotifyParentDelivery) => Promise<void>, steerMember?: TeamMemberAction, stopMember?: TeamMemberAction, resolveWorkerModeRef?: (selector: string) => string | undefined): {
|
|
8
8
|
name: string;
|
|
9
9
|
inject: string[];
|
|
10
10
|
apply(ctx: Context, startupSignal: AbortSignal): Promise<void>;
|
|
@@ -19,7 +19,7 @@ export function teamHintSections(hint, tools) {
|
|
|
19
19
|
},
|
|
20
20
|
];
|
|
21
21
|
}
|
|
22
|
-
export function createBuiltinAgentToolsPlugin(root, settings, resultReader, previousDataReview, suppressedGuidanceRoles, skillService, notifyParent, steerMember, stopMember) {
|
|
22
|
+
export function createBuiltinAgentToolsPlugin(root, settings, resultReader, previousDataReview, suppressedGuidanceRoles, skillService, notifyParent, steerMember, stopMember, resolveWorkerModeRef) {
|
|
23
23
|
return {
|
|
24
24
|
name: 'builtin-agent-tools',
|
|
25
25
|
inject: ['saturnTools'],
|
|
@@ -90,6 +90,20 @@ export function createBuiltinAgentToolsPlugin(root, settings, resultReader, prev
|
|
|
90
90
|
versions: sets.spawnTeamV2Versions,
|
|
91
91
|
priority: 0,
|
|
92
92
|
},
|
|
93
|
+
...(resolveWorkerModeRef
|
|
94
|
+
? [
|
|
95
|
+
{
|
|
96
|
+
binding: createSpawnTeamTool({
|
|
97
|
+
includeSandboxProfile: true,
|
|
98
|
+
includeWorkSubpath: true,
|
|
99
|
+
resolveModeRef: resolveWorkerModeRef,
|
|
100
|
+
...(resolveCaller ? { resolveCaller } : {}),
|
|
101
|
+
}),
|
|
102
|
+
versions: [],
|
|
103
|
+
priority: 0,
|
|
104
|
+
},
|
|
105
|
+
]
|
|
106
|
+
: []),
|
|
93
107
|
{
|
|
94
108
|
binding: createTodoWriteTool(),
|
|
95
109
|
versions: [...sets.defaultVersions, dataReviewToolSet],
|
|
@@ -16,5 +16,6 @@ export interface HostToolOptions {
|
|
|
16
16
|
steerMember?: TeamMemberAction;
|
|
17
17
|
stopMember?: TeamMemberAction;
|
|
18
18
|
notifyParent?: (delivery: TeamNotifyParentDelivery) => Promise<void>;
|
|
19
|
+
resolveWorkerModeRef?: (selector: string) => string | undefined;
|
|
19
20
|
}
|
|
20
21
|
export declare function createToolPlugins(root: string, options: HostToolOptions, startupDependencies?: string[], withContext?: boolean): RequiredHostPlugin[];
|
|
@@ -4,7 +4,7 @@ import { createProcessManagerPlugin } from './process-manager-plugin.js';
|
|
|
4
4
|
import { createToolsCorePlugin } from './tools-core-plugin.js';
|
|
5
5
|
import { createWorkspaceToolsPlugin } from './workspace-tools-plugin.js';
|
|
6
6
|
export function createToolPlugins(root, options, startupDependencies = [], withContext = false) {
|
|
7
|
-
const { config, trustedConfig, hash, resultReader, processManager, sharedProcessManager, previousDataReview, suppressedGuidanceRoles, skillService, notifyParent, steerMember, stopMember, } = options;
|
|
7
|
+
const { config, trustedConfig, hash, resultReader, processManager, sharedProcessManager, previousDataReview, suppressedGuidanceRoles, skillService, notifyParent, steerMember, stopMember, resolveWorkerModeRef, } = options;
|
|
8
8
|
const effectiveWorkspaceTools = Boolean(config.workspaceTools);
|
|
9
9
|
const effectiveProcessManager = config.processManager ?? effectiveWorkspaceTools;
|
|
10
10
|
const effectiveBuiltinAgentTools = config.builtinAgentTools !== false;
|
|
@@ -30,7 +30,7 @@ export function createToolPlugins(root, options, startupDependencies = [], withC
|
|
|
30
30
|
: []),
|
|
31
31
|
...(effectiveBuiltinAgentTools
|
|
32
32
|
? [
|
|
33
|
-
guidanceOwner(createBuiltinAgentToolsPlugin(root, config.counter, resultReader, previousDataReview, suppressedGuidanceRoles, skillService, notifyParent, steerMember, stopMember)),
|
|
33
|
+
guidanceOwner(createBuiltinAgentToolsPlugin(root, config.counter, resultReader, previousDataReview, suppressedGuidanceRoles, skillService, notifyParent, steerMember, stopMember, resolveWorkerModeRef)),
|
|
34
34
|
]
|
|
35
35
|
: []),
|
|
36
36
|
...(Object.keys(config.mcpServers ?? {}).length
|
|
@@ -343,6 +343,19 @@ function createToolsService(config, trustedConfig, hash) {
|
|
|
343
343
|
const overrides = new Map(scoped
|
|
344
344
|
.resolve(target, ({ scopeKey, toolSets }) => scopeKey !== undefined && toolSets.includes(runConfig.toolSetVersion))
|
|
345
345
|
.map((entry) => [entry.name, entry]));
|
|
346
|
+
if (runConfig.teamDefaultConcurrency !== undefined &&
|
|
347
|
+
(runConfig.toolSetVersion === '4' ||
|
|
348
|
+
mcp ||
|
|
349
|
+
[
|
|
350
|
+
previousWorkspaceToolSetVersion,
|
|
351
|
+
patchWorkspaceToolSetVersion,
|
|
352
|
+
phaseOneToolSetVersion,
|
|
353
|
+
workspaceToolSetVersion,
|
|
354
|
+
].includes(runConfig.toolSetVersion)) &&
|
|
355
|
+
registry.isActive(spawnTeamToolName, '3') &&
|
|
356
|
+
!overrides.has(spawnTeamToolName)) {
|
|
357
|
+
overrides.set(spawnTeamToolName, { name: spawnTeamToolName, version: '3', toolSets: [] });
|
|
358
|
+
}
|
|
346
359
|
const snapshot = registry.snapshotForAdmission(runConfig, overrides, ({ name, version, scopeKey }) => knownPluginTools.has(contributionIdentity({
|
|
347
360
|
kind: 'tool',
|
|
348
361
|
id: name,
|
|
@@ -122,6 +122,11 @@ export declare function loadModeConfiguration(env: NodeJS.ProcessEnv, configured
|
|
|
122
122
|
} | undefined;
|
|
123
123
|
team?: {
|
|
124
124
|
max_depth?: number | undefined;
|
|
125
|
+
default_concurrency?: number | undefined;
|
|
126
|
+
default_preset?: string | undefined;
|
|
127
|
+
max_concurrency?: number | undefined;
|
|
128
|
+
max_active_depth1?: number | undefined;
|
|
129
|
+
worker_soft_checkpoint_ms?: number | undefined;
|
|
125
130
|
async_coordinator?: boolean | undefined;
|
|
126
131
|
coordinator_poll_interval_ms?: number | undefined;
|
|
127
132
|
} | undefined;
|
package/dist/modes.js
CHANGED
|
@@ -351,7 +351,6 @@ function configureMode(ref, raw, builtin) {
|
|
|
351
351
|
'max_active_challenges',
|
|
352
352
|
'max_helpers_per_challenge',
|
|
353
353
|
'per_challenge_wall_time_ms',
|
|
354
|
-
'worker_soft_checkpoint_ms',
|
|
355
354
|
'board_port',
|
|
356
355
|
'board_token',
|
|
357
356
|
'board_public_host',
|
|
@@ -363,6 +362,8 @@ function configureMode(ref, raw, builtin) {
|
|
|
363
362
|
]
|
|
364
363
|
.filter((key) => raw[key] !== undefined)
|
|
365
364
|
.map((key) => [key, raw[key]]));
|
|
365
|
+
if (ref === 'ctf@1' && raw.worker_soft_checkpoint_ms !== undefined)
|
|
366
|
+
ctfOptions.worker_soft_checkpoint_ms = raw.worker_soft_checkpoint_ms;
|
|
366
367
|
if (Object.keys(ctfOptions).length) {
|
|
367
368
|
if (ref !== 'ctf@1')
|
|
368
369
|
throw new RuntimeError('INVALID_CONFIG', 'CTF settings require ctf@1');
|
|
@@ -374,31 +375,46 @@ function configureMode(ref, raw, builtin) {
|
|
|
374
375
|
const coordinatorPollIntervalMs = raw.coordinator_poll_interval_ms ??
|
|
375
376
|
raw.team?.coordinator_poll_interval_ms ??
|
|
376
377
|
base?.team?.coordinatorPollIntervalMs;
|
|
377
|
-
const workerSoftCheckpointMs = raw.worker_soft_checkpoint_ms ??
|
|
378
|
+
const workerSoftCheckpointMs = raw.team?.worker_soft_checkpoint_ms ??
|
|
379
|
+
raw.worker_soft_checkpoint_ms ??
|
|
380
|
+
base?.team?.workerSoftCheckpointMs;
|
|
378
381
|
const ctfPlugin = ref === 'ctf@1' ? plugins?.find((plugin) => plugin.builtin === 'ctf' || plugin.id === 'ctf') : undefined;
|
|
379
382
|
const rawMaxActive = ctfPlugin?.config?.max_active_challenges;
|
|
380
|
-
const maxActiveDepth1 =
|
|
381
|
-
|
|
382
|
-
|
|
383
|
+
const maxActiveDepth1 = raw.team?.max_active_depth1 ??
|
|
384
|
+
(typeof rawMaxActive === 'number' && Number.isSafeInteger(rawMaxActive) && rawMaxActive >= 1
|
|
385
|
+
? rawMaxActive
|
|
386
|
+
: base?.team?.maxActiveDepth1);
|
|
383
387
|
const isContainerSandbox = Boolean(sandbox && sandbox.backend !== 'host' && sandbox.scope !== 'none');
|
|
384
|
-
const
|
|
388
|
+
const sandboxConcurrency = isContainerSandbox
|
|
385
389
|
? sandbox?.maxConcurrentContainers !== undefined
|
|
386
390
|
? Math.max(1, sandbox.maxConcurrentContainers - 1)
|
|
387
391
|
: base?.team?.maxConcurrency
|
|
388
392
|
: undefined;
|
|
389
|
-
const
|
|
393
|
+
const maxConcurrency = raw.team?.max_concurrency ?? (isContainerSandbox ? base?.team?.maxConcurrency : undefined);
|
|
394
|
+
const defaultConcurrency = raw.team?.default_concurrency ?? base?.team?.defaultConcurrency;
|
|
395
|
+
if (defaultConcurrency !== undefined && maxConcurrency !== undefined && defaultConcurrency > maxConcurrency)
|
|
396
|
+
throw new RuntimeError('INVALID_CONFIG', `Mode ${ref}: team.default_concurrency exceeds team.max_concurrency`);
|
|
397
|
+
const effectiveMaxConcurrency = sandboxConcurrency === undefined
|
|
398
|
+
? maxConcurrency
|
|
399
|
+
: Math.min(sandboxConcurrency, raw.team?.max_concurrency ?? sandboxConcurrency);
|
|
400
|
+
const defaultPreset = raw.team?.default_preset ?? base?.team?.defaultPreset;
|
|
401
|
+
const team = defaultPreset !== undefined ||
|
|
402
|
+
maxDepth !== undefined ||
|
|
390
403
|
asyncCoordinator !== undefined ||
|
|
391
404
|
coordinatorPollIntervalMs !== undefined ||
|
|
392
405
|
workerSoftCheckpointMs !== undefined ||
|
|
393
406
|
maxActiveDepth1 !== undefined ||
|
|
394
|
-
|
|
407
|
+
defaultConcurrency !== undefined ||
|
|
408
|
+
effectiveMaxConcurrency !== undefined
|
|
395
409
|
? {
|
|
396
410
|
...(maxDepth !== undefined ? { maxDepth } : {}),
|
|
411
|
+
...(defaultPreset !== undefined ? { defaultPreset } : {}),
|
|
397
412
|
...(asyncCoordinator !== undefined ? { asyncCoordinator } : {}),
|
|
398
413
|
...(coordinatorPollIntervalMs !== undefined ? { coordinatorPollIntervalMs } : {}),
|
|
399
414
|
...(workerSoftCheckpointMs !== undefined ? { workerSoftCheckpointMs } : {}),
|
|
400
415
|
...(maxActiveDepth1 !== undefined ? { maxActiveDepth1 } : {}),
|
|
401
|
-
...(
|
|
416
|
+
...(defaultConcurrency !== undefined ? { defaultConcurrency } : {}),
|
|
417
|
+
...(effectiveMaxConcurrency !== undefined ? { maxConcurrency: effectiveMaxConcurrency } : {}),
|
|
402
418
|
}
|
|
403
419
|
: undefined;
|
|
404
420
|
const budget = { ...builtin?.budget, overrides: readConfiguredRunBudget(raw.limits) };
|
|
@@ -847,6 +847,11 @@ declare const catalogSchema: z.ZodObject<{
|
|
|
847
847
|
}, z.core.$strict>>;
|
|
848
848
|
team: z.ZodOptional<z.ZodObject<{
|
|
849
849
|
max_depth: z.ZodOptional<z.ZodNumber>;
|
|
850
|
+
default_concurrency: z.ZodOptional<z.ZodNumber>;
|
|
851
|
+
default_preset: z.ZodOptional<z.ZodString>;
|
|
852
|
+
max_concurrency: z.ZodOptional<z.ZodNumber>;
|
|
853
|
+
max_active_depth1: z.ZodOptional<z.ZodNumber>;
|
|
854
|
+
worker_soft_checkpoint_ms: z.ZodOptional<z.ZodNumber>;
|
|
850
855
|
async_coordinator: z.ZodOptional<z.ZodBoolean>;
|
|
851
856
|
coordinator_poll_interval_ms: z.ZodOptional<z.ZodNumber>;
|
|
852
857
|
}, z.core.$strict>>;
|
|
@@ -1,10 +1,27 @@
|
|
|
1
|
-
import type { HostProtocolRequest, JsonValue, LoggerPort, ModeDefinition, RunId, SessionId } from '@saturn-universe/core';
|
|
1
|
+
import type { AgentSessionId, RunConfig, TeamConfig, ToolDefinition, HostProtocolRequest, JsonValue, LoggerPort, ModeDefinition, RunId, SessionId } from '@saturn-universe/core';
|
|
2
2
|
import type { HostStatusFields } from '@saturn-universe/protocol';
|
|
3
3
|
import type { SqliteStore } from '@saturn-universe/storage';
|
|
4
|
-
import type { ProcessManager } from '@saturn-universe/tools';
|
|
4
|
+
import type { ProcessManager, createToolExecutor } from '@saturn-universe/tools';
|
|
5
|
+
import type { createAgentLoop, createRunLoop } from '@saturn-universe/runtime';
|
|
5
6
|
import type { PluginLifecycle } from './cordis/plugin-lifecycle.js';
|
|
6
7
|
import type { LoadedHostPlugin } from './cordis/plugin-loader.js';
|
|
7
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
|
+
}
|
|
8
25
|
interface ModeRuntime {
|
|
9
26
|
readonly status: Omit<HostStatusFields, 'epoch' | 'cursor'> & {
|
|
10
27
|
readonly configuredProfiles: number;
|
|
@@ -24,6 +41,9 @@ interface ModeRuntime {
|
|
|
24
41
|
pluginGenerations(): PluginStatus;
|
|
25
42
|
drainPlugins(): Promise<PluginStatus>;
|
|
26
43
|
close(): Promise<void>;
|
|
44
|
+
stopRuns(): Promise<void>;
|
|
45
|
+
wakeTeam(runId: RunId): Promise<void> | undefined;
|
|
46
|
+
readonly worker: WorkerModeRuntime;
|
|
27
47
|
}
|
|
28
48
|
export declare function createSessionModeRuntime({ store, activeMode, availableModes, processManager, logger, mount, }: {
|
|
29
49
|
store: SqliteStore;
|
|
@@ -31,7 +51,7 @@ export declare function createSessionModeRuntime({ store, activeMode, availableM
|
|
|
31
51
|
availableModes: readonly ModeDefinition[];
|
|
32
52
|
processManager: ProcessManager;
|
|
33
53
|
logger: LoggerPort;
|
|
34
|
-
mount: (modeRef: string, plugins?: readonly LoadedHostPlugin[]) => Promise<ModeRuntime>;
|
|
54
|
+
mount: (modeRef: string, workers: WorkerModeMounts, plugins?: readonly LoadedHostPlugin[]) => Promise<ModeRuntime>;
|
|
35
55
|
}): Promise<{
|
|
36
56
|
readonly status: ModeRuntime["status"];
|
|
37
57
|
recover: () => Promise<void>;
|
|
@@ -3,7 +3,9 @@ import { canonicalJson, isTerminalRunStatus, reportDiagnostic, resolveModeSelect
|
|
|
3
3
|
export async function createSessionModeRuntime({ store, activeMode, availableModes, processManager, logger, mount, }) {
|
|
4
4
|
const defaultRef = activeMode.ref;
|
|
5
5
|
const mounts = new Map();
|
|
6
|
+
const workerMounts = new Map();
|
|
6
7
|
let queue = Promise.resolve();
|
|
8
|
+
let mountQueue = Promise.resolve();
|
|
7
9
|
let closing = false;
|
|
8
10
|
let closeTask;
|
|
9
11
|
function resolve(selector) {
|
|
@@ -12,11 +14,56 @@ export async function createSessionModeRuntime({ store, activeMode, availableMod
|
|
|
12
14
|
throw new RuntimeError('INVALID_CONFIG', `Unknown mode: ${selector}`);
|
|
13
15
|
return mode;
|
|
14
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
|
+
};
|
|
15
58
|
async function open(modeRef, plugins) {
|
|
16
59
|
const existing = mounts.get(modeRef);
|
|
17
60
|
if (existing)
|
|
18
61
|
return existing;
|
|
19
|
-
const opened = {
|
|
62
|
+
const opened = {
|
|
63
|
+
runtime: await mount(modeRef, workers, plugins),
|
|
64
|
+
sessions: new Set(),
|
|
65
|
+
workers: 0,
|
|
66
|
+
};
|
|
20
67
|
mounts.set(modeRef, opened);
|
|
21
68
|
return opened;
|
|
22
69
|
}
|
|
@@ -50,7 +97,10 @@ export async function createSessionModeRuntime({ store, activeMode, availableMod
|
|
|
50
97
|
}
|
|
51
98
|
async function useMount(ref, sessionId) {
|
|
52
99
|
const unusedDefault = mounts.get(defaultRef);
|
|
53
|
-
if (ref !== defaultRef &&
|
|
100
|
+
if (ref !== defaultRef &&
|
|
101
|
+
!mounts.has(ref) &&
|
|
102
|
+
unusedDefault?.sessions.size === 0 &&
|
|
103
|
+
unusedDefault.workers === 0) {
|
|
54
104
|
// Cold recovery may start with a default scope that has no session users yet.
|
|
55
105
|
const plugins = unusedDefault.runtime.activePlugins();
|
|
56
106
|
try {
|
|
@@ -68,7 +118,7 @@ export async function createSessionModeRuntime({ store, activeMode, availableMod
|
|
|
68
118
|
}
|
|
69
119
|
async function sessionRuntime(sessionId) {
|
|
70
120
|
const { session } = await store.sessionModeState(sessionId);
|
|
71
|
-
return useMount(session.modeRef ?? defaultRef, sessionId);
|
|
121
|
+
return serializeMount(() => useMount(session.modeRef ?? defaultRef, sessionId));
|
|
72
122
|
}
|
|
73
123
|
async function runRuntime(runId, resume = false) {
|
|
74
124
|
const { route, config } = await store.environmentReader.load(runId);
|
|
@@ -81,7 +131,7 @@ export async function createSessionModeRuntime({ store, activeMode, availableMod
|
|
|
81
131
|
// Pre-Mode logs used a legacy non-versioned name. A removed versioned Mode cannot
|
|
82
132
|
// safely execute its Run's frozen tools or sandbox settings on a different mount.
|
|
83
133
|
const ref = canonical || (config.modeRef?.includes('@') ? config.modeRef : defaultRef);
|
|
84
|
-
return useMount(ref, route.sessionId);
|
|
134
|
+
return serializeMount(() => useMount(ref, route.sessionId));
|
|
85
135
|
}
|
|
86
136
|
async function select(commandId, command) {
|
|
87
137
|
const { sessionId } = command;
|
|
@@ -105,6 +155,7 @@ export async function createSessionModeRuntime({ store, activeMode, availableMod
|
|
|
105
155
|
const targetWasMounted = mounts.has(ref);
|
|
106
156
|
const shouldRetire = priorMount &&
|
|
107
157
|
previousRef !== ref &&
|
|
158
|
+
priorMount.workers === 0 &&
|
|
108
159
|
priorMount.sessions.size === Number(priorMount.sessions.has(sessionId));
|
|
109
160
|
const priorPlugins = shouldRetire ? priorMount.runtime.activePlugins() : undefined;
|
|
110
161
|
let target;
|
|
@@ -159,7 +210,7 @@ export async function createSessionModeRuntime({ store, activeMode, availableMod
|
|
|
159
210
|
const { command, commandId } = request;
|
|
160
211
|
switch (command.type) {
|
|
161
212
|
case 'session.mode.select':
|
|
162
|
-
return serialize(() => select(commandId, command));
|
|
213
|
+
return serialize(() => serializeMount(() => select(commandId, command)));
|
|
163
214
|
case 'run.submit':
|
|
164
215
|
return serialize(async () => {
|
|
165
216
|
const runtime = await sessionRuntime(command.input.sessionId);
|
|
@@ -228,18 +279,21 @@ export async function createSessionModeRuntime({ store, activeMode, availableMod
|
|
|
228
279
|
}
|
|
229
280
|
}),
|
|
230
281
|
handle,
|
|
231
|
-
reloadPlugins: () => serialize(async () => (await open(defaultRef)).runtime.reloadPlugins()),
|
|
232
|
-
reloadPlugin: (id) => serialize(async () => (await open(defaultRef)).runtime.reloadPlugin(id)),
|
|
233
|
-
deactivatePlugin: (id) => serialize(async () => (await open(defaultRef)).runtime.deactivatePlugin(id)),
|
|
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)),
|
|
234
285
|
pluginGenerations: () => mounts.get(defaultRef)?.runtime.pluginGenerations() ?? [],
|
|
235
|
-
drainPlugins: () => serialize(async () => (await open(defaultRef)).runtime.drainPlugins()),
|
|
286
|
+
drainPlugins: () => serialize(async () => (await serializeMount(() => open(defaultRef))).runtime.drainPlugins()),
|
|
236
287
|
close() {
|
|
237
288
|
closing = true;
|
|
238
289
|
return (closeTask ??= (async () => {
|
|
239
290
|
await queue;
|
|
240
291
|
try {
|
|
292
|
+
await mountQueue;
|
|
293
|
+
const stopped = await Promise.allSettled([...mounts.values()].map(({ runtime }) => runtime.stopRuns()));
|
|
294
|
+
await mountQueue;
|
|
241
295
|
const results = await Promise.allSettled([...mounts.values()].map(({ runtime }) => runtime.close()));
|
|
242
|
-
const failed = results.find((result) => result.status === 'rejected');
|
|
296
|
+
const failed = [...stopped, ...results].find((result) => result.status === 'rejected');
|
|
243
297
|
if (failed)
|
|
244
298
|
throw failed.reason;
|
|
245
299
|
}
|
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",
|