@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,289 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import { lstat, open, realpath } from 'node:fs/promises';
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
import { contextExtensionRefPattern, RuntimeError } from '@saturn-universe/core';
|
|
5
|
+
import { readFileWindow, relativePathWithin } from '@saturn-universe/tools';
|
|
6
|
+
import { configurationTable, pluginConfigSchema, pluginEntrySchema, pluginIdSchema, } from './plugin-configuration.js';
|
|
7
|
+
import { configuredPluginGrantFields, validConfiguredPluginGrant } from './plugin-tool-grants.js';
|
|
8
|
+
import { configuredRunBudgetShape, unlimitedInt } from './run-budget.js';
|
|
9
|
+
const maxFileBytes = 64 * 1024;
|
|
10
|
+
const maxSnapshotBytes = 256 * 1024;
|
|
11
|
+
const ref = z.string().regex(contextExtensionRefPattern);
|
|
12
|
+
const resourceName = z.string().min(1).max(1024);
|
|
13
|
+
const identifier = z.string().trim().min(1).max(200);
|
|
14
|
+
const toolNames = z
|
|
15
|
+
.array(z.string().min(1).max(128))
|
|
16
|
+
.max(256)
|
|
17
|
+
.refine((items) => new Set(items).size === items.length);
|
|
18
|
+
const promptOverrideSchema = z
|
|
19
|
+
.strictObject({
|
|
20
|
+
mode: z.enum(['append', 'replace']),
|
|
21
|
+
text: z.string().max(16384),
|
|
22
|
+
})
|
|
23
|
+
.refine((value) => value.mode === 'replace' || value.text.trim().length > 0);
|
|
24
|
+
const rolePromptSectionSchema = z
|
|
25
|
+
.strictObject({
|
|
26
|
+
id: identifier.optional(),
|
|
27
|
+
text: z.string().max(16384),
|
|
28
|
+
priority: z.number().int().min(-1000).max(1000).optional(),
|
|
29
|
+
required: z.boolean().optional(),
|
|
30
|
+
mode: z.enum(['append', 'replace']).optional(),
|
|
31
|
+
})
|
|
32
|
+
.refine((value) => (value.mode ?? 'append') === 'replace' || value.text.trim().length > 0);
|
|
33
|
+
const modePromptsSchema = z.strictObject({
|
|
34
|
+
instructions: z.string().trim().min(1).max(16384).optional(),
|
|
35
|
+
core: promptOverrideSchema.optional(),
|
|
36
|
+
execution_policy: promptOverrideSchema.optional(),
|
|
37
|
+
roles: z
|
|
38
|
+
.strictObject({
|
|
39
|
+
main: z.array(rolePromptSectionSchema).max(32).optional(),
|
|
40
|
+
planner: z.array(rolePromptSectionSchema).max(32).optional(),
|
|
41
|
+
worker: z.array(rolePromptSectionSchema).max(32).optional(),
|
|
42
|
+
})
|
|
43
|
+
.optional(),
|
|
44
|
+
});
|
|
45
|
+
const modeToolsSchema = z.strictObject({
|
|
46
|
+
workspace_tools: z.boolean().optional(),
|
|
47
|
+
process_manager: z.boolean().optional(),
|
|
48
|
+
builtin_agent_tools: z.boolean().optional(),
|
|
49
|
+
allowed_tools: toolNames.optional(),
|
|
50
|
+
denied_tools: toolNames.optional(),
|
|
51
|
+
permission_mode: z.enum(['strict', 'default', 'full']).optional(),
|
|
52
|
+
});
|
|
53
|
+
const modePluginEntrySchema = z
|
|
54
|
+
.strictObject({
|
|
55
|
+
enabled: z.boolean().optional(),
|
|
56
|
+
entry: pluginEntrySchema.optional(),
|
|
57
|
+
config: pluginConfigSchema.optional(),
|
|
58
|
+
...configuredPluginGrantFields(toolNames),
|
|
59
|
+
})
|
|
60
|
+
.partial({ allowed_tools: true })
|
|
61
|
+
.refine(validConfiguredPluginGrant);
|
|
62
|
+
const modePluginsSchema = z.union([
|
|
63
|
+
z.array(pluginIdSchema).max(64),
|
|
64
|
+
configurationTable(pluginIdSchema, modePluginEntrySchema),
|
|
65
|
+
]);
|
|
66
|
+
const sandboxReadonlyMountSchema = z.strictObject({
|
|
67
|
+
host_path: z
|
|
68
|
+
.string()
|
|
69
|
+
.trim()
|
|
70
|
+
.min(1)
|
|
71
|
+
.max(1024)
|
|
72
|
+
.refine((value) => !/[\0\r\n]/.test(value) && !value.split(/[\\/]/).includes('..')),
|
|
73
|
+
container_path: z
|
|
74
|
+
.string()
|
|
75
|
+
.trim()
|
|
76
|
+
.min(1)
|
|
77
|
+
.max(1024)
|
|
78
|
+
.refine((value) => !/[\0\r\n\\]/.test(value) &&
|
|
79
|
+
!value.split('/').includes('..') &&
|
|
80
|
+
path.posix.normalize(value).startsWith('/readonly/') &&
|
|
81
|
+
path.posix.normalize(value) !== '/readonly/'),
|
|
82
|
+
});
|
|
83
|
+
const sandboxResourcesSchema = z.strictObject({
|
|
84
|
+
cpus: z.number().positive().max(128).optional(),
|
|
85
|
+
memory_mb: z
|
|
86
|
+
.number()
|
|
87
|
+
.int()
|
|
88
|
+
.positive()
|
|
89
|
+
.max(1024 * 1024)
|
|
90
|
+
.optional(),
|
|
91
|
+
pids_limit: z.number().int().positive().max(100_000).optional(),
|
|
92
|
+
disk_soft_limit_mb: z
|
|
93
|
+
.number()
|
|
94
|
+
.int()
|
|
95
|
+
.positive()
|
|
96
|
+
.max(1024 * 1024)
|
|
97
|
+
.optional(),
|
|
98
|
+
});
|
|
99
|
+
const sandboxRetentionSchema = z.strictObject({
|
|
100
|
+
mode: z.enum(['always', 'on_success', 'ttl']),
|
|
101
|
+
ttl_hours: z
|
|
102
|
+
.number()
|
|
103
|
+
.positive()
|
|
104
|
+
.max(24 * 365)
|
|
105
|
+
.optional(),
|
|
106
|
+
});
|
|
107
|
+
export const modeSandboxSchema = z.strictObject({
|
|
108
|
+
backend: z.enum(['host', 'docker', 'gvisor', 'sysbox']).optional(),
|
|
109
|
+
scope: z.enum(['none', 'per_run_and_worker']).optional(),
|
|
110
|
+
image: z.string().trim().min(1).max(512).optional(),
|
|
111
|
+
network: z.enum(['none', 'internal', 'proxy', 'bridge']).optional(),
|
|
112
|
+
network_name: z.string().trim().min(1).max(128).optional(),
|
|
113
|
+
proxy_url: z.string().trim().min(1).max(1024).optional(),
|
|
114
|
+
cap_add: z
|
|
115
|
+
.array(z.string().regex(/^[A-Z0-9_]+$/))
|
|
116
|
+
.max(32)
|
|
117
|
+
.optional(),
|
|
118
|
+
readonly_mounts: z.array(sandboxReadonlyMountSchema).max(32).optional(),
|
|
119
|
+
kvm: z.boolean().optional(),
|
|
120
|
+
tmpfs_size_mb: z.number().int().positive().max(65536).optional(),
|
|
121
|
+
resources: sandboxResourcesSchema.optional(),
|
|
122
|
+
retention: sandboxRetentionSchema.optional(),
|
|
123
|
+
fallback_policy: z.enum(['fail_closed', 'allow_host_fallback']).optional(),
|
|
124
|
+
allow_target_services: z.boolean().optional(),
|
|
125
|
+
worker_allow_target_services: z.boolean().optional(),
|
|
126
|
+
max_targets_per_run: z.number().int().min(1).max(16).optional(),
|
|
127
|
+
max_concurrent_containers: z.number().int().min(1).max(64).optional(),
|
|
128
|
+
allowed_target_capabilities: z
|
|
129
|
+
.array(z.string().regex(/^[A-Z0-9_]+$/))
|
|
130
|
+
.max(16)
|
|
131
|
+
.optional(),
|
|
132
|
+
});
|
|
133
|
+
const modeTeamSchema = z.strictObject({
|
|
134
|
+
max_depth: z.number().int().min(1).max(2).optional(),
|
|
135
|
+
async_coordinator: z.boolean().optional(),
|
|
136
|
+
coordinator_poll_interval_ms: z.number().int().min(0).optional(),
|
|
137
|
+
});
|
|
138
|
+
const modeLimitsSchema = z.strictObject(configuredRunBudgetShape());
|
|
139
|
+
export const modeDefinitionSchema = z
|
|
140
|
+
.strictObject({
|
|
141
|
+
display_name: z.string().trim().min(1).max(200).optional(),
|
|
142
|
+
description: z.string().trim().min(1).max(1000).optional(),
|
|
143
|
+
instructions: z.string().trim().min(1).max(16384).optional(),
|
|
144
|
+
allowed_tools: toolNames.optional(),
|
|
145
|
+
denied_tools: toolNames.optional(),
|
|
146
|
+
prompts: modePromptsSchema.optional(),
|
|
147
|
+
tools: modeToolsSchema.optional(),
|
|
148
|
+
plugins: modePluginsSchema.optional(),
|
|
149
|
+
sandbox: modeSandboxSchema.optional(),
|
|
150
|
+
team: modeTeamSchema.optional(),
|
|
151
|
+
limits: modeLimitsSchema.optional(),
|
|
152
|
+
max_active_challenges: z.number().int().min(1).optional(),
|
|
153
|
+
max_helpers_per_challenge: z.number().int().min(0).optional(),
|
|
154
|
+
per_challenge_wall_time_ms: unlimitedInt().optional(),
|
|
155
|
+
worker_soft_checkpoint_ms: unlimitedInt().optional(),
|
|
156
|
+
board_port: z.number().int().min(0).max(65535).optional(),
|
|
157
|
+
board_token: z.string().min(1).optional(),
|
|
158
|
+
board_public_host: z.string().min(1).optional(),
|
|
159
|
+
coordinator_poll_interval_ms: z.number().int().min(0).optional(),
|
|
160
|
+
auto_submit: z.boolean().optional(),
|
|
161
|
+
max_remote_instances: z.number().int().min(1).max(16).optional(),
|
|
162
|
+
instance_cooldown_ms: z.number().int().min(0).optional(),
|
|
163
|
+
auto_stop_on_solve: z.boolean().optional(),
|
|
164
|
+
})
|
|
165
|
+
.refine((value) => !(value.allowed_tools !== undefined && value.tools?.allowed_tools !== undefined) &&
|
|
166
|
+
!(value.denied_tools !== undefined && value.tools?.denied_tools !== undefined) &&
|
|
167
|
+
!(value.instructions !== undefined && value.prompts?.instructions !== undefined));
|
|
168
|
+
export const modeDefinitionsSchema = z.record(ref, modeDefinitionSchema);
|
|
169
|
+
export const skillDefinitionsSchema = z.record(ref, z.strictObject({ path: resourceName, resources: z.array(resourceName).max(16).optional() }));
|
|
170
|
+
export async function freezeContextExtensions(root, mode, availableSkills, skillRefs = []) {
|
|
171
|
+
if (skillRefs.length > 16)
|
|
172
|
+
throw invalid();
|
|
173
|
+
const modeInstructions = mode.prompts?.instructions ?? '';
|
|
174
|
+
const { allowedTools, deniedTools } = mode.tools ?? {};
|
|
175
|
+
const hasFrozenMode = Boolean(modeInstructions.trim()) || allowedTools !== undefined || deniedTools !== undefined;
|
|
176
|
+
if (!hasFrozenMode && !skillRefs.length)
|
|
177
|
+
return {};
|
|
178
|
+
if (new Set(skillRefs.map((value) => value.split('@')[0])).size !== skillRefs.length)
|
|
179
|
+
throw invalid();
|
|
180
|
+
const skills = [];
|
|
181
|
+
let remaining = maxSnapshotBytes - Buffer.byteLength(modeInstructions);
|
|
182
|
+
for (const ref of skillRefs) {
|
|
183
|
+
const source = availableSkills?.[ref];
|
|
184
|
+
if (!source || path.basename(source.path) !== 'SKILL.md')
|
|
185
|
+
throw invalid();
|
|
186
|
+
const manifest = await resolveFile(root, root, source.path);
|
|
187
|
+
if (path.basename(manifest) !== 'SKILL.md')
|
|
188
|
+
throw invalid();
|
|
189
|
+
const instructions = skillInstructions(await readText(manifest, remaining));
|
|
190
|
+
remaining -= Buffer.byteLength(instructions);
|
|
191
|
+
const resources = [];
|
|
192
|
+
const seen = new Set([manifest]);
|
|
193
|
+
for (const name of source.resources ?? []) {
|
|
194
|
+
const file = await resolveFile(root, path.dirname(manifest), name);
|
|
195
|
+
if (seen.has(file))
|
|
196
|
+
throw invalid();
|
|
197
|
+
seen.add(file);
|
|
198
|
+
const text = await readText(file, remaining);
|
|
199
|
+
remaining -= Buffer.byteLength(text);
|
|
200
|
+
resources.push({ path: name, text });
|
|
201
|
+
}
|
|
202
|
+
skills.push({ ref, instructions, resources });
|
|
203
|
+
}
|
|
204
|
+
return {
|
|
205
|
+
contextExtensions: {
|
|
206
|
+
...(hasFrozenMode
|
|
207
|
+
? {
|
|
208
|
+
mode: {
|
|
209
|
+
ref: mode.ref,
|
|
210
|
+
instructions: modeInstructions,
|
|
211
|
+
...(allowedTools !== undefined ? { allowedTools: [...allowedTools] } : {}),
|
|
212
|
+
...(deniedTools !== undefined ? { deniedTools: [...deniedTools] } : {}),
|
|
213
|
+
},
|
|
214
|
+
}
|
|
215
|
+
: {}),
|
|
216
|
+
skills,
|
|
217
|
+
},
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
async function resolveFile(root, directory, supplied) {
|
|
221
|
+
try {
|
|
222
|
+
if (path.isAbsolute(supplied) || /[:\x00]/.test(supplied))
|
|
223
|
+
throw invalid();
|
|
224
|
+
const target = path.resolve(directory, supplied);
|
|
225
|
+
checkLocation(root, directory, target);
|
|
226
|
+
const resolved = await realpath(target);
|
|
227
|
+
checkLocation(root, directory, resolved);
|
|
228
|
+
const info = await lstat(resolved);
|
|
229
|
+
if (!info.isFile() || info.nlink !== 1)
|
|
230
|
+
throw invalid();
|
|
231
|
+
return resolved;
|
|
232
|
+
}
|
|
233
|
+
catch {
|
|
234
|
+
throw invalid();
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
function checkLocation(root, directory, resolved) {
|
|
238
|
+
if (!relativePathWithin(directory, resolved))
|
|
239
|
+
throw invalid();
|
|
240
|
+
const parts = path.relative(root, resolved).toLowerCase().split(path.sep);
|
|
241
|
+
if (parts[0] === '.saturn' && parts[1] === 'skills')
|
|
242
|
+
parts.splice(0, 2);
|
|
243
|
+
if (parts.some((part) => /^(\.saturn|\.env(?:\..*)?|\.git)$/.test(part)))
|
|
244
|
+
throw invalid();
|
|
245
|
+
if (process.platform === 'win32' &&
|
|
246
|
+
parts.some((part) => /[. ]$/.test(part) || /^(con|prn|aux|nul|com[1-9¹²³]|lpt[1-9¹²³])(?:\.|$)/.test(part)))
|
|
247
|
+
throw invalid();
|
|
248
|
+
}
|
|
249
|
+
function skillInstructions(manifest) {
|
|
250
|
+
const normalized = manifest.replace(/\r\n/g, '\n');
|
|
251
|
+
let body = normalized;
|
|
252
|
+
if (normalized.startsWith('---\n')) {
|
|
253
|
+
// Metadata and optional manifest keys are descriptive. Only the Markdown body supplies instructions.
|
|
254
|
+
const end = normalized.indexOf('\n---\n', 4);
|
|
255
|
+
if (end < 0)
|
|
256
|
+
throw invalid();
|
|
257
|
+
body = normalized.slice(end + 5);
|
|
258
|
+
}
|
|
259
|
+
if (!body.trim())
|
|
260
|
+
throw invalid();
|
|
261
|
+
return body.trim();
|
|
262
|
+
}
|
|
263
|
+
async function readText(file, remaining) {
|
|
264
|
+
try {
|
|
265
|
+
const handle = await open(file, 'r');
|
|
266
|
+
try {
|
|
267
|
+
const limit = Math.min(maxFileBytes, remaining);
|
|
268
|
+
const info = await handle.stat();
|
|
269
|
+
if (!info.isFile() || info.nlink !== 1 || info.size > limit)
|
|
270
|
+
throw invalid();
|
|
271
|
+
const data = await readFileWindow(handle, 0, limit + 1);
|
|
272
|
+
if (data.length > limit)
|
|
273
|
+
throw invalid();
|
|
274
|
+
const text = new TextDecoder('utf-8', { fatal: true }).decode(data);
|
|
275
|
+
if (text.includes('\0'))
|
|
276
|
+
throw invalid();
|
|
277
|
+
return text;
|
|
278
|
+
}
|
|
279
|
+
finally {
|
|
280
|
+
await handle.close();
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
catch {
|
|
284
|
+
throw invalid();
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
function invalid() {
|
|
288
|
+
return new RuntimeError('INVALID_CONFIG', 'Invalid Mode or Skill configuration');
|
|
289
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { Context } from '@deepseek-ai/cordis';
|
|
2
|
+
import type { AgentSessionId, ContextProvider, Hash, ModeDefinition } from '@saturn-universe/core';
|
|
3
|
+
import type { SkillRegistryService } from '../skills-runtime.js';
|
|
4
|
+
import type { ContributionScope, ContributionTarget } from './scoped-layers.js';
|
|
5
|
+
declare module '@deepseek-ai/cordis' {
|
|
6
|
+
interface Context {
|
|
7
|
+
saturnContext: ReturnType<typeof createContextService>;
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
export declare function createContextCorePlugin(hash: Hash, activeMode?: ModeDefinition, skillService?: SkillRegistryService): {
|
|
11
|
+
name: string;
|
|
12
|
+
inject: string[];
|
|
13
|
+
apply(ctx: Context): void;
|
|
14
|
+
};
|
|
15
|
+
declare function createContextService(ctx: Context, hash: Hash, activeMode?: ModeDefinition, skillService?: SkillRegistryService): {
|
|
16
|
+
composer: import("@saturn-universe/core").ContextComposer & {
|
|
17
|
+
assembleSideContext(input: import("@saturn-universe/core").ContextRequest, snapshot: import("@saturn-universe/core").ContextStateSnapshot, previous?: import("@saturn-universe/core").PersistedModelRequest): ReturnType<import("@saturn-universe/core").ContextComposer["assemble"]>;
|
|
18
|
+
};
|
|
19
|
+
registerProvider: {
|
|
20
|
+
(provider: ContextProvider, options: {
|
|
21
|
+
scope?: ContributionScope;
|
|
22
|
+
}): () => void;
|
|
23
|
+
(provider: ContextProvider): () => void;
|
|
24
|
+
};
|
|
25
|
+
listProviders: (target?: ContributionTarget) => ContextProvider[];
|
|
26
|
+
listBindings: (target?: ContributionTarget) => {
|
|
27
|
+
id: string;
|
|
28
|
+
version: string;
|
|
29
|
+
scopeKey?: string;
|
|
30
|
+
}[];
|
|
31
|
+
agentSessionIds: () => readonly AgentSessionId[];
|
|
32
|
+
resolveProvider: (id: string, version: string, scopeKey?: string) => ContextProvider;
|
|
33
|
+
releaseProvider: (id: string, version: string, scopeKey?: string) => boolean;
|
|
34
|
+
};
|
|
35
|
+
export {};
|
|
@@ -0,0 +1,296 @@
|
|
|
1
|
+
import { buildCoreSystemPrompt, buildExecutionPolicyPrompt, createBuiltinProviders, createContextComposer, createContextProviderRegistry, createHistoryBuilder, registerProviders, validateProvider, } from '@saturn-universe/context';
|
|
2
|
+
import { RuntimeError } from '@saturn-universe/core';
|
|
3
|
+
import { responsesCodecs } from '@saturn-universe/model';
|
|
4
|
+
import { formatCompactSkillIndex } from '@saturn-universe/protocol';
|
|
5
|
+
import { dataReviewToolSet } from '@saturn-universe/tools';
|
|
6
|
+
import { responsesTokenCounter } from '../token-estimator.js';
|
|
7
|
+
import { executionTarget, globalScope, mainTarget, ScopedVersions, validateContributionScope, } from './scoped-layers.js';
|
|
8
|
+
import { contributionScopeKey } from './scoped-layers.js';
|
|
9
|
+
import { registerPluginContribution, trackPluginWork } from './plugin-contributions.js';
|
|
10
|
+
import { teamHintSections } from './tools/builtin-agent-tools-plugin.js';
|
|
11
|
+
export function createContextCorePlugin(hash, activeMode, skillService) {
|
|
12
|
+
return {
|
|
13
|
+
name: 'context-core',
|
|
14
|
+
inject: ['saturnStorage', 'saturnEnvProbe', 'saturnTools', 'saturnModel', 'saturnHooks'],
|
|
15
|
+
apply(ctx) {
|
|
16
|
+
ctx.provide('saturnContext', createContextService(ctx, hash, activeMode, skillService));
|
|
17
|
+
},
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
function resolvePromptOverride(baseline, override) {
|
|
21
|
+
if (!override)
|
|
22
|
+
return baseline;
|
|
23
|
+
if (override.mode === 'replace')
|
|
24
|
+
return override.text;
|
|
25
|
+
return override.text.trim() ? `${baseline}\n\n${override.text}` : baseline;
|
|
26
|
+
}
|
|
27
|
+
function createContextService(ctx, hash, activeMode, skillService) {
|
|
28
|
+
const { saturnStorage: { store }, saturnEnvProbe, saturnTools, saturnModel, saturnHooks, } = ctx;
|
|
29
|
+
const global = createContextProviderRegistry();
|
|
30
|
+
const scoped = new ScopedVersions('Context provider', 'PROVIDER_CONFLICT');
|
|
31
|
+
const workspaceAssignmentCache = new Map();
|
|
32
|
+
let disposed = false;
|
|
33
|
+
ctx.effect(() => () => {
|
|
34
|
+
disposed = true;
|
|
35
|
+
scoped.clear();
|
|
36
|
+
workspaceAssignmentCache.clear();
|
|
37
|
+
});
|
|
38
|
+
const registerBuiltin = (provider) => ctx.effect(() => global.register(provider));
|
|
39
|
+
const register = (provider, scope) => {
|
|
40
|
+
if (disposed)
|
|
41
|
+
throw new RuntimeError('HOST_DISPOSED', 'Context providers are disposed');
|
|
42
|
+
const validated = validateContributionScope(scope);
|
|
43
|
+
const { id, version } = provider;
|
|
44
|
+
const scopeKey = contributionScopeKey(validated);
|
|
45
|
+
const binding = { id, version, ...(scopeKey === undefined ? {} : { scopeKey }) };
|
|
46
|
+
return registerPluginContribution({ kind: 'context', ...binding }, (managed) => {
|
|
47
|
+
const tracked = { ...provider, collect: trackPluginWork(provider.collect.bind(provider)) };
|
|
48
|
+
if (validated.kind === 'global') {
|
|
49
|
+
let stop = managed ? global.register(tracked) : registerBuiltin(tracked);
|
|
50
|
+
return {
|
|
51
|
+
deactivate: () => stop(),
|
|
52
|
+
activate: () => {
|
|
53
|
+
stop = global.activate(id, version);
|
|
54
|
+
},
|
|
55
|
+
release: () => {
|
|
56
|
+
global.release(id, version);
|
|
57
|
+
},
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
validateProvider(tracked);
|
|
61
|
+
const registration = scoped.register(binding, tracked, validated);
|
|
62
|
+
const deactivate = managed ? registration : ctx.effect(() => registration);
|
|
63
|
+
return { deactivate, activate: registration.activate, release: () => scoped.release(binding) };
|
|
64
|
+
});
|
|
65
|
+
};
|
|
66
|
+
const resolve = (binding) => binding.scopeKey === undefined
|
|
67
|
+
? global.resolve(binding.id, binding.version)
|
|
68
|
+
: scoped.resolve(binding).value;
|
|
69
|
+
const listBindings = (target = mainTarget) => {
|
|
70
|
+
const bindings = new Map(global.list().map(({ id, version }) => [id, { id, version }]));
|
|
71
|
+
for (const binding of scoped.list(target))
|
|
72
|
+
bindings.set(binding.id, binding);
|
|
73
|
+
return registerProviders([...bindings.values()].map(resolve)).map(({ id }) => ({ ...bindings.get(id) }));
|
|
74
|
+
};
|
|
75
|
+
const listProviders = (target) => listBindings(target).map(resolve);
|
|
76
|
+
const resolveProvider = (id, version, scopeKey) => resolve({ id, version, ...(scopeKey === undefined ? {} : { scopeKey }) });
|
|
77
|
+
const releaseProvider = (id, version, scopeKey) => scopeKey === undefined ? global.release(id, version) : scoped.release({ id, version, scopeKey });
|
|
78
|
+
const corePrompt = resolvePromptOverride(buildCoreSystemPrompt(), activeMode?.prompts?.core);
|
|
79
|
+
const executionPolicyPrompt = resolvePromptOverride(buildExecutionPolicyPrompt(), activeMode?.prompts?.executionPolicy);
|
|
80
|
+
for (const provider of createBuiltinProviders([], corePrompt, { executionPolicyPrompt })) {
|
|
81
|
+
if (provider.id === 'tools') {
|
|
82
|
+
registerBuiltin({
|
|
83
|
+
...provider,
|
|
84
|
+
async collect(input) {
|
|
85
|
+
const tools = await saturnTools.registry.specs(input.config);
|
|
86
|
+
return {
|
|
87
|
+
...(await provider.collect(input)),
|
|
88
|
+
prompt: teamHintSections(input.config.teamHint, tools),
|
|
89
|
+
tools,
|
|
90
|
+
};
|
|
91
|
+
},
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
else if (provider.id === 'core') {
|
|
95
|
+
registerBuiltin({
|
|
96
|
+
...provider,
|
|
97
|
+
async collect(input) {
|
|
98
|
+
const base = await provider.collect(input);
|
|
99
|
+
if (input.config.toolSetVersion === dataReviewToolSet)
|
|
100
|
+
return {
|
|
101
|
+
...base,
|
|
102
|
+
prompt: [
|
|
103
|
+
{
|
|
104
|
+
id: 'runtime',
|
|
105
|
+
source: 'core',
|
|
106
|
+
priority: 100,
|
|
107
|
+
authority: 'core',
|
|
108
|
+
required: true,
|
|
109
|
+
text: 'Review only inline numeric datasets. Use review_numeric_data with explicitly requested supported checks. Explain the selected transformations and any remaining failed checks.',
|
|
110
|
+
},
|
|
111
|
+
],
|
|
112
|
+
};
|
|
113
|
+
const prompt = [...base.prompt];
|
|
114
|
+
const visibleTools = await saturnTools.registry.specs(input.config);
|
|
115
|
+
const includeReadonlyCommands = visibleTools.some(({ canonicalName }) => canonicalName === 'run_readonly_command');
|
|
116
|
+
const targetServicesAvailable = visibleTools.some(({ canonicalName }) => canonicalName === 'sandbox_target_up');
|
|
117
|
+
const rawSandbox = ctx.get('saturnSandbox')?.getProbeContext(input.runId, input.agentSessionId);
|
|
118
|
+
const pluginHost = ctx.get('saturnPluginHost');
|
|
119
|
+
let workSubpath = rawSandbox?.workSubpath;
|
|
120
|
+
if (!workSubpath && input.agentSessionId && pluginHost?.resolveWorkspaceAssignment) {
|
|
121
|
+
const cacheKey = `${input.runId}:${input.agentSessionId}`;
|
|
122
|
+
if (workspaceAssignmentCache.has(cacheKey)) {
|
|
123
|
+
workSubpath = workspaceAssignmentCache.get(cacheKey) ?? undefined;
|
|
124
|
+
}
|
|
125
|
+
else {
|
|
126
|
+
try {
|
|
127
|
+
const assignment = await pluginHost.resolveWorkspaceAssignment({
|
|
128
|
+
runId: input.runId,
|
|
129
|
+
agentSessionId: input.agentSessionId,
|
|
130
|
+
});
|
|
131
|
+
const resolved = assignment?.role === 'worker' && assignment.workSubpath ? assignment.workSubpath : null;
|
|
132
|
+
if (workspaceAssignmentCache.size >= 512) {
|
|
133
|
+
const oldest = workspaceAssignmentCache.keys().next().value;
|
|
134
|
+
if (oldest !== undefined)
|
|
135
|
+
workspaceAssignmentCache.delete(oldest);
|
|
136
|
+
}
|
|
137
|
+
workspaceAssignmentCache.set(cacheKey, resolved);
|
|
138
|
+
if (resolved)
|
|
139
|
+
workSubpath = resolved;
|
|
140
|
+
}
|
|
141
|
+
catch {
|
|
142
|
+
// Partial unit-test stores may not have full membership/team state.
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
const sandbox = rawSandbox
|
|
147
|
+
? {
|
|
148
|
+
...rawSandbox,
|
|
149
|
+
...(targetServicesAvailable ? { targetServicesAvailable: true } : {}),
|
|
150
|
+
}
|
|
151
|
+
: undefined;
|
|
152
|
+
const envText = await saturnEnvProbe.getSessionEnvironmentContext(input.sessionId, {
|
|
153
|
+
includeReadonlyCommands,
|
|
154
|
+
mcpServers: saturnTools.mcpServers?.map(({ id, discovery, toolCount, error }) => ({
|
|
155
|
+
id,
|
|
156
|
+
discovery,
|
|
157
|
+
toolCount,
|
|
158
|
+
...(error ? { error } : {}),
|
|
159
|
+
})) ?? [],
|
|
160
|
+
...(sandbox ? { sandbox } : {}),
|
|
161
|
+
...(workSubpath ? { workSubpath } : {}),
|
|
162
|
+
});
|
|
163
|
+
prompt.push({
|
|
164
|
+
id: 'environment-context',
|
|
165
|
+
source: 'env-probe',
|
|
166
|
+
priority: 0,
|
|
167
|
+
authority: 'background',
|
|
168
|
+
required: true,
|
|
169
|
+
text: envText,
|
|
170
|
+
});
|
|
171
|
+
return { ...base, prompt };
|
|
172
|
+
},
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
else {
|
|
176
|
+
registerBuiltin(provider);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
if (activeMode?.prompts?.roles) {
|
|
180
|
+
const [modeName, modeVersion = '1'] = activeMode.ref.split('@');
|
|
181
|
+
for (const role of ['main', 'planner', 'worker']) {
|
|
182
|
+
const sections = (activeMode.prompts.roles[role] ?? []).filter((section) => section.text.trim().length > 0);
|
|
183
|
+
if (!sections.length)
|
|
184
|
+
continue;
|
|
185
|
+
const providerId = `mode:${modeName}:role:${role}`;
|
|
186
|
+
const roleScope = { kind: 'role', roles: [role] };
|
|
187
|
+
const scopeKey = contributionScopeKey(roleScope);
|
|
188
|
+
const roleProvider = {
|
|
189
|
+
id: providerId,
|
|
190
|
+
version: modeVersion,
|
|
191
|
+
phase: 'mode',
|
|
192
|
+
priority: 45,
|
|
193
|
+
required: true,
|
|
194
|
+
timeoutMs: 15_000,
|
|
195
|
+
async collect() {
|
|
196
|
+
return {
|
|
197
|
+
providerId,
|
|
198
|
+
version: modeVersion,
|
|
199
|
+
prompt: sections.map((section, index) => ({
|
|
200
|
+
id: section.id ?? `mode:${modeName}:${role}:${index}`,
|
|
201
|
+
source: `mode:${modeName}`,
|
|
202
|
+
priority: section.priority ?? 45,
|
|
203
|
+
authority: 'configured_instruction',
|
|
204
|
+
required: section.required ?? true,
|
|
205
|
+
text: section.text,
|
|
206
|
+
})),
|
|
207
|
+
background: [],
|
|
208
|
+
tools: [],
|
|
209
|
+
relevantTurnIds: [],
|
|
210
|
+
};
|
|
211
|
+
},
|
|
212
|
+
};
|
|
213
|
+
validateProvider(roleProvider);
|
|
214
|
+
ctx.effect(() => scoped.register({ id: providerId, version: modeVersion, ...(scopeKey === undefined ? {} : { scopeKey }) }, roleProvider, roleScope));
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
if (skillService && skillService.indexSkills().length > 0) {
|
|
218
|
+
registerBuiltin({
|
|
219
|
+
id: 'skills-index',
|
|
220
|
+
version: '1',
|
|
221
|
+
phase: 'extensions',
|
|
222
|
+
priority: 20,
|
|
223
|
+
required: false,
|
|
224
|
+
timeoutMs: 15_000,
|
|
225
|
+
async collect(input) {
|
|
226
|
+
if (input.config.toolSetVersion === dataReviewToolSet) {
|
|
227
|
+
return {
|
|
228
|
+
providerId: 'skills-index',
|
|
229
|
+
version: '1',
|
|
230
|
+
prompt: [],
|
|
231
|
+
background: [],
|
|
232
|
+
tools: [],
|
|
233
|
+
relevantTurnIds: [],
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
const indexText = formatCompactSkillIndex(skillService.indexSkills(input.config.disabledSkills));
|
|
237
|
+
return {
|
|
238
|
+
providerId: 'skills-index',
|
|
239
|
+
version: '1',
|
|
240
|
+
prompt: indexText
|
|
241
|
+
? [
|
|
242
|
+
{
|
|
243
|
+
id: 'skills-index',
|
|
244
|
+
source: 'skills',
|
|
245
|
+
priority: 20,
|
|
246
|
+
authority: 'configured_instruction',
|
|
247
|
+
required: false,
|
|
248
|
+
text: indexText,
|
|
249
|
+
},
|
|
250
|
+
]
|
|
251
|
+
: [],
|
|
252
|
+
background: [],
|
|
253
|
+
tools: [],
|
|
254
|
+
relevantTurnIds: [],
|
|
255
|
+
};
|
|
256
|
+
},
|
|
257
|
+
});
|
|
258
|
+
}
|
|
259
|
+
const target = async ({ runId, agentSessionId }) => executionTarget(await store.environmentReader.load(runId, agentSessionId));
|
|
260
|
+
function registerProvider(provider, { scope = globalScope } = {}) {
|
|
261
|
+
if (provider.id === 'core' || provider.id === 'tools' || provider.id === 'session')
|
|
262
|
+
throw new RuntimeError('RESERVED_CONTEXT_PROVIDER', `Context provider ${provider.id} is reserved`);
|
|
263
|
+
return register(provider, scope);
|
|
264
|
+
}
|
|
265
|
+
const composer = createContextComposer({
|
|
266
|
+
reader: store.contextReader,
|
|
267
|
+
describe: saturnModel.gateway,
|
|
268
|
+
async hooks(config, input) {
|
|
269
|
+
const bindings = config.pluginBindings?.hooks ?? [];
|
|
270
|
+
return bindings.length ? saturnHooks.forBindings(bindings, await target(input)) : {};
|
|
271
|
+
},
|
|
272
|
+
listProviders: async (input) => listProviders(await target(input)),
|
|
273
|
+
hash,
|
|
274
|
+
builder: createHistoryBuilder({
|
|
275
|
+
hash,
|
|
276
|
+
codecs: responsesCodecs,
|
|
277
|
+
artifactReader: store.artifactStore,
|
|
278
|
+
counter: responsesTokenCounter,
|
|
279
|
+
}),
|
|
280
|
+
providerRegistry: {
|
|
281
|
+
register: registerProvider,
|
|
282
|
+
list: listProviders,
|
|
283
|
+
resolve: resolveProvider,
|
|
284
|
+
release: releaseProvider,
|
|
285
|
+
},
|
|
286
|
+
});
|
|
287
|
+
return {
|
|
288
|
+
composer,
|
|
289
|
+
registerProvider,
|
|
290
|
+
listProviders,
|
|
291
|
+
listBindings,
|
|
292
|
+
agentSessionIds: () => scoped.agentSessionIds(),
|
|
293
|
+
resolveProvider,
|
|
294
|
+
releaseProvider,
|
|
295
|
+
};
|
|
296
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { Context } from '@deepseek-ai/cordis';
|
|
2
|
+
import type { HostEnvironmentInfo } from '@saturn-universe/context';
|
|
3
|
+
import { collectWorkspaceSnapshot, probeHostEnvironment } from '../env-probe.js';
|
|
4
|
+
export interface SessionEnvironmentContextOptions {
|
|
5
|
+
readonly includeReadonlyCommands?: boolean;
|
|
6
|
+
readonly sandbox?: HostEnvironmentInfo['sandbox'];
|
|
7
|
+
readonly mcpServers?: HostEnvironmentInfo['mcpServers'];
|
|
8
|
+
readonly workSubpath?: string;
|
|
9
|
+
}
|
|
10
|
+
interface EnvProbeService {
|
|
11
|
+
readonly staticEnvInfo: Omit<HostEnvironmentInfo, 'workspaceEntries' | 'gitBranch'>;
|
|
12
|
+
getSessionEnvironmentContext(sessionId: string, options?: SessionEnvironmentContextOptions): Promise<string>;
|
|
13
|
+
}
|
|
14
|
+
declare module '@deepseek-ai/cordis' {
|
|
15
|
+
interface Context {
|
|
16
|
+
saturnEnvProbe: EnvProbeService;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
export interface EnvProbeDependencies {
|
|
20
|
+
probeHostEnvironment: typeof probeHostEnvironment;
|
|
21
|
+
collectWorkspaceSnapshot: typeof collectWorkspaceSnapshot;
|
|
22
|
+
}
|
|
23
|
+
export declare function createEnvProbePlugin(root: string, { probeHostEnvironment: probe, collectWorkspaceSnapshot: collect, }?: Partial<EnvProbeDependencies>): {
|
|
24
|
+
name: string;
|
|
25
|
+
apply(ctx: Context, startupSignal: AbortSignal): Promise<void>;
|
|
26
|
+
};
|
|
27
|
+
export {};
|