@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,114 @@
|
|
|
1
|
+
import { realpath } from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { buildEnvironmentContext } from '@saturn-universe/context';
|
|
4
|
+
import { validateWorkSubpath } from '@saturn-universe/core';
|
|
5
|
+
import { relativePathWithin } from '@saturn-universe/tools';
|
|
6
|
+
import { collectWorkspaceSnapshot, probeHostEnvironment } from '../env-probe.js';
|
|
7
|
+
const maxSessionSnapshots = 128;
|
|
8
|
+
export function createEnvProbePlugin(root, { probeHostEnvironment: probe = probeHostEnvironment, collectWorkspaceSnapshot: collect = collectWorkspaceSnapshot, } = {}) {
|
|
9
|
+
return {
|
|
10
|
+
name: 'env-probe',
|
|
11
|
+
async apply(ctx, startupSignal) {
|
|
12
|
+
const { workspaceEntries: _entries, gitBranch: _branch, ...staticEnvInfo } = await probe(root);
|
|
13
|
+
startupSignal.throwIfAborted();
|
|
14
|
+
const sessionSnapshots = new Map();
|
|
15
|
+
const pendingSnapshots = new Map();
|
|
16
|
+
let disposed = false;
|
|
17
|
+
ctx.effect(() => () => {
|
|
18
|
+
disposed = true;
|
|
19
|
+
sessionSnapshots.clear();
|
|
20
|
+
pendingSnapshots.clear();
|
|
21
|
+
});
|
|
22
|
+
const renderSessionEnvironment = (cached, options) => {
|
|
23
|
+
const includeReadonlyCommands = options?.includeReadonlyCommands ?? true;
|
|
24
|
+
const workSubpath = options?.workSubpath;
|
|
25
|
+
if (includeReadonlyCommands && !options?.sandbox && !workSubpath && !options?.mcpServers?.length) {
|
|
26
|
+
return cached.defaultText;
|
|
27
|
+
}
|
|
28
|
+
const { availableReadonlyCommands, missingReadonlyCommands, ...baseStaticInfo } = staticEnvInfo;
|
|
29
|
+
return buildEnvironmentContext({
|
|
30
|
+
...baseStaticInfo,
|
|
31
|
+
...(includeReadonlyCommands
|
|
32
|
+
? {
|
|
33
|
+
...(availableReadonlyCommands !== undefined ? { availableReadonlyCommands } : {}),
|
|
34
|
+
...(missingReadonlyCommands !== undefined ? { missingReadonlyCommands } : {}),
|
|
35
|
+
}
|
|
36
|
+
: {}),
|
|
37
|
+
...cached.snapshot,
|
|
38
|
+
...(workSubpath ? { workSubpath } : {}),
|
|
39
|
+
...(options?.sandbox ? { sandbox: options.sandbox } : {}),
|
|
40
|
+
...(options?.mcpServers?.length ? { mcpServers: options.mcpServers } : {}),
|
|
41
|
+
});
|
|
42
|
+
};
|
|
43
|
+
const resolveSnapshotRoot = async (workSubpath) => {
|
|
44
|
+
if (!workSubpath)
|
|
45
|
+
return root;
|
|
46
|
+
try {
|
|
47
|
+
const normalized = validateWorkSubpath(workSubpath);
|
|
48
|
+
const realRoot = await realpath(root);
|
|
49
|
+
const candidate = path.resolve(realRoot, ...normalized.split('/'));
|
|
50
|
+
const realCandidate = await realpath(candidate);
|
|
51
|
+
if (relativePathWithin(realRoot, realCandidate)) {
|
|
52
|
+
return realCandidate;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
// Fall back to workspace root if subpath is not created or outside root.
|
|
57
|
+
}
|
|
58
|
+
return root;
|
|
59
|
+
};
|
|
60
|
+
const service = {
|
|
61
|
+
staticEnvInfo: Object.freeze(staticEnvInfo),
|
|
62
|
+
async getSessionEnvironmentContext(sessionId, options) {
|
|
63
|
+
if (disposed)
|
|
64
|
+
throw new Error('Host env-probe is disposed');
|
|
65
|
+
let normalizedSubpath;
|
|
66
|
+
if (options?.workSubpath) {
|
|
67
|
+
try {
|
|
68
|
+
normalizedSubpath = validateWorkSubpath(options.workSubpath);
|
|
69
|
+
}
|
|
70
|
+
catch {
|
|
71
|
+
normalizedSubpath =
|
|
72
|
+
options.workSubpath.trim().replaceAll('\\', '/').replace(/\/+$/, '') || undefined;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
const cacheKey = normalizedSubpath ? `${sessionId}::${normalizedSubpath}` : sessionId;
|
|
76
|
+
const renderOptions = normalizedSubpath ? { ...options, workSubpath: normalizedSubpath } : options;
|
|
77
|
+
const cached = sessionSnapshots.get(cacheKey);
|
|
78
|
+
if (cached !== undefined)
|
|
79
|
+
return renderSessionEnvironment(cached, renderOptions);
|
|
80
|
+
const pending = pendingSnapshots.get(cacheKey);
|
|
81
|
+
if (pending)
|
|
82
|
+
return renderSessionEnvironment(await pending, renderOptions);
|
|
83
|
+
const snapshotPromise = normalizedSubpath
|
|
84
|
+
? resolveSnapshotRoot(normalizedSubpath).then((snapshotRoot) => collect(snapshotRoot))
|
|
85
|
+
: collect(root);
|
|
86
|
+
const entryPromise = snapshotPromise
|
|
87
|
+
.then((snapshot) => {
|
|
88
|
+
if (disposed)
|
|
89
|
+
throw new Error('Host env-probe is disposed');
|
|
90
|
+
const entry = {
|
|
91
|
+
snapshot,
|
|
92
|
+
defaultText: buildEnvironmentContext({
|
|
93
|
+
...staticEnvInfo,
|
|
94
|
+
...snapshot,
|
|
95
|
+
...(normalizedSubpath ? { workSubpath: normalizedSubpath } : {}),
|
|
96
|
+
}),
|
|
97
|
+
};
|
|
98
|
+
if (sessionSnapshots.size >= maxSessionSnapshots) {
|
|
99
|
+
const oldest = sessionSnapshots.keys().next().value;
|
|
100
|
+
if (oldest !== undefined)
|
|
101
|
+
sessionSnapshots.delete(oldest);
|
|
102
|
+
}
|
|
103
|
+
sessionSnapshots.set(cacheKey, entry);
|
|
104
|
+
return entry;
|
|
105
|
+
})
|
|
106
|
+
.finally(() => pendingSnapshots.delete(cacheKey));
|
|
107
|
+
pendingSnapshots.set(cacheKey, entryPromise);
|
|
108
|
+
return renderSessionEnvironment(await entryPromise, renderOptions);
|
|
109
|
+
},
|
|
110
|
+
};
|
|
111
|
+
ctx.provide('saturnEnvProbe', service);
|
|
112
|
+
},
|
|
113
|
+
};
|
|
114
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { Context } from '@deepseek-ai/cordis';
|
|
2
|
+
import type { EventPosition, LoggerPort, ModeDefinition } from '@saturn-universe/core';
|
|
3
|
+
import type { SqliteStore } from '@saturn-universe/storage';
|
|
4
|
+
import type { PluginSessionPaths, SaturnPluginRegistrarV1 } from '@saturn-universe/plugin-sdk';
|
|
5
|
+
import type { EnvProbeDependencies } from './env-probe-plugin.js';
|
|
6
|
+
import type { ModelResponsesOptions } from './model-responses-plugin.js';
|
|
7
|
+
import type { LoadedHostPlugin } from './plugin-loader.js';
|
|
8
|
+
import { PluginLifecycle } from './plugin-lifecycle.js';
|
|
9
|
+
import type { RequiredHostPlugin } from './required-host-plugin.js';
|
|
10
|
+
import type { SandboxPluginOptions } from './sandbox-plugin.js';
|
|
11
|
+
import type { SkillRegistryService } from '../skills-runtime.js';
|
|
12
|
+
import type { HostToolOptions } from './tools/index.js';
|
|
13
|
+
import type { WebSearchConfig } from '../user-config.js';
|
|
14
|
+
type PluginHostServices = Pick<SaturnPluginRegistrarV1, 'registerSecret' | 'redactValue' | 'resolveWorkspaceAssignment' | 'syncWorkspaceSubpaths' | 'onWorkerLifecycle'> & {
|
|
15
|
+
resolveSessionPaths?: (pluginId: string, sessionId: string) => PluginSessionPaths;
|
|
16
|
+
reportPluginStatus?: (pluginId: string, status: Readonly<Record<string, import('@saturn-universe/core').JsonValue>> | undefined) => void;
|
|
17
|
+
};
|
|
18
|
+
declare module '@deepseek-ai/cordis' {
|
|
19
|
+
interface Context {
|
|
20
|
+
saturnStorage: {
|
|
21
|
+
readonly store: SqliteStore;
|
|
22
|
+
};
|
|
23
|
+
saturnPluginHost: PluginHostServices & {
|
|
24
|
+
readonly workspaceRoot: string;
|
|
25
|
+
readonly logger: LoggerPort;
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
interface Events {
|
|
29
|
+
'saturn/storage-committed'(cursor: EventPosition): void;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
export declare function createPluginContext(): {
|
|
33
|
+
root: Context;
|
|
34
|
+
dispose: () => Promise<void>;
|
|
35
|
+
};
|
|
36
|
+
export declare function createHostContext(store: SqliteStore): {
|
|
37
|
+
root: Context;
|
|
38
|
+
dispose: () => Promise<void>;
|
|
39
|
+
};
|
|
40
|
+
export declare function startHostContext(store: SqliteStore, root: string, { envProbe, tools, model, activeMode, sandbox, skillService, webSearch, requiredPlugins, externalPlugins, timeoutMs, logger, pluginHostServices, }?: {
|
|
41
|
+
envProbe?: Partial<EnvProbeDependencies>;
|
|
42
|
+
tools?: HostToolOptions;
|
|
43
|
+
model?: ModelResponsesOptions;
|
|
44
|
+
activeMode?: ModeDefinition;
|
|
45
|
+
sandbox?: SandboxPluginOptions;
|
|
46
|
+
skillService?: SkillRegistryService;
|
|
47
|
+
webSearch?: {
|
|
48
|
+
config: WebSearchConfig;
|
|
49
|
+
apiKey: string;
|
|
50
|
+
};
|
|
51
|
+
requiredPlugins?: readonly RequiredHostPlugin[];
|
|
52
|
+
externalPlugins?: readonly LoadedHostPlugin[];
|
|
53
|
+
timeoutMs?: number;
|
|
54
|
+
logger?: LoggerPort;
|
|
55
|
+
pluginHostServices?: PluginHostServices;
|
|
56
|
+
}): Promise<{
|
|
57
|
+
dispose: () => Promise<void>;
|
|
58
|
+
lifecycle: PluginLifecycle;
|
|
59
|
+
ctx: Context;
|
|
60
|
+
}>;
|
|
61
|
+
export declare function startRequiredPlugins(host: ReturnType<typeof createPluginContext>, plugins: readonly RequiredHostPlugin[], timeoutMs?: number): Promise<{
|
|
62
|
+
ctx: Context;
|
|
63
|
+
dispose: () => Promise<void>;
|
|
64
|
+
}>;
|
|
65
|
+
export {};
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
import { Context } from '@deepseek-ai/cordis';
|
|
2
|
+
import { RuntimeError } from '@saturn-universe/core';
|
|
3
|
+
import { createHostLogger } from '../logger.js';
|
|
4
|
+
import { createContextCorePlugin } from './context-core-plugin.js';
|
|
5
|
+
import { createEnvProbePlugin } from './env-probe-plugin.js';
|
|
6
|
+
import { createModelResponsesPlugin } from './model-responses-plugin.js';
|
|
7
|
+
import { PluginLifecycle } from './plugin-lifecycle.js';
|
|
8
|
+
import { adaptCordisPlugin, adaptSaturnPlugin, HOST_PLUGIN_STARTUP_TIMEOUT_MS, } from './plugin-sdk-adapter.js';
|
|
9
|
+
import { runtimeHooksPlugin } from './runtime-hooks-plugin.js';
|
|
10
|
+
import { createSandboxPlugin } from './sandbox-plugin.js';
|
|
11
|
+
import { createToolPlugins } from './tools/index.js';
|
|
12
|
+
import { createSandboxTargetToolsPlugin } from './tools/sandbox-target-tools-plugin.js';
|
|
13
|
+
import { createWebSearchToolsPlugin } from './tools/web-search-tools-plugin.js';
|
|
14
|
+
const storageBridge = {
|
|
15
|
+
name: 'storage-bridge',
|
|
16
|
+
inject: ['saturnStorage'],
|
|
17
|
+
apply(ctx) {
|
|
18
|
+
const { store } = ctx.saturnStorage;
|
|
19
|
+
ctx.effect(() => store.subscribe((cursor) => ctx.emit('saturn/storage-committed', cursor)));
|
|
20
|
+
},
|
|
21
|
+
};
|
|
22
|
+
function pluginReadiness() {
|
|
23
|
+
let resolve;
|
|
24
|
+
let reject;
|
|
25
|
+
const promise = new Promise((ready, failed) => {
|
|
26
|
+
resolve = ready;
|
|
27
|
+
reject = failed;
|
|
28
|
+
});
|
|
29
|
+
return { promise, resolve, reject };
|
|
30
|
+
}
|
|
31
|
+
async function waitForPlugin(root, fiber, interrupted) {
|
|
32
|
+
const ready = pluginReadiness();
|
|
33
|
+
const check = () => {
|
|
34
|
+
void fiber.await().then((settled) => {
|
|
35
|
+
// Pending fibers settle without activating until all injections are available.
|
|
36
|
+
if (settled.committed)
|
|
37
|
+
ready.resolve();
|
|
38
|
+
}, ready.reject);
|
|
39
|
+
};
|
|
40
|
+
const stop = root.on('internal/status', (changed) => {
|
|
41
|
+
if (changed === fiber.ctx.fiber)
|
|
42
|
+
check();
|
|
43
|
+
});
|
|
44
|
+
try {
|
|
45
|
+
check();
|
|
46
|
+
await Promise.race([ready.promise, interrupted]);
|
|
47
|
+
}
|
|
48
|
+
finally {
|
|
49
|
+
await stop();
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
export function createPluginContext() {
|
|
53
|
+
const root = new Context();
|
|
54
|
+
let disposal;
|
|
55
|
+
return {
|
|
56
|
+
root,
|
|
57
|
+
dispose: () => (disposal ??= root.fiber.dispose()),
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
export function createHostContext(store) {
|
|
61
|
+
const host = createPluginContext();
|
|
62
|
+
host.root.provide('saturnStorage', { store });
|
|
63
|
+
return host;
|
|
64
|
+
}
|
|
65
|
+
export async function startHostContext(store, root, { envProbe, tools, model, activeMode, sandbox, skillService, webSearch, requiredPlugins = [], externalPlugins = [], timeoutMs = HOST_PLUGIN_STARTUP_TIMEOUT_MS, logger = createHostLogger([]), pluginHostServices, } = {}) {
|
|
66
|
+
const host = createHostContext(store);
|
|
67
|
+
host.root.provide('saturnPluginHost', { workspaceRoot: root, logger, ...pluginHostServices });
|
|
68
|
+
const effectiveMode = activeMode ?? {
|
|
69
|
+
ref: 'default@1',
|
|
70
|
+
displayName: 'default',
|
|
71
|
+
description: 'Default host mode',
|
|
72
|
+
sandbox: { backend: 'host', scope: 'none', fallbackPolicy: 'fail_closed' },
|
|
73
|
+
};
|
|
74
|
+
let startupDeadline = performance.now() + timeoutMs;
|
|
75
|
+
const required = await startRequiredPlugins(host, [
|
|
76
|
+
storageBridge,
|
|
77
|
+
runtimeHooksPlugin,
|
|
78
|
+
createEnvProbePlugin(root, envProbe),
|
|
79
|
+
createSandboxPlugin(root, effectiveMode, sandbox),
|
|
80
|
+
...(tools
|
|
81
|
+
? createToolPlugins(root, skillService ? { ...tools, skillService } : tools, ['saturnEnvProbe', 'saturnSandbox'], model !== undefined)
|
|
82
|
+
: []),
|
|
83
|
+
...(tools && tools.config.workspaceTools ? [createSandboxTargetToolsPlugin()] : []),
|
|
84
|
+
...(tools && webSearch ? [createWebSearchToolsPlugin(webSearch.config, webSearch.apiKey)] : []),
|
|
85
|
+
...(model ? [createModelResponsesPlugin(model)] : []),
|
|
86
|
+
...(model && tools ? [createContextCorePlugin(tools.hash, activeMode, skillService)] : []),
|
|
87
|
+
...requiredPlugins,
|
|
88
|
+
], timeoutMs);
|
|
89
|
+
const lifecycle = new PluginLifecycle(store, logger, (plugin, contributions) => mountExternalPlugin(required.ctx, plugin, contributions, startupDeadline === undefined ? timeoutMs : Math.max(0, Math.ceil(startupDeadline - performance.now()))));
|
|
90
|
+
const unsubscribe = required.ctx.on('saturn/storage-committed', () => lifecycle.requestDrain());
|
|
91
|
+
let disposal;
|
|
92
|
+
const dispose = () => (disposal ??= (async () => {
|
|
93
|
+
try {
|
|
94
|
+
await lifecycle.close();
|
|
95
|
+
}
|
|
96
|
+
finally {
|
|
97
|
+
await unsubscribe();
|
|
98
|
+
await required.dispose();
|
|
99
|
+
}
|
|
100
|
+
})());
|
|
101
|
+
try {
|
|
102
|
+
await lifecycle.replace(async () => externalPlugins);
|
|
103
|
+
return { ...required, dispose, lifecycle };
|
|
104
|
+
}
|
|
105
|
+
catch (error) {
|
|
106
|
+
await dispose();
|
|
107
|
+
throw error;
|
|
108
|
+
}
|
|
109
|
+
finally {
|
|
110
|
+
startupDeadline = undefined;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
async function mountExternalPlugin(root, { descriptor, config }, contributions, timeoutMs) {
|
|
114
|
+
const startup = new AbortController();
|
|
115
|
+
const interrupted = new Promise((_, reject) => {
|
|
116
|
+
startup.signal.addEventListener('abort', () => reject(startup.signal.reason), { once: true });
|
|
117
|
+
});
|
|
118
|
+
void interrupted.catch(() => undefined);
|
|
119
|
+
const activation = { signal: startup.signal, interrupted, contributions, ready: false };
|
|
120
|
+
const timer = setTimeout(() => {
|
|
121
|
+
startup.abort(new RuntimeError('HOST_PLUGIN_STARTUP_TIMEOUT', `Host plugin timed out after ${timeoutMs}ms: ${descriptor.kind === 'cordis' ? 'cordis' : 'saturn'}-plugin:${descriptor.id}`));
|
|
122
|
+
}, timeoutMs);
|
|
123
|
+
let fiber;
|
|
124
|
+
try {
|
|
125
|
+
fiber =
|
|
126
|
+
descriptor.kind === 'cordis'
|
|
127
|
+
? adaptCordisPlugin(descriptor, config, root, activation)
|
|
128
|
+
: root.plugin(adaptSaturnPlugin(descriptor, config, contributions), startup.signal);
|
|
129
|
+
await waitForPlugin(root, fiber, interrupted);
|
|
130
|
+
activation.ready = true;
|
|
131
|
+
const mounted = fiber;
|
|
132
|
+
return () => mounted.dispose();
|
|
133
|
+
}
|
|
134
|
+
catch (error) {
|
|
135
|
+
startup.abort(error);
|
|
136
|
+
await contributions.dispose(false);
|
|
137
|
+
await fiber?.dispose().catch(() => undefined);
|
|
138
|
+
throw error;
|
|
139
|
+
}
|
|
140
|
+
finally {
|
|
141
|
+
clearTimeout(timer);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
export async function startRequiredPlugins(host, plugins, timeoutMs = HOST_PLUGIN_STARTUP_TIMEOUT_MS) {
|
|
145
|
+
const startup = new AbortController();
|
|
146
|
+
const interrupted = new Promise((_, reject) => {
|
|
147
|
+
startup.signal.addEventListener('abort', () => reject(startup.signal.reason), { once: true });
|
|
148
|
+
});
|
|
149
|
+
void interrupted.catch(() => undefined);
|
|
150
|
+
const pending = new Set(plugins.map(({ name }) => name));
|
|
151
|
+
const mounted = [];
|
|
152
|
+
let disposal;
|
|
153
|
+
const dispose = () => (disposal ??= (async () => {
|
|
154
|
+
const errors = [];
|
|
155
|
+
for (const fiber of mounted.reverse()) {
|
|
156
|
+
try {
|
|
157
|
+
await fiber.dispose();
|
|
158
|
+
}
|
|
159
|
+
catch (error) {
|
|
160
|
+
errors.push(error);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
await host.dispose();
|
|
164
|
+
if (errors.length)
|
|
165
|
+
throw new AggregateError(errors, 'Host plugin disposal failed');
|
|
166
|
+
})());
|
|
167
|
+
const timer = setTimeout(() => {
|
|
168
|
+
startup.abort(new RuntimeError('HOST_PLUGIN_STARTUP_TIMEOUT', `Host plugins timed out after ${timeoutMs}ms: ${[...pending].join(', ')}`));
|
|
169
|
+
}, timeoutMs);
|
|
170
|
+
try {
|
|
171
|
+
await Promise.all(plugins.map(async (plugin) => {
|
|
172
|
+
const fiber = host.root.plugin({
|
|
173
|
+
name: plugin.name,
|
|
174
|
+
...(plugin.inject ? { inject: plugin.inject } : {}),
|
|
175
|
+
async apply(ctx) {
|
|
176
|
+
startup.signal.throwIfAborted();
|
|
177
|
+
// An injected provider starts before its consumers, so its disposal runs after theirs.
|
|
178
|
+
mounted.push(ctx.fiber);
|
|
179
|
+
await Promise.race([plugin.apply(ctx, startup.signal), interrupted]);
|
|
180
|
+
},
|
|
181
|
+
});
|
|
182
|
+
await waitForPlugin(host.root, fiber, interrupted);
|
|
183
|
+
pending.delete(plugin.name);
|
|
184
|
+
}));
|
|
185
|
+
return { ctx: host.root, dispose };
|
|
186
|
+
}
|
|
187
|
+
catch (error) {
|
|
188
|
+
startup.abort(error);
|
|
189
|
+
try {
|
|
190
|
+
await dispose();
|
|
191
|
+
}
|
|
192
|
+
finally {
|
|
193
|
+
throw error;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
finally {
|
|
197
|
+
clearTimeout(timer);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import type { Context } from '@deepseek-ai/cordis';
|
|
2
|
+
import type { Hash, HostCommand, ModelRef, ProviderProfile, RunConfig } from '@saturn-universe/core';
|
|
3
|
+
import { ProviderRegistry } from '@saturn-universe/model';
|
|
4
|
+
import type { ModelDisplay } from '@saturn-universe/protocol';
|
|
5
|
+
import type { ProviderCatalog } from '../provider-catalog.js';
|
|
6
|
+
declare module '@deepseek-ai/cordis' {
|
|
7
|
+
interface Context {
|
|
8
|
+
saturnModel: ReturnType<typeof createModelService>;
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
export interface ModelResponsesOptions {
|
|
12
|
+
readonly catalog: ProviderCatalog | undefined;
|
|
13
|
+
readonly entryProfile: string | undefined;
|
|
14
|
+
readonly profile: string | undefined;
|
|
15
|
+
readonly taskProfile: string | undefined;
|
|
16
|
+
readonly credential: (ref: string) => string | undefined;
|
|
17
|
+
readonly hash: Hash;
|
|
18
|
+
}
|
|
19
|
+
type RunModelInput = Pick<Extract<HostCommand, {
|
|
20
|
+
type: 'run.submit';
|
|
21
|
+
}>['input'], 'model' | 'config' | 'profile' | 'taskProfile'>;
|
|
22
|
+
export declare function createModelResponsesPlugin(options: ModelResponsesOptions): {
|
|
23
|
+
name: string;
|
|
24
|
+
apply(ctx: Context): void;
|
|
25
|
+
};
|
|
26
|
+
declare function createModelService(ctx: Context, options: ModelResponsesOptions): {
|
|
27
|
+
providers: ProviderRegistry;
|
|
28
|
+
gateway: import("@saturn-universe/core").ModelGateway & {
|
|
29
|
+
execute(request: import("@saturn-universe/core").ModelRequest, options: import("@saturn-universe/core").ModelInvocationOptions): Promise<import("@saturn-universe/core").ModelResponse>;
|
|
30
|
+
};
|
|
31
|
+
defaultModel: ModelRef | undefined;
|
|
32
|
+
registerProfile: (profile: ProviderProfile) => () => void;
|
|
33
|
+
releaseProfile(profileRef: string): void;
|
|
34
|
+
requireActive: (model: ModelRef) => void;
|
|
35
|
+
selectRunModel: (input: RunModelInput) => {
|
|
36
|
+
model: ModelRef;
|
|
37
|
+
resolvedModel: {
|
|
38
|
+
profile: ProviderProfile;
|
|
39
|
+
binding: import("@saturn-universe/core").ProviderBinding;
|
|
40
|
+
capabilities: import("@saturn-universe/core").ModelCapabilities;
|
|
41
|
+
};
|
|
42
|
+
profileReasoningEffort: string | undefined;
|
|
43
|
+
};
|
|
44
|
+
resolveFrozenModel: (config: RunConfig) => {
|
|
45
|
+
profile: ProviderProfile;
|
|
46
|
+
binding: import("@saturn-universe/core").ProviderBinding;
|
|
47
|
+
capabilities: import("@saturn-universe/core").ModelCapabilities;
|
|
48
|
+
};
|
|
49
|
+
verifyCheckpointCredential(config: RunConfig): void;
|
|
50
|
+
modelDisplay: (model: ModelRef, effort?: string) => ModelDisplay;
|
|
51
|
+
defaultModelDisplay: (model: ModelRef, profileReasoningEffort?: string) => {
|
|
52
|
+
defaultReasoningEffort: string | null;
|
|
53
|
+
contextWindow: number;
|
|
54
|
+
reasoningModel: boolean;
|
|
55
|
+
reasoningEfforts: string[];
|
|
56
|
+
modelId: string;
|
|
57
|
+
reasoningEffort?: string;
|
|
58
|
+
};
|
|
59
|
+
pricingForModel: (model: ModelRef) => {};
|
|
60
|
+
statusSummary(): {
|
|
61
|
+
profiles?: {
|
|
62
|
+
ready: boolean;
|
|
63
|
+
capabilityDigest: string;
|
|
64
|
+
defaultReasoningEffort: string | null;
|
|
65
|
+
contextWindow: number;
|
|
66
|
+
reasoningModel: boolean;
|
|
67
|
+
reasoningEfforts: string[];
|
|
68
|
+
modelId: string;
|
|
69
|
+
reasoningEffort?: string;
|
|
70
|
+
protocol?: "openai-responses" | "openai-chat" | "anthropic" | "gemini";
|
|
71
|
+
name: string;
|
|
72
|
+
providerId: string;
|
|
73
|
+
revision: string;
|
|
74
|
+
codecVersion: 1 | 2;
|
|
75
|
+
}[];
|
|
76
|
+
selectedProfile?: string;
|
|
77
|
+
defaultProfile?: string;
|
|
78
|
+
configuredProfiles: number;
|
|
79
|
+
};
|
|
80
|
+
};
|
|
81
|
+
export {};
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
import { canonicalJson, RuntimeError } from '@saturn-universe/core';
|
|
2
|
+
import { createModelGateway, GatewayError, ProviderRegistry } from '@saturn-universe/model';
|
|
3
|
+
import { catalogRegistrations, profileModel, resolveRunDefaults, selectProfile, } from '../provider-catalog.js';
|
|
4
|
+
import { registerPluginContribution } from './plugin-contributions.js';
|
|
5
|
+
export function createModelResponsesPlugin(options) {
|
|
6
|
+
return {
|
|
7
|
+
name: 'model-responses',
|
|
8
|
+
apply(ctx) {
|
|
9
|
+
ctx.provide('saturnModel', createModelService(ctx, options));
|
|
10
|
+
},
|
|
11
|
+
};
|
|
12
|
+
}
|
|
13
|
+
function createModelService(ctx, options) {
|
|
14
|
+
const { catalog, entryProfile, taskProfile, credential, hash } = options;
|
|
15
|
+
const providers = new ProviderRegistry();
|
|
16
|
+
const registerRaw = providers.register.bind(providers);
|
|
17
|
+
const contributed = new Set();
|
|
18
|
+
const retired = new Set();
|
|
19
|
+
const register = (profile) => ctx.effect(() => registerRaw(profile));
|
|
20
|
+
if (catalog)
|
|
21
|
+
for (const profile of catalogRegistrations(catalog))
|
|
22
|
+
register(profile);
|
|
23
|
+
const defaultModel = catalog && (catalog.profiles.length || entryProfile || taskProfile)
|
|
24
|
+
? profileModel(selectProfile(catalog, {
|
|
25
|
+
...(entryProfile ? { entryProfile } : {}),
|
|
26
|
+
...(taskProfile ? { taskProfile } : {}),
|
|
27
|
+
}))
|
|
28
|
+
: undefined;
|
|
29
|
+
function requireCredential(ref) {
|
|
30
|
+
const value = credential(ref);
|
|
31
|
+
if (!value?.trim())
|
|
32
|
+
throw new RuntimeError('CREDENTIAL_UNAVAILABLE', 'Credential reference unavailable');
|
|
33
|
+
return value;
|
|
34
|
+
}
|
|
35
|
+
const vault = {
|
|
36
|
+
async resolve(ref) {
|
|
37
|
+
return requireCredential(ref);
|
|
38
|
+
},
|
|
39
|
+
};
|
|
40
|
+
const gateway = createModelGateway(providers, vault);
|
|
41
|
+
function requireActive(model) {
|
|
42
|
+
if (!providers.isActive(model.profileRef))
|
|
43
|
+
throw new RuntimeError('PLUGIN_INACTIVE', `Model profile ${model.profileRef} is inactive`);
|
|
44
|
+
}
|
|
45
|
+
function selectRunModel(input) {
|
|
46
|
+
if (input.model &&
|
|
47
|
+
input.config?.model &&
|
|
48
|
+
canonicalJson(input.model) !== canonicalJson(input.config.model))
|
|
49
|
+
throw new RuntimeError('INVALID_CONFIG', 'Run model selections conflict');
|
|
50
|
+
const explicitModel = input.model ?? input.config?.model;
|
|
51
|
+
if (explicitModel && (input.profile !== undefined || input.taskProfile !== undefined))
|
|
52
|
+
throw new RuntimeError('INVALID_CONFIG', 'Run selectors are mutually exclusive');
|
|
53
|
+
if (!catalog && (input.profile || input.taskProfile || options.profile || taskProfile))
|
|
54
|
+
throw new RuntimeError('INVALID_CONFIG', 'Profiles require TOML configuration');
|
|
55
|
+
const requestTaskProfile = input.taskProfile ?? (!explicitModel && !input.profile ? taskProfile : undefined);
|
|
56
|
+
const isContribution = explicitModel && (contributed.has(explicitModel.profileRef) || retired.has(explicitModel.profileRef));
|
|
57
|
+
const selected = catalog && !isContribution
|
|
58
|
+
? selectProfile(catalog, {
|
|
59
|
+
...(explicitModel ? { model: explicitModel } : {}),
|
|
60
|
+
...(input.profile ? { profile: input.profile } : {}),
|
|
61
|
+
...(entryProfile ? { entryProfile } : {}),
|
|
62
|
+
...(requestTaskProfile ? { taskProfile: requestTaskProfile } : {}),
|
|
63
|
+
})
|
|
64
|
+
: undefined;
|
|
65
|
+
const model = selected ? profileModel(selected) : (explicitModel ?? defaultModel);
|
|
66
|
+
if (!model || (!isContribution && !catalog))
|
|
67
|
+
throw new RuntimeError('INVALID_CONFIG', 'Run model does not match configured Provider');
|
|
68
|
+
if (selected)
|
|
69
|
+
requireCredential(selected.credentialRef);
|
|
70
|
+
requireActive(model);
|
|
71
|
+
const resolvedModel = providers.resolve(model);
|
|
72
|
+
if (isContribution)
|
|
73
|
+
requireCredential(resolvedModel.profile.apiKeyRef);
|
|
74
|
+
return { model, resolvedModel, profileReasoningEffort: selected?.defaultReasoningEffort };
|
|
75
|
+
}
|
|
76
|
+
function resolveFrozenModel(config) {
|
|
77
|
+
const model = config.model;
|
|
78
|
+
const expected = config.pluginBindings?.modelProvider;
|
|
79
|
+
const unavailable = () => new RuntimeError('PLUGIN_VERSION_UNAVAILABLE', `Model profile ${expected?.profileRef ?? model.profileRef} is unavailable or changed`);
|
|
80
|
+
let resolved;
|
|
81
|
+
try {
|
|
82
|
+
resolved = providers.resolve(model);
|
|
83
|
+
}
|
|
84
|
+
catch (error) {
|
|
85
|
+
if (error instanceof GatewayError)
|
|
86
|
+
throw unavailable();
|
|
87
|
+
throw error;
|
|
88
|
+
}
|
|
89
|
+
const { binding } = resolved;
|
|
90
|
+
if ((config.providerBinding && hash(config.providerBinding) !== hash(binding)) ||
|
|
91
|
+
(expected &&
|
|
92
|
+
(expected.profileRef !== model.profileRef ||
|
|
93
|
+
expected.providerId !== binding.profileId ||
|
|
94
|
+
expected.revision !== binding.profileRevision ||
|
|
95
|
+
(expected.compatibilityKey !== undefined &&
|
|
96
|
+
expected.compatibilityKey !== binding.compatibilityKey))))
|
|
97
|
+
throw unavailable();
|
|
98
|
+
return resolved;
|
|
99
|
+
}
|
|
100
|
+
function modelDisplay(model, effort) {
|
|
101
|
+
if (effort)
|
|
102
|
+
return { modelId: model.modelId, reasoningEffort: effort };
|
|
103
|
+
try {
|
|
104
|
+
if (providers.resolve(model).capabilities.responses?.reasoningModel)
|
|
105
|
+
return { modelId: model.modelId, reasoningEffort: 'auto' };
|
|
106
|
+
}
|
|
107
|
+
catch (error) {
|
|
108
|
+
if (!(error instanceof RuntimeError))
|
|
109
|
+
throw error;
|
|
110
|
+
}
|
|
111
|
+
return { modelId: model.modelId };
|
|
112
|
+
}
|
|
113
|
+
function defaultModelDisplay(model, profileReasoningEffort) {
|
|
114
|
+
const { capabilities } = providers.resolve(model);
|
|
115
|
+
const options = {
|
|
116
|
+
capabilities,
|
|
117
|
+
...(profileReasoningEffort ? { profileReasoningEffort } : {}),
|
|
118
|
+
};
|
|
119
|
+
const reasoning = resolveRunDefaults(model, catalog?.runDefaults, options).responses.reasoning;
|
|
120
|
+
return {
|
|
121
|
+
...modelDisplay(model, reasoning?.effort),
|
|
122
|
+
defaultReasoningEffort: resolveRunDefaults(model, undefined, options).responses.reasoning?.effort ?? null,
|
|
123
|
+
contextWindow: capabilities.contextWindow,
|
|
124
|
+
reasoningModel: capabilities.responses.reasoningModel,
|
|
125
|
+
reasoningEfforts: [...capabilities.responses.reasoningEfforts],
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
function pricingForModel(model) {
|
|
129
|
+
const profile = catalog?.profiles.find((p) => {
|
|
130
|
+
const ref = profileModel(p);
|
|
131
|
+
return (ref.providerId === model.providerId &&
|
|
132
|
+
ref.modelId === model.modelId &&
|
|
133
|
+
ref.profileRef === model.profileRef);
|
|
134
|
+
});
|
|
135
|
+
return profile ? profilePricing(profile) : {};
|
|
136
|
+
}
|
|
137
|
+
function profilePricing(profile) {
|
|
138
|
+
return profile.pricing
|
|
139
|
+
? {
|
|
140
|
+
pricing: profile.pricing,
|
|
141
|
+
...(profile.pricingSource ? { pricingSource: profile.pricingSource } : {}),
|
|
142
|
+
}
|
|
143
|
+
: {};
|
|
144
|
+
}
|
|
145
|
+
function registerProfile(profile, hostEffect) {
|
|
146
|
+
const ref = `${profile.id}@${profile.revision}`;
|
|
147
|
+
return registerPluginContribution({ kind: 'model', ref }, (managed) => {
|
|
148
|
+
const deactivate = hostEffect && !managed ? register(profile) : registerRaw(profile);
|
|
149
|
+
if (hostEffect || managed)
|
|
150
|
+
contributed.add(ref);
|
|
151
|
+
return {
|
|
152
|
+
deactivate,
|
|
153
|
+
activate: () => providers.activate(ref),
|
|
154
|
+
release(rememberInactive) {
|
|
155
|
+
if (rememberInactive)
|
|
156
|
+
retired.add(ref);
|
|
157
|
+
contributed.delete(ref);
|
|
158
|
+
providers.release(ref);
|
|
159
|
+
},
|
|
160
|
+
};
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
providers.register = (profile) => registerProfile(profile, false);
|
|
164
|
+
return {
|
|
165
|
+
providers,
|
|
166
|
+
gateway,
|
|
167
|
+
defaultModel,
|
|
168
|
+
registerProfile: (profile) => registerProfile(profile, true),
|
|
169
|
+
releaseProfile(profileRef) {
|
|
170
|
+
contributed.delete(profileRef);
|
|
171
|
+
providers.release(profileRef);
|
|
172
|
+
},
|
|
173
|
+
requireActive,
|
|
174
|
+
selectRunModel,
|
|
175
|
+
resolveFrozenModel,
|
|
176
|
+
verifyCheckpointCredential(config) {
|
|
177
|
+
requireCredential(resolveFrozenModel(config).profile.apiKeyRef);
|
|
178
|
+
},
|
|
179
|
+
modelDisplay,
|
|
180
|
+
defaultModelDisplay,
|
|
181
|
+
pricingForModel,
|
|
182
|
+
statusSummary() {
|
|
183
|
+
return {
|
|
184
|
+
configuredProfiles: catalog?.profiles.length ?? 0,
|
|
185
|
+
...(catalog
|
|
186
|
+
? {
|
|
187
|
+
...(catalog.defaultProfile ? { defaultProfile: catalog.defaultProfile } : {}),
|
|
188
|
+
...(defaultModel
|
|
189
|
+
? {
|
|
190
|
+
selectedProfile: catalog.profiles.find((p) => canonicalJson(profileModel(p)) === canonicalJson(defaultModel)).name,
|
|
191
|
+
}
|
|
192
|
+
: {}),
|
|
193
|
+
profiles: catalog.profiles.map((p) => ({
|
|
194
|
+
name: p.name,
|
|
195
|
+
providerId: p.providerId,
|
|
196
|
+
revision: p.revision,
|
|
197
|
+
codecVersion: p.codecVersion,
|
|
198
|
+
...(p.protocol ? { protocol: p.protocol } : {}),
|
|
199
|
+
...defaultModelDisplay(profileModel(p), p.defaultReasoningEffort),
|
|
200
|
+
capabilityDigest: providers.resolve(profileModel(p)).binding.capabilityDigest,
|
|
201
|
+
...profilePricing(p),
|
|
202
|
+
ready: Boolean(credential(p.credentialRef)?.trim()),
|
|
203
|
+
})),
|
|
204
|
+
}
|
|
205
|
+
: {}),
|
|
206
|
+
};
|
|
207
|
+
},
|
|
208
|
+
};
|
|
209
|
+
}
|