@saturn-universe/runtime-host 0.0.0-stage → 0.1.1
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 +478 -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 +472 -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,310 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
import { readFile, realpath, stat } from 'node:fs/promises';
|
|
3
|
+
import { createRequire, findPackageJSON, registerHooks } from 'node:module';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
6
|
+
import { Context } from '@deepseek-ai/cordis';
|
|
7
|
+
import { canonicalJson, RuntimeError } from '@saturn-universe/core';
|
|
8
|
+
import { SATURN_PLUGIN_SDK_VERSION, SUPPORTED_CORDIS_VERSION, validatePluginCompatibility, } from '@saturn-universe/plugin-sdk';
|
|
9
|
+
import { resolve } from 'import-meta-resolve';
|
|
10
|
+
import semver from 'semver';
|
|
11
|
+
import { resolveBuiltinPluginEntry } from '../modes.js';
|
|
12
|
+
import { HOST_PLUGIN_STARTUP_TIMEOUT_MS } from './plugin-sdk-adapter.js';
|
|
13
|
+
const sdkPackage = '@saturn-universe/plugin-sdk';
|
|
14
|
+
const cordisPackage = '@deepseek-ai/cordis';
|
|
15
|
+
const hostRequire = createRequire(import.meta.url);
|
|
16
|
+
// External plugin imports must go through Node's loader, including under the test module runner.
|
|
17
|
+
const nativeImportModule = 'data:text/javascript,export const load = (url) => import(url)';
|
|
18
|
+
export async function loadModePlugins(activeMode, configuration, logger, reload) {
|
|
19
|
+
const { configPath, configSource, trustedPlugins } = configuration;
|
|
20
|
+
const isTrusted = Boolean(trustedPlugins && (configSource === 'user' || configSource === 'explicit'));
|
|
21
|
+
const bindings = [...(activeMode.plugins ?? [])].sort((a, b) => a.id.localeCompare(b.id));
|
|
22
|
+
if (!isTrusted) {
|
|
23
|
+
let hasEnabledUntrusted = false;
|
|
24
|
+
for (const binding of bindings) {
|
|
25
|
+
const id = binding.id;
|
|
26
|
+
if (binding.builtin) {
|
|
27
|
+
if (binding.enabled === false)
|
|
28
|
+
continue;
|
|
29
|
+
if (binding.entry) {
|
|
30
|
+
logger.error({ code: 'PLUGIN_TRUST_REQUIRED', configSource, pluginId: id, enabled: true }, 'Executable plugins require a user or explicit Host configuration');
|
|
31
|
+
hasEnabledUntrusted = true;
|
|
32
|
+
}
|
|
33
|
+
continue;
|
|
34
|
+
}
|
|
35
|
+
const enabled = binding.enabled ?? Boolean(binding.entry);
|
|
36
|
+
logger.error({ code: 'PLUGIN_TRUST_REQUIRED', configSource, pluginId: id, enabled }, 'Executable plugins require a user or explicit Host configuration');
|
|
37
|
+
if (enabled)
|
|
38
|
+
hasEnabledUntrusted = true;
|
|
39
|
+
}
|
|
40
|
+
if (hasEnabledUntrusted) {
|
|
41
|
+
throw new RuntimeError('PLUGIN_TRUST_REQUIRED', 'Enabled plugins require a user or explicit Host configuration');
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
const loaded = [];
|
|
45
|
+
for (const binding of bindings) {
|
|
46
|
+
const id = binding.id;
|
|
47
|
+
if (reload?.pluginId !== undefined && reload.pluginId !== id)
|
|
48
|
+
continue;
|
|
49
|
+
if (binding.builtin) {
|
|
50
|
+
if (binding.enabled === false)
|
|
51
|
+
continue;
|
|
52
|
+
let filename;
|
|
53
|
+
let directoryManifest;
|
|
54
|
+
if (binding.entry) {
|
|
55
|
+
if (!configPath)
|
|
56
|
+
throw new RuntimeError('INVALID_CONFIG', 'Plugin configuration requires a file path');
|
|
57
|
+
const resolved = await resolveEntry(id, path.dirname(configPath), binding.entry);
|
|
58
|
+
filename = resolved.filename;
|
|
59
|
+
directoryManifest = resolved.directoryManifest;
|
|
60
|
+
}
|
|
61
|
+
else {
|
|
62
|
+
filename = resolveBuiltinPluginEntry(binding.builtin);
|
|
63
|
+
directoryManifest = path.join(path.dirname(filename), 'package.json');
|
|
64
|
+
}
|
|
65
|
+
const mergedConfig = binding.config ? { ...binding.config } : undefined;
|
|
66
|
+
loaded.push(await loadPluginFromEntry(id, filename, directoryManifest, mergedConfig, reload));
|
|
67
|
+
continue;
|
|
68
|
+
}
|
|
69
|
+
const enabled = binding.enabled ?? Boolean(binding.entry);
|
|
70
|
+
if (!enabled)
|
|
71
|
+
continue;
|
|
72
|
+
const entry = binding.entry;
|
|
73
|
+
if (!entry) {
|
|
74
|
+
throw new RuntimeError('INVALID_CONFIG', `Mode ${activeMode.ref} plugin ${id} is missing an entry`);
|
|
75
|
+
}
|
|
76
|
+
if (!configPath)
|
|
77
|
+
throw new RuntimeError('INVALID_CONFIG', 'Plugin configuration requires a file path');
|
|
78
|
+
const resolved = await resolveEntry(id, path.dirname(configPath), entry);
|
|
79
|
+
const mergedConfig = binding.config ? { ...binding.config } : undefined;
|
|
80
|
+
loaded.push(await loadPluginFromEntry(id, resolved.filename, resolved.directoryManifest, mergedConfig, reload));
|
|
81
|
+
}
|
|
82
|
+
return loaded;
|
|
83
|
+
}
|
|
84
|
+
async function loadPluginFromEntry(id, filename, directoryManifest, config, reload) {
|
|
85
|
+
const entryUrl = pathToFileURL(filename).href;
|
|
86
|
+
await verifyCordisImport(id, entryUrl);
|
|
87
|
+
await verifyPackageDependencies(id, filename, directoryManifest);
|
|
88
|
+
const previous = reload?.active.get(id);
|
|
89
|
+
if (previous?.entryUrl === entryUrl &&
|
|
90
|
+
previous.files &&
|
|
91
|
+
previous.files.size &&
|
|
92
|
+
canonicalJson(config ?? null) === canonicalJson(previous.config ?? null) &&
|
|
93
|
+
(await filesUnchanged(previous.files))) {
|
|
94
|
+
validateDescriptor(id, previous.descriptor);
|
|
95
|
+
if (previous.descriptor.kind === 'cordis')
|
|
96
|
+
await verifyCordisInstance(id, filename);
|
|
97
|
+
return previous;
|
|
98
|
+
}
|
|
99
|
+
const { exports, files } = await importPlugin(id, entryUrl, reload?.timeoutMs ?? HOST_PLUGIN_STARTUP_TIMEOUT_MS);
|
|
100
|
+
const descriptor = validateDescriptor(id, exports.default ?? exports.plugin);
|
|
101
|
+
if (descriptor.kind === 'cordis')
|
|
102
|
+
await verifyCordisInstance(id, filename);
|
|
103
|
+
return { descriptor, config, entryUrl, files };
|
|
104
|
+
}
|
|
105
|
+
function digest(source) {
|
|
106
|
+
const bytes = typeof source === 'string'
|
|
107
|
+
? source
|
|
108
|
+
: ArrayBuffer.isView(source)
|
|
109
|
+
? Buffer.from(source.buffer, source.byteOffset, source.byteLength)
|
|
110
|
+
: Buffer.from(source);
|
|
111
|
+
return createHash('sha256').update(bytes).digest('hex');
|
|
112
|
+
}
|
|
113
|
+
async function filesUnchanged(files) {
|
|
114
|
+
return (await Promise.all([...files].map(async ([url, hash]) => {
|
|
115
|
+
try {
|
|
116
|
+
return digest(await readFile(new URL(url))) === hash;
|
|
117
|
+
}
|
|
118
|
+
catch {
|
|
119
|
+
return false;
|
|
120
|
+
}
|
|
121
|
+
}))).every(Boolean);
|
|
122
|
+
}
|
|
123
|
+
async function importPlugin(id, entryUrl, timeoutMs) {
|
|
124
|
+
const parameter = 'saturn-plugin-generation';
|
|
125
|
+
const generation = randomUUID();
|
|
126
|
+
const entry = new URL(entryUrl);
|
|
127
|
+
entry.searchParams.set(parameter, generation);
|
|
128
|
+
const files = new Map();
|
|
129
|
+
const isGeneration = (url) => url?.startsWith('file:') && new URL(url).searchParams.get(parameter) === generation;
|
|
130
|
+
const hooks = registerHooks({
|
|
131
|
+
resolve(specifier, context, next) {
|
|
132
|
+
const resolved = next(specifier, context);
|
|
133
|
+
// Keep shared packages, including both SDK and Cordis, on Node's normal cache keys.
|
|
134
|
+
if (!isGeneration(context.parentURL) ||
|
|
135
|
+
!/^(\.\.?[/\\]|file:)/.test(specifier) ||
|
|
136
|
+
!resolved.url.startsWith('file:') ||
|
|
137
|
+
new URL(resolved.url).pathname.split('/').includes('node_modules'))
|
|
138
|
+
return resolved;
|
|
139
|
+
const url = new URL(resolved.url);
|
|
140
|
+
url.searchParams.set(parameter, generation);
|
|
141
|
+
return { ...resolved, url: url.href };
|
|
142
|
+
},
|
|
143
|
+
load(url, context, next) {
|
|
144
|
+
const loaded = next(url, context);
|
|
145
|
+
if (isGeneration(url) && loaded.source !== null && loaded.source !== undefined) {
|
|
146
|
+
const file = new URL(url);
|
|
147
|
+
file.searchParams.delete(parameter);
|
|
148
|
+
files.set(file.href, digest(loaded.source));
|
|
149
|
+
}
|
|
150
|
+
return loaded;
|
|
151
|
+
},
|
|
152
|
+
});
|
|
153
|
+
let timer;
|
|
154
|
+
try {
|
|
155
|
+
const timeout = new Promise((_, reject) => {
|
|
156
|
+
timer = setTimeout(() => reject(new RuntimeError('HOST_PLUGIN_STARTUP_TIMEOUT', `Plugin ${id} import timed out`)), timeoutMs);
|
|
157
|
+
});
|
|
158
|
+
const exports = await Promise.race([
|
|
159
|
+
import(/* @vite-ignore */ nativeImportModule)
|
|
160
|
+
.then(({ load }) => load(entry.href))
|
|
161
|
+
.catch(() => {
|
|
162
|
+
throw new RuntimeError('PLUGIN_IMPORT_FAILED', `Could not import plugin ${id}`);
|
|
163
|
+
}),
|
|
164
|
+
timeout,
|
|
165
|
+
]);
|
|
166
|
+
return { exports, files };
|
|
167
|
+
}
|
|
168
|
+
finally {
|
|
169
|
+
clearTimeout(timer);
|
|
170
|
+
hooks.deregister();
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
async function resolveEntry(id, directory, entry) {
|
|
174
|
+
try {
|
|
175
|
+
// Drive-relative paths would otherwise fall back to that drive's working directory on Windows.
|
|
176
|
+
const root = path.parse(entry).root;
|
|
177
|
+
if (process.platform === 'win32' && root && (!path.isAbsolute(entry) || root.length === 1))
|
|
178
|
+
throw new Error('A Windows absolute path requires a drive or network share');
|
|
179
|
+
const target = await realpath(path.resolve(directory, entry));
|
|
180
|
+
if ((await stat(target)).isFile())
|
|
181
|
+
return { filename: target };
|
|
182
|
+
const directoryManifest = path.join(target, 'package.json');
|
|
183
|
+
const manifest = await readManifest(directoryManifest);
|
|
184
|
+
const entryFile = typeof manifest?.name === 'string' && manifest.exports !== undefined && manifest.exports !== null
|
|
185
|
+
? fileURLToPath(resolve(manifest.name, pathToFileURL(directoryManifest).href))
|
|
186
|
+
: hostRequire.resolve(target);
|
|
187
|
+
const filename = await realpath(entryFile);
|
|
188
|
+
if ((await stat(filename)).isFile())
|
|
189
|
+
return { filename, directoryManifest };
|
|
190
|
+
}
|
|
191
|
+
catch {
|
|
192
|
+
// Keep filesystem paths and contents out of startup diagnostics.
|
|
193
|
+
}
|
|
194
|
+
throw new RuntimeError('PLUGIN_ENTRY_INVALID', `Plugin ${id} requires an existing local module or package entry`);
|
|
195
|
+
}
|
|
196
|
+
function validateDescriptor(id, value) {
|
|
197
|
+
const invalid = () => new RuntimeError('INVALID_PLUGIN_DESCRIPTOR', `Invalid descriptor for plugin ${id}`);
|
|
198
|
+
if (!isRecord(value))
|
|
199
|
+
throw invalid();
|
|
200
|
+
const { kind, apiVersion, sdkVersion, version, cordisVersion, cordisContextClass, plugin } = value;
|
|
201
|
+
if (typeof value.id !== 'string' ||
|
|
202
|
+
typeof version !== 'string' ||
|
|
203
|
+
!version.trim() ||
|
|
204
|
+
version !== version.trim() ||
|
|
205
|
+
typeof apiVersion !== 'number' ||
|
|
206
|
+
(sdkVersion !== undefined && typeof sdkVersion !== 'string'))
|
|
207
|
+
throw invalid();
|
|
208
|
+
if (value.id !== id)
|
|
209
|
+
throw new RuntimeError('PLUGIN_ID_MISMATCH', `The descriptor ID must match the configured plugin ID ${id}`);
|
|
210
|
+
const common = { apiVersion, ...(sdkVersion !== undefined ? { sdkVersion } : {}) };
|
|
211
|
+
const compatibility = kind === 'saturn-registrar' && typeof value.setup === 'function'
|
|
212
|
+
? validatePluginCompatibility({ ...common, kind })
|
|
213
|
+
: kind === 'cordis' &&
|
|
214
|
+
typeof cordisVersion === 'string' &&
|
|
215
|
+
(typeof plugin === 'function' || (isRecord(plugin) && typeof plugin.apply === 'function'))
|
|
216
|
+
? validatePluginCompatibility({
|
|
217
|
+
...common,
|
|
218
|
+
kind,
|
|
219
|
+
cordisVersion,
|
|
220
|
+
cordisContextClass,
|
|
221
|
+
hostCordisContextClass: Context,
|
|
222
|
+
})
|
|
223
|
+
: undefined;
|
|
224
|
+
if (!compatibility)
|
|
225
|
+
throw invalid();
|
|
226
|
+
if (!compatibility.ok)
|
|
227
|
+
throw new RuntimeError(compatibility.error.code, compatibility.error.message);
|
|
228
|
+
return value;
|
|
229
|
+
}
|
|
230
|
+
function cordisInstanceMismatch(id) {
|
|
231
|
+
return new RuntimeError('PLUGIN_CORDIS_INSTANCE_MISMATCH', `Plugin ${id} must resolve the Host's Cordis instance`);
|
|
232
|
+
}
|
|
233
|
+
async function verifyCordisImport(id, entryUrl) {
|
|
234
|
+
let pluginCordis;
|
|
235
|
+
try {
|
|
236
|
+
pluginCordis = resolve(cordisPackage, entryUrl);
|
|
237
|
+
}
|
|
238
|
+
catch (error) {
|
|
239
|
+
// Registrars can run without Cordis in their module search path.
|
|
240
|
+
if (error.code === 'ERR_MODULE_NOT_FOUND')
|
|
241
|
+
return;
|
|
242
|
+
throw cordisInstanceMismatch(id);
|
|
243
|
+
}
|
|
244
|
+
const [pluginPath, hostPath] = await Promise.all([
|
|
245
|
+
realpath(fileURLToPath(pluginCordis)),
|
|
246
|
+
realpath(fileURLToPath(resolve(cordisPackage, import.meta.url))),
|
|
247
|
+
]).catch(() => {
|
|
248
|
+
throw cordisInstanceMismatch(id);
|
|
249
|
+
});
|
|
250
|
+
if (pluginPath !== hostPath)
|
|
251
|
+
throw cordisInstanceMismatch(id);
|
|
252
|
+
}
|
|
253
|
+
async function verifyCordisInstance(id, filename) {
|
|
254
|
+
try {
|
|
255
|
+
const pluginRequire = createRequire(filename);
|
|
256
|
+
const [pluginCordis, hostCordis] = await Promise.all([
|
|
257
|
+
realpath(pluginRequire.resolve(cordisPackage)),
|
|
258
|
+
realpath(hostRequire.resolve(cordisPackage)),
|
|
259
|
+
]);
|
|
260
|
+
if (pluginCordis === hostCordis && pluginRequire(pluginCordis).Context === Context)
|
|
261
|
+
return;
|
|
262
|
+
}
|
|
263
|
+
catch {
|
|
264
|
+
// Failure to resolve or read the constructor also prevents verifying shared identity.
|
|
265
|
+
}
|
|
266
|
+
throw cordisInstanceMismatch(id);
|
|
267
|
+
}
|
|
268
|
+
async function verifyPackageDependencies(id, filename, directoryManifest) {
|
|
269
|
+
let manifests;
|
|
270
|
+
try {
|
|
271
|
+
const scopeManifest = findPackageJSON(pathToFileURL(filename));
|
|
272
|
+
const files = new Set([directoryManifest, scopeManifest]);
|
|
273
|
+
manifests = await Promise.all([...files].filter((file) => file !== undefined).map(readManifest));
|
|
274
|
+
}
|
|
275
|
+
catch {
|
|
276
|
+
throw new RuntimeError('PLUGIN_PACKAGE_INVALID', `Could not read package metadata for plugin ${id}`);
|
|
277
|
+
}
|
|
278
|
+
for (const manifest of manifests) {
|
|
279
|
+
for (const field of ['dependencies', 'peerDependencies', 'optionalDependencies', 'devDependencies']) {
|
|
280
|
+
const dependencies = manifest?.[field];
|
|
281
|
+
if (!isRecord(dependencies))
|
|
282
|
+
continue;
|
|
283
|
+
for (const [name, version, code] of [
|
|
284
|
+
[sdkPackage, SATURN_PLUGIN_SDK_VERSION, 'PLUGIN_SDK_INCOMPATIBLE'],
|
|
285
|
+
[cordisPackage, SUPPORTED_CORDIS_VERSION, 'PLUGIN_CORDIS_INCOMPATIBLE'],
|
|
286
|
+
]) {
|
|
287
|
+
if (!Object.hasOwn(dependencies, name))
|
|
288
|
+
continue;
|
|
289
|
+
const range = dependencies[name];
|
|
290
|
+
if (typeof range !== 'string' || !semver.satisfies(version, range))
|
|
291
|
+
throw new RuntimeError(code, `Plugin ${id} must declare a ${name} range compatible with ${version}`);
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
async function readManifest(filename) {
|
|
297
|
+
try {
|
|
298
|
+
const manifest = JSON.parse(await readFile(filename, 'utf8'));
|
|
299
|
+
if (!isRecord(manifest))
|
|
300
|
+
throw new Error('Invalid package manifest');
|
|
301
|
+
return manifest;
|
|
302
|
+
}
|
|
303
|
+
catch (error) {
|
|
304
|
+
if (error.code !== 'ENOENT')
|
|
305
|
+
throw error;
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
function isRecord(value) {
|
|
309
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
310
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { Context } from '@deepseek-ai/cordis';
|
|
2
|
+
import type { SaturnCordisPluginV1, SaturnPluginV1 } from '@saturn-universe/plugin-sdk';
|
|
3
|
+
import type { PluginContributions } from './plugin-contributions.js';
|
|
4
|
+
export declare const HOST_PLUGIN_STARTUP_TIMEOUT_MS = 12000;
|
|
5
|
+
type PluginStartup = {
|
|
6
|
+
signal: AbortSignal;
|
|
7
|
+
interrupted: Promise<never>;
|
|
8
|
+
readonly ready: boolean;
|
|
9
|
+
contributions?: PluginContributions;
|
|
10
|
+
};
|
|
11
|
+
export declare function adaptSaturnPlugin<Config>(plugin: SaturnPluginV1<Config>, config: Config, contributions?: PluginContributions): {
|
|
12
|
+
name: string;
|
|
13
|
+
inject: string[];
|
|
14
|
+
apply(ctx: Context, hostStartupSignal?: AbortSignal): Promise<void>;
|
|
15
|
+
};
|
|
16
|
+
export declare function adaptCordisPlugin<Config>(descriptor: SaturnCordisPluginV1<Config>, config: Config, hostCordisContext: Context, startup?: PluginStartup): import("@deepseek-ai/cordis").Fiber & PromiseLike<import("@deepseek-ai/cordis").Fiber>;
|
|
17
|
+
export {};
|
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
import { Context, isConstructor, symbols } from '@deepseek-ai/cordis';
|
|
2
|
+
import { RuntimeError } from '@saturn-universe/core';
|
|
3
|
+
import { validatePluginCompatibility } from '@saturn-universe/plugin-sdk';
|
|
4
|
+
import { contributionScopeKey, globalScope, validateContributionScope } from './scoped-layers.js';
|
|
5
|
+
// Allow for slow Windows PATH scans within the CLI's 15-second Host readiness budget.
|
|
6
|
+
export const HOST_PLUGIN_STARTUP_TIMEOUT_MS = 12_000;
|
|
7
|
+
const reservedProviders = new Set(['core', 'tools', 'session']);
|
|
8
|
+
const hookNames = ['beforeModelRequest', 'evaluateToolPermission', 'formatToolResult'];
|
|
9
|
+
function requireCompatibility(plugin) {
|
|
10
|
+
const result = validatePluginCompatibility(plugin);
|
|
11
|
+
if (!result.ok)
|
|
12
|
+
throw new RuntimeError(result.error.code, result.error.message);
|
|
13
|
+
}
|
|
14
|
+
export function adaptSaturnPlugin(plugin, config, contributions) {
|
|
15
|
+
requireCompatibility(plugin);
|
|
16
|
+
const { id, version, setup } = plugin;
|
|
17
|
+
if (!id.trim() || id !== id.trim() || !version.trim() || version !== version.trim())
|
|
18
|
+
throw new RuntimeError('INVALID_PLUGIN_IDENTITY', 'Plugin ID and version must be nonempty and trimmed');
|
|
19
|
+
return {
|
|
20
|
+
name: `saturn-plugin:${id}`,
|
|
21
|
+
inject: ['saturnPluginHost', 'saturnTools', 'saturnModel', 'saturnContext', 'saturnHooks'],
|
|
22
|
+
async apply(ctx, hostStartupSignal) {
|
|
23
|
+
const standaloneStartup = new AbortController();
|
|
24
|
+
const startupSignal = hostStartupSignal ?? standaloneStartup.signal;
|
|
25
|
+
const { saturnPluginHost, saturnTools, saturnModel, saturnContext, saturnHooks } = ctx;
|
|
26
|
+
const { workspaceRoot, logger } = saturnPluginHost;
|
|
27
|
+
const cleanups = [];
|
|
28
|
+
let ready = false;
|
|
29
|
+
let disposal;
|
|
30
|
+
function dispose(rollback) {
|
|
31
|
+
// Cordis may dispose the fiber while apply() is unwinding from a startup timeout.
|
|
32
|
+
return (disposal ??= Promise.resolve().then(async () => {
|
|
33
|
+
for (const { stop, release } of cleanups.splice(0).reverse()) {
|
|
34
|
+
try {
|
|
35
|
+
await stop();
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
logger.error({ pluginId: id, code: 'PLUGIN_CLEANUP_FAILED' }, 'Plugin cleanup failed');
|
|
39
|
+
}
|
|
40
|
+
finally {
|
|
41
|
+
if (rollback)
|
|
42
|
+
release?.();
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
}));
|
|
46
|
+
}
|
|
47
|
+
// A single effect owns the stack so async cleanup finishes in reverse registration order.
|
|
48
|
+
ctx.effect(() => () => dispose(!ready || startupSignal.aborted), `saturn-plugin:${id}`);
|
|
49
|
+
function requireSetup() {
|
|
50
|
+
if (ready || disposal || startupSignal.aborted)
|
|
51
|
+
throw new RuntimeError('PLUGIN_REGISTRAR_CLOSED', `Plugin ${id} setup has ended`);
|
|
52
|
+
}
|
|
53
|
+
function track(stop, release) {
|
|
54
|
+
if (contributions)
|
|
55
|
+
return stop;
|
|
56
|
+
let active = true;
|
|
57
|
+
const deactivate = () => {
|
|
58
|
+
if (!active)
|
|
59
|
+
return;
|
|
60
|
+
active = false;
|
|
61
|
+
stop();
|
|
62
|
+
};
|
|
63
|
+
cleanups.push({ stop: deactivate, release });
|
|
64
|
+
return deactivate;
|
|
65
|
+
}
|
|
66
|
+
const timer = hostStartupSignal
|
|
67
|
+
? undefined
|
|
68
|
+
: setTimeout(() => {
|
|
69
|
+
standaloneStartup.abort(new RuntimeError('PLUGIN_SETUP_TIMEOUT', `Plugin ${id} setup timed out`));
|
|
70
|
+
}, HOST_PLUGIN_STARTUP_TIMEOUT_MS);
|
|
71
|
+
let abort;
|
|
72
|
+
const interrupted = new Promise((_, reject) => {
|
|
73
|
+
abort = () => reject(startupSignal.reason);
|
|
74
|
+
startupSignal.addEventListener('abort', abort, { once: true });
|
|
75
|
+
});
|
|
76
|
+
try {
|
|
77
|
+
startupSignal.throwIfAborted();
|
|
78
|
+
const versions = await Promise.race([saturnTools.pluginToolVersions(), interrupted]);
|
|
79
|
+
startupSignal.throwIfAborted();
|
|
80
|
+
const registrar = {
|
|
81
|
+
pluginId: id,
|
|
82
|
+
pluginVersion: version,
|
|
83
|
+
workspaceRoot,
|
|
84
|
+
logger: Object.freeze({
|
|
85
|
+
info: logger.info.bind(logger),
|
|
86
|
+
error: logger.error.bind(logger),
|
|
87
|
+
}),
|
|
88
|
+
registerTool(definition, handler, { scope = globalScope, ...options } = {}) {
|
|
89
|
+
requireSetup();
|
|
90
|
+
const snapshot = structuredClone(definition);
|
|
91
|
+
if (snapshot.source?.kind !== 'plugin' || snapshot.source.sourceId !== id)
|
|
92
|
+
throw new RuntimeError('INVALID_PLUGIN_TOOL_SOURCE', `Tool source must be plugin ${id}`);
|
|
93
|
+
const validated = validateContributionScope(scope);
|
|
94
|
+
return track(saturnTools.registerTool(snapshot, handler, versions, { ...options, scope: validated }), () => {
|
|
95
|
+
saturnTools.registry.release(snapshot.name, snapshot.version, contributionScopeKey(validated));
|
|
96
|
+
});
|
|
97
|
+
},
|
|
98
|
+
registerModelProfile(profile) {
|
|
99
|
+
requireSetup();
|
|
100
|
+
const snapshot = structuredClone(profile);
|
|
101
|
+
const ref = `${snapshot.id}@${snapshot.revision}`;
|
|
102
|
+
return track(saturnModel.registerProfile(snapshot), () => saturnModel.releaseProfile(ref));
|
|
103
|
+
},
|
|
104
|
+
registerContextProvider(provider, { scope = globalScope } = {}) {
|
|
105
|
+
requireSetup();
|
|
106
|
+
const { id, version, phase, priority, required, timeoutMs, collect } = provider;
|
|
107
|
+
if (reservedProviders.has(id))
|
|
108
|
+
throw new RuntimeError('RESERVED_CONTEXT_PROVIDER', `Context provider ${id} is reserved`);
|
|
109
|
+
const validated = validateContributionScope(scope);
|
|
110
|
+
return track(saturnContext.registerProvider({
|
|
111
|
+
id,
|
|
112
|
+
version,
|
|
113
|
+
phase,
|
|
114
|
+
priority,
|
|
115
|
+
required,
|
|
116
|
+
timeoutMs,
|
|
117
|
+
collect: collect.bind(provider),
|
|
118
|
+
}, { scope: validated }), () => {
|
|
119
|
+
saturnContext.releaseProvider(id, version, contributionScopeKey(validated));
|
|
120
|
+
});
|
|
121
|
+
},
|
|
122
|
+
registerHook(hook, { scope = globalScope } = {}) {
|
|
123
|
+
requireSetup();
|
|
124
|
+
const { id: localId, ...callbacks } = hook;
|
|
125
|
+
if (typeof localId !== 'string' ||
|
|
126
|
+
!/^[a-zA-Z0-9_-]{1,64}$/.test(localId) ||
|
|
127
|
+
!Reflect.ownKeys(callbacks).every((name) => hookNames.some((allowed) => name === allowed && typeof callbacks[allowed] === 'function')))
|
|
128
|
+
throw new RuntimeError('INVALID_PLUGIN_HOOK', 'A plugin hook requires a local ID and supported callbacks');
|
|
129
|
+
const validated = validateContributionScope(scope);
|
|
130
|
+
const scopeKey = contributionScopeKey(validated);
|
|
131
|
+
const binding = { id: `plugin:${encodeURIComponent(id)}:${localId}`, version };
|
|
132
|
+
return track(saturnHooks.register(binding, callbacks, { scope: validated }), () => {
|
|
133
|
+
saturnHooks.release({ ...binding, ...(scopeKey === undefined ? {} : { scopeKey }) });
|
|
134
|
+
});
|
|
135
|
+
},
|
|
136
|
+
onDispose(cleanup) {
|
|
137
|
+
requireSetup();
|
|
138
|
+
if (contributions)
|
|
139
|
+
contributions.onDispose(cleanup);
|
|
140
|
+
else
|
|
141
|
+
cleanups.push({ stop: cleanup });
|
|
142
|
+
},
|
|
143
|
+
};
|
|
144
|
+
// Keep the original enumerable registrar shape for plugins that inspect it.
|
|
145
|
+
for (const name of [
|
|
146
|
+
'registerSecret',
|
|
147
|
+
'redactValue',
|
|
148
|
+
'resolveWorkspaceAssignment',
|
|
149
|
+
'syncWorkspaceSubpaths',
|
|
150
|
+
]) {
|
|
151
|
+
if (saturnPluginHost[name])
|
|
152
|
+
Object.defineProperty(registrar, name, { value: saturnPluginHost[name] });
|
|
153
|
+
}
|
|
154
|
+
if (saturnPluginHost.resolveSessionPaths) {
|
|
155
|
+
const resolvePaths = saturnPluginHost.resolveSessionPaths;
|
|
156
|
+
Object.defineProperty(registrar, 'resolveSessionPaths', {
|
|
157
|
+
value: (sessionId) => resolvePaths(id, sessionId),
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
if (saturnPluginHost.onWorkerLifecycle) {
|
|
161
|
+
const subscribe = saturnPluginHost.onWorkerLifecycle;
|
|
162
|
+
Object.defineProperty(registrar, 'onWorkerLifecycle', {
|
|
163
|
+
value: (listener) => {
|
|
164
|
+
requireSetup();
|
|
165
|
+
const stop = subscribe(listener);
|
|
166
|
+
if (contributions)
|
|
167
|
+
contributions.onDispose(stop);
|
|
168
|
+
return track(stop, () => { });
|
|
169
|
+
},
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
if (saturnPluginHost.reportPluginStatus) {
|
|
173
|
+
const report = saturnPluginHost.reportPluginStatus;
|
|
174
|
+
Object.defineProperty(registrar, 'reportStatus', {
|
|
175
|
+
value: (status) => report(id, status),
|
|
176
|
+
});
|
|
177
|
+
if (contributions)
|
|
178
|
+
contributions.onDispose(() => report(id, undefined));
|
|
179
|
+
else
|
|
180
|
+
cleanups.push({ stop: () => report(id, undefined) });
|
|
181
|
+
}
|
|
182
|
+
const setupTask = Promise.resolve().then(() => {
|
|
183
|
+
startupSignal.throwIfAborted();
|
|
184
|
+
const apply = () => setup(Object.freeze(registrar), config);
|
|
185
|
+
return contributions ? contributions.setup(apply) : apply();
|
|
186
|
+
});
|
|
187
|
+
await Promise.race([setupTask, interrupted]);
|
|
188
|
+
startupSignal.throwIfAborted();
|
|
189
|
+
ready = true;
|
|
190
|
+
}
|
|
191
|
+
catch (error) {
|
|
192
|
+
await dispose(true);
|
|
193
|
+
throw error;
|
|
194
|
+
}
|
|
195
|
+
finally {
|
|
196
|
+
clearTimeout(timer);
|
|
197
|
+
startupSignal.removeEventListener('abort', abort);
|
|
198
|
+
}
|
|
199
|
+
},
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
export function adaptCordisPlugin(descriptor, config, hostCordisContext, startup) {
|
|
203
|
+
requireCompatibility({
|
|
204
|
+
...descriptor,
|
|
205
|
+
hostCordisContextClass: hostCordisContext.root instanceof Context ? Context : undefined,
|
|
206
|
+
});
|
|
207
|
+
// The SDK's structural entrypoint accepts a Cordis Context only after the identity check above.
|
|
208
|
+
const plugin = descriptor.plugin;
|
|
209
|
+
if (!startup)
|
|
210
|
+
return hostCordisContext.registry.plugin(plugin, config);
|
|
211
|
+
const callback = typeof plugin === 'function' ? plugin : plugin.apply;
|
|
212
|
+
return hostCordisContext.registry.plugin({
|
|
213
|
+
name: `cordis-plugin:${descriptor.id}`,
|
|
214
|
+
...(plugin.inject ? { inject: plugin.inject } : {}),
|
|
215
|
+
...(plugin.Config ? { Config: plugin.Config } : {}),
|
|
216
|
+
apply(ctx, config) {
|
|
217
|
+
startup.signal.throwIfAborted();
|
|
218
|
+
const inSetup = (execute) => startup.contributions ? startup.contributions.setup(execute) : execute();
|
|
219
|
+
// Cordis also waits for ctx.effect() initialization when disposing its owner.
|
|
220
|
+
const contextEffect = ctx.fiber.effect.bind(ctx.fiber);
|
|
221
|
+
Object.defineProperty(ctx, 'effect', {
|
|
222
|
+
configurable: true,
|
|
223
|
+
value: (execute, label) => contextEffect(() => interruptibleEffect(inSetup(execute), ctx, startup, inSetup), label),
|
|
224
|
+
});
|
|
225
|
+
// Preserve Cordis class initialization hooks while bounding asynchronous activation.
|
|
226
|
+
const apply = () => {
|
|
227
|
+
if (!isConstructor(callback))
|
|
228
|
+
return callback(ctx, config);
|
|
229
|
+
const instance = new callback(ctx, config);
|
|
230
|
+
for (const hook of instance?.[symbols.initHooks] ?? [])
|
|
231
|
+
hook();
|
|
232
|
+
return instance?.[symbols.init]?.();
|
|
233
|
+
};
|
|
234
|
+
return interruptibleEffect(inSetup(apply), ctx, startup, inSetup);
|
|
235
|
+
},
|
|
236
|
+
}, config);
|
|
237
|
+
}
|
|
238
|
+
function interruptibleEffect(effect, ctx, startup, inSetup) {
|
|
239
|
+
if (!effect || typeof effect === 'function')
|
|
240
|
+
return effect;
|
|
241
|
+
const cleanupLate = (cleanup) => {
|
|
242
|
+
if (!startup.signal.aborted || typeof cleanup !== 'function')
|
|
243
|
+
return cleanup;
|
|
244
|
+
void Promise.resolve()
|
|
245
|
+
.then(cleanup)
|
|
246
|
+
.catch((error) => ctx.logger.error(error));
|
|
247
|
+
};
|
|
248
|
+
if ('then' in effect) {
|
|
249
|
+
return startup.ready
|
|
250
|
+
? effect
|
|
251
|
+
: Promise.race([Promise.resolve(effect).then(cleanupLate), startup.interrupted]);
|
|
252
|
+
}
|
|
253
|
+
if (Symbol.iterator in effect) {
|
|
254
|
+
return {
|
|
255
|
+
[Symbol.iterator]() {
|
|
256
|
+
const iterator = inSetup(() => effect[Symbol.iterator]());
|
|
257
|
+
return { next: () => inSetup(() => iterator.next()) };
|
|
258
|
+
},
|
|
259
|
+
};
|
|
260
|
+
}
|
|
261
|
+
if (Symbol.asyncIterator in effect) {
|
|
262
|
+
const iterator = inSetup(() => effect[Symbol.asyncIterator]());
|
|
263
|
+
return (async function* () {
|
|
264
|
+
try {
|
|
265
|
+
for (;;) {
|
|
266
|
+
const next = inSetup(() => iterator.next()).then(({ done, value }) => ({
|
|
267
|
+
done,
|
|
268
|
+
value: cleanupLate(value),
|
|
269
|
+
}));
|
|
270
|
+
const { done, value } = await (startup.ready ? next : Promise.race([next, startup.interrupted]));
|
|
271
|
+
if (done)
|
|
272
|
+
return value;
|
|
273
|
+
yield value;
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
finally {
|
|
277
|
+
if (startup.signal.aborted)
|
|
278
|
+
void iterator.return?.().catch((error) => ctx.logger.error(error));
|
|
279
|
+
}
|
|
280
|
+
})();
|
|
281
|
+
}
|
|
282
|
+
return effect;
|
|
283
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { Context } from '@deepseek-ai/cordis';
|
|
2
|
+
import type { HookBinding, HookRegistry, RuntimeHooks } from '@saturn-universe/core';
|
|
3
|
+
import { ScopedVersions } from './scoped-layers.js';
|
|
4
|
+
import type { ContributionScope, ContributionTarget } from './scoped-layers.js';
|
|
5
|
+
interface RuntimeHookService extends HookRegistry {
|
|
6
|
+
register(binding: HookBinding, hooks: RuntimeHooks, options?: {
|
|
7
|
+
readonly active?: boolean;
|
|
8
|
+
readonly scope?: ContributionScope;
|
|
9
|
+
}): () => void;
|
|
10
|
+
list(target?: ContributionTarget): readonly HookBinding[];
|
|
11
|
+
agentSessionIds(): ReturnType<ScopedVersions<RuntimeHooks>['agentSessionIds']>;
|
|
12
|
+
forBindings(bindings: readonly HookBinding[], target?: ContributionTarget): RuntimeHooks;
|
|
13
|
+
}
|
|
14
|
+
declare module '@deepseek-ai/cordis' {
|
|
15
|
+
interface Context {
|
|
16
|
+
saturnHooks: RuntimeHookService;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
export declare const runtimeHooksPlugin: {
|
|
20
|
+
name: string;
|
|
21
|
+
apply(ctx: Context): void;
|
|
22
|
+
};
|
|
23
|
+
export {};
|