@saturn-universe/tools 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/container-sandbox.d.ts +168 -0
- package/dist/container-sandbox.js +1241 -0
- package/dist/counter.d.ts +5 -0
- package/dist/counter.js +82 -0
- package/dist/data-review.d.ts +4 -0
- package/dist/data-review.js +146 -0
- package/dist/execution-backend.d.ts +55 -0
- package/dist/execution-backend.js +339 -0
- package/dist/executor.d.ts +25 -0
- package/dist/executor.js +978 -0
- package/dist/file-window.d.ts +3 -0
- package/dist/file-window.js +12 -0
- package/dist/index.d.ts +27 -0
- package/dist/index.js +17 -0
- package/dist/mcp-headers.d.ts +3 -0
- package/dist/mcp-headers.js +51 -0
- package/dist/mcp-http.d.ts +3 -0
- package/dist/mcp-http.js +253 -0
- package/dist/mcp-stdio.d.ts +2 -0
- package/dist/mcp-stdio.js +147 -0
- package/dist/mcp-wire.d.ts +33 -0
- package/dist/mcp-wire.js +85 -0
- package/dist/mcp.d.ts +19 -0
- package/dist/mcp.js +325 -0
- package/dist/path-containment.d.ts +3 -0
- package/dist/path-containment.js +11 -0
- package/dist/planner.d.ts +3 -0
- package/dist/planner.js +162 -0
- package/dist/process-manager.d.ts +67 -0
- package/dist/process-manager.js +423 -0
- package/dist/process-output.d.ts +34 -0
- package/dist/process-output.js +162 -0
- package/dist/process-worker.d.ts +1 -0
- package/dist/process-worker.js +202 -0
- package/dist/registry.d.ts +33 -0
- package/dist/registry.js +227 -0
- package/dist/search.d.ts +9 -0
- package/dist/search.js +96 -0
- package/dist/team.d.ts +36 -0
- package/dist/team.js +284 -0
- package/dist/text-patch.d.ts +15 -0
- package/dist/text-patch.js +81 -0
- package/dist/todo.d.ts +3 -0
- package/dist/todo.js +105 -0
- package/dist/workspace-discovery.d.ts +42 -0
- package/dist/workspace-discovery.js +404 -0
- package/dist/workspace-snapshot.d.ts +28 -0
- package/dist/workspace-snapshot.js +371 -0
- package/dist/workspace.d.ts +22 -0
- package/dist/workspace.js +1819 -0
- package/package.json +16 -3
- package/README.md +0 -3
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
// Kept as a self-contained Node program so the same supervisor runs from source
|
|
2
|
+
// tests and packaged builds, without a loader or another installed dependency.
|
|
3
|
+
export const processWorkerSource = String.raw `
|
|
4
|
+
const fs = require('node:fs');
|
|
5
|
+
const net = require('node:net');
|
|
6
|
+
const path = require('node:path');
|
|
7
|
+
const { spawn } = require('node:child_process');
|
|
8
|
+
const filename = process.argv[1];
|
|
9
|
+
const record = JSON.parse(fs.readFileSync(filename, 'utf8'));
|
|
10
|
+
const limit = 256 * 1024;
|
|
11
|
+
let stdout = Buffer.alloc(0), stderr = Buffer.alloc(0);
|
|
12
|
+
let stdoutOffset = 0, stderrOffset = 0;
|
|
13
|
+
let child, stopping, timer, finished = false;
|
|
14
|
+
const sockets = new Set();
|
|
15
|
+
const appliedWrites = new Map();
|
|
16
|
+
function persist() {
|
|
17
|
+
record.stdout = stdout.toString('base64'); record.stderr = stderr.toString('base64');
|
|
18
|
+
record.stdoutOffset = stdoutOffset; record.stderrOffset = stderrOffset;
|
|
19
|
+
record.updatedAt = Date.now();
|
|
20
|
+
const temporary = filename + '.' + process.pid + '.tmp';
|
|
21
|
+
fs.writeFileSync(temporary, JSON.stringify(record), { mode: 0o600 });
|
|
22
|
+
fs.renameSync(temporary, filename);
|
|
23
|
+
}
|
|
24
|
+
function collect(stream, chunk) {
|
|
25
|
+
if (stream === 'stdout') {
|
|
26
|
+
stdout = Buffer.concat([stdout, chunk]);
|
|
27
|
+
if (stdout.length > limit) { stdoutOffset += stdout.length - limit; stdout = stdout.subarray(-limit); }
|
|
28
|
+
} else {
|
|
29
|
+
stderr = Buffer.concat([stderr, chunk]);
|
|
30
|
+
if (stderr.length > limit) { stderrOffset += stderr.length - limit; stderr = stderr.subarray(-limit); }
|
|
31
|
+
}
|
|
32
|
+
persist();
|
|
33
|
+
}
|
|
34
|
+
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
|
|
35
|
+
function groupAlive() {
|
|
36
|
+
try { process.kill(-child.pid, 0); return true; } catch (error) { return error.code !== 'ESRCH'; }
|
|
37
|
+
}
|
|
38
|
+
function runStopCommand(cmd) {
|
|
39
|
+
const timeoutMs = cmd.timeoutMs || 6000;
|
|
40
|
+
return new Promise(resolve => {
|
|
41
|
+
let settled = false;
|
|
42
|
+
let helper;
|
|
43
|
+
try {
|
|
44
|
+
helper = spawn(cmd.program, [...(cmd.args || [])], {
|
|
45
|
+
cwd: cmd.cwd || process.cwd(),
|
|
46
|
+
env: cmd.env || record.env,
|
|
47
|
+
shell: false,
|
|
48
|
+
windowsHide: true,
|
|
49
|
+
stdio: ['ignore', 'ignore', 'pipe'],
|
|
50
|
+
});
|
|
51
|
+
} catch {
|
|
52
|
+
resolve(false);
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
const errChunks = [];
|
|
56
|
+
let errBytes = 0;
|
|
57
|
+
const finish = ok => {
|
|
58
|
+
if (settled) return;
|
|
59
|
+
settled = true;
|
|
60
|
+
clearTimeout(stopTimer);
|
|
61
|
+
resolve(ok);
|
|
62
|
+
};
|
|
63
|
+
const stopTimer = setTimeout(() => {
|
|
64
|
+
try { helper.kill('SIGKILL'); } catch {}
|
|
65
|
+
finish(false);
|
|
66
|
+
}, timeoutMs);
|
|
67
|
+
if (helper.stderr) {
|
|
68
|
+
helper.stderr.on('data', chunk => {
|
|
69
|
+
if (errBytes < 4096) {
|
|
70
|
+
const slice = chunk.subarray(0, 4096 - errBytes);
|
|
71
|
+
errChunks.push(slice);
|
|
72
|
+
errBytes += slice.length;
|
|
73
|
+
}
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
helper.once('error', () => finish(false));
|
|
77
|
+
helper.once('close', code => {
|
|
78
|
+
const stderr = Buffer.concat(errChunks).toString('utf8');
|
|
79
|
+
finish(code === 0 || /no such container|is not running/i.test(stderr));
|
|
80
|
+
});
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
async function stop(reason) {
|
|
84
|
+
if (stopping) return stopping;
|
|
85
|
+
if (finished) return record;
|
|
86
|
+
stopping = (async () => {
|
|
87
|
+
record.stopReason = reason;
|
|
88
|
+
let stopCommandConfirmed = true;
|
|
89
|
+
if (record.stopCommand) {
|
|
90
|
+
stopCommandConfirmed = await runStopCommand(record.stopCommand);
|
|
91
|
+
for (let i = 0; i < 15 && child.exitCode === null && child.signalCode === null; i++) await sleep(20);
|
|
92
|
+
}
|
|
93
|
+
let confirmed = false;
|
|
94
|
+
if (process.platform === 'win32') {
|
|
95
|
+
if (child.exitCode !== null || child.signalCode !== null) {
|
|
96
|
+
confirmed = true;
|
|
97
|
+
} else {
|
|
98
|
+
// taskkill owns Windows descendants. It cannot prove termination inside WSL.
|
|
99
|
+
confirmed = await new Promise(resolve => {
|
|
100
|
+
const killer = spawn(path.join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'taskkill.exe'), ['/PID', String(child.pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore' });
|
|
101
|
+
const timeout = setTimeout(() => { killer.kill(); resolve(false); }, 3000);
|
|
102
|
+
killer.once('error', () => { clearTimeout(timeout); resolve(false); });
|
|
103
|
+
killer.once('close', code => { clearTimeout(timeout); resolve(code === 0); });
|
|
104
|
+
});
|
|
105
|
+
if (!record.stopCommand && path.basename(record.program).toLowerCase() === 'wsl.exe') confirmed = false;
|
|
106
|
+
if (!confirmed && child.exitCode === null && child.signalCode === null) child.kill('SIGKILL');
|
|
107
|
+
}
|
|
108
|
+
} else {
|
|
109
|
+
if ((child.exitCode === null && child.signalCode === null) || groupAlive()) {
|
|
110
|
+
try { process.kill(-child.pid, 'SIGKILL'); } catch (error) { if (error.code !== 'ESRCH') record.stopError = error.message; }
|
|
111
|
+
for (let i = 0; i < 40 && groupAlive(); i++) await sleep(20);
|
|
112
|
+
}
|
|
113
|
+
confirmed = !groupAlive();
|
|
114
|
+
}
|
|
115
|
+
for (let i = 0; i < 20 && child.exitCode === null && child.signalCode === null; i++) await sleep(10);
|
|
116
|
+
confirmed = stopCommandConfirmed && confirmed && (child.exitCode !== null || child.signalCode !== null);
|
|
117
|
+
record.status = confirmed ? 'exited' : 'unknown';
|
|
118
|
+
record.terminationConfirmed = confirmed;
|
|
119
|
+
record.exitCode = child.exitCode; record.signal = child.signalCode;
|
|
120
|
+
finished = true; clearTimeout(timer);
|
|
121
|
+
// A descendant can keep inherited pipes open; this must not claim it exited.
|
|
122
|
+
child.stdout.destroy(); child.stderr.destroy(); child.stdin.destroy();
|
|
123
|
+
persist();
|
|
124
|
+
setTimeout(shutdown, 100);
|
|
125
|
+
return record;
|
|
126
|
+
})();
|
|
127
|
+
return stopping;
|
|
128
|
+
}
|
|
129
|
+
function shutdown() { for (const socket of sockets) socket.end(); server.close(); }
|
|
130
|
+
const server = net.createServer(socket => {
|
|
131
|
+
socket.setEncoding('utf8');
|
|
132
|
+
sockets.add(socket); socket.on('close', () => sockets.delete(socket));
|
|
133
|
+
socket.setTimeout(5000, () => socket.destroy());
|
|
134
|
+
let data = '';
|
|
135
|
+
socket.on('data', chunk => {
|
|
136
|
+
data += chunk.toString('utf8');
|
|
137
|
+
if (Buffer.byteLength(data) > 96 * 1024) { socket.destroy(); return; }
|
|
138
|
+
if (!data.includes('\n')) return;
|
|
139
|
+
socket.pause();
|
|
140
|
+
(async () => {
|
|
141
|
+
const request = JSON.parse(data.slice(0, data.indexOf('\n')));
|
|
142
|
+
if (request.token !== record.token || request.processId !== record.processId) { socket.destroy(); return; }
|
|
143
|
+
if (request.action === 'stop') { socket.setTimeout(0); await stop('requested'); }
|
|
144
|
+
else if (request.action === 'write') {
|
|
145
|
+
const fingerprint = JSON.stringify([request.input, request.eof]);
|
|
146
|
+
const prior = appliedWrites.get(request.executionKey);
|
|
147
|
+
if (prior && prior.fingerprint !== fingerprint) throw new Error('Execution key input changed');
|
|
148
|
+
if (prior) await prior.operation;
|
|
149
|
+
else {
|
|
150
|
+
if (appliedWrites.size >= 2048) throw new Error('Process input operation limit reached');
|
|
151
|
+
if (finished || child.stdin.destroyed || child.stdin.writableEnded) throw new Error('Process stdin is closed');
|
|
152
|
+
// Reserve before awaiting a stream callback: concurrent retries share it.
|
|
153
|
+
const operation = (async () => {
|
|
154
|
+
if (request.input) await new Promise((resolve, reject) => child.stdin.write(request.input, error => error ? reject(error) : resolve()));
|
|
155
|
+
if (request.eof) child.stdin.end();
|
|
156
|
+
})();
|
|
157
|
+
appliedWrites.set(request.executionKey, { fingerprint, operation });
|
|
158
|
+
await operation;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
// Reads observe the state already persisted by lifecycle/output events.
|
|
162
|
+
// Avoid blocking the supervisor on redundant synchronous disk writes.
|
|
163
|
+
if (request.action !== 'read') persist();
|
|
164
|
+
socket.end(JSON.stringify({ token: record.token, record }) + '\n');
|
|
165
|
+
})().catch(error => socket.end(JSON.stringify({ token: record.token, error: error.message }) + '\n'));
|
|
166
|
+
});
|
|
167
|
+
});
|
|
168
|
+
server.on('error', () => process.exit(1));
|
|
169
|
+
const emergencyStop = () => { if (child) void stop('supervisor-shutdown').finally(() => process.exit(1)); else process.exit(1); };
|
|
170
|
+
process.on('SIGTERM', emergencyStop);
|
|
171
|
+
process.on('SIGINT', emergencyStop);
|
|
172
|
+
process.on('uncaughtException', emergencyStop);
|
|
173
|
+
server.listen(0, '127.0.0.1', () => {
|
|
174
|
+
record.port = server.address().port;
|
|
175
|
+
record.supervisorPid = process.pid;
|
|
176
|
+
try {
|
|
177
|
+
child = spawn(record.program, record.args, { cwd: record.cwd, env: record.env, shell: false, windowsHide: true, detached: process.platform !== 'win32', stdio: ['pipe', 'pipe', 'pipe'] });
|
|
178
|
+
} catch (error) {
|
|
179
|
+
record.status = 'exited'; record.startError = error.message; record.terminationConfirmed = true; persist(); shutdown(); return;
|
|
180
|
+
}
|
|
181
|
+
child.stdin.on('error', () => {});
|
|
182
|
+
child.stdout.on('data', chunk => collect('stdout', chunk));
|
|
183
|
+
child.stderr.on('data', chunk => collect('stderr', chunk));
|
|
184
|
+
child.once('spawn', () => { record.pid = child.pid; record.status = 'running'; persist(); });
|
|
185
|
+
child.once('error', error => { record.status = 'exited'; record.startError = error.message; record.terminationConfirmed = true; finished = true; clearTimeout(timer); persist(); shutdown(); });
|
|
186
|
+
child.once('close', (code, signal) => {
|
|
187
|
+
if (stopping || finished) return;
|
|
188
|
+
if (process.platform !== 'win32' && groupAlive()) {
|
|
189
|
+
// A direct child may leave same-group descendants with closed pipes.
|
|
190
|
+
// Retain ownership and the hard deadline until that group is stopped.
|
|
191
|
+
record.exitCode = code; record.signal = signal; record.directExited = true;
|
|
192
|
+
persist(); return;
|
|
193
|
+
}
|
|
194
|
+
record.status = 'exited'; record.exitCode = code; record.signal = signal;
|
|
195
|
+
// Normal completion proves the direct process exited, not detached grandchildren.
|
|
196
|
+
record.terminationConfirmed = false;
|
|
197
|
+
finished = true; clearTimeout(timer); persist(); setTimeout(shutdown, 100);
|
|
198
|
+
});
|
|
199
|
+
persist();
|
|
200
|
+
timer = setTimeout(() => void stop('deadline'), Math.max(1, record.deadlineAt - Date.now()));
|
|
201
|
+
});
|
|
202
|
+
`;
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { Hash, ToolRegistry, ToolBinding, ToolDefinition, ToolHandler, ToolRegistrationOptions, RunConfig, RunToolBinding, ToolSpec, JsonValue } from '@saturn-universe/core';
|
|
2
|
+
type ToolRef = Pick<ToolDefinition, 'version' | 'scopeKey'>;
|
|
3
|
+
export declare class Registry implements ToolRegistry {
|
|
4
|
+
readonly version: string;
|
|
5
|
+
private readonly versions;
|
|
6
|
+
private readonly hash;
|
|
7
|
+
private readonly bindings;
|
|
8
|
+
constructor(version?: string, versions?: readonly string[], hash?: Hash);
|
|
9
|
+
register(definition: ToolDefinition, handler: ToolHandler, versions?: readonly string[], { order }?: ToolRegistrationOptions): () => void;
|
|
10
|
+
deactivate(name: string, version: string, scopeKey?: string): void;
|
|
11
|
+
activate(name: string, version: string, scopeKey?: string): void;
|
|
12
|
+
isActive(name: string, version: string, scopeKey?: string): boolean;
|
|
13
|
+
release(name: string, version: string, scopeKey?: string): boolean;
|
|
14
|
+
snapshot(config: RunConfig): Promise<import("@saturn-universe/core").ToolSnapshot>;
|
|
15
|
+
snapshotForAdmission(config: RunConfig, overrides?: ReadonlyMap<string, ToolRef>, omitInactive?: (definition: ToolDefinition) => boolean): {
|
|
16
|
+
version: string;
|
|
17
|
+
definitions: ToolDefinition[];
|
|
18
|
+
};
|
|
19
|
+
private select;
|
|
20
|
+
pin(definition: ToolDefinition): RunToolBinding;
|
|
21
|
+
verifyBound(config: RunConfig): Promise<void>;
|
|
22
|
+
resolveFrozen(definition: ToolDefinition): Promise<ToolBinding>;
|
|
23
|
+
private resolvePinned;
|
|
24
|
+
private resolveAvailable;
|
|
25
|
+
private unavailable;
|
|
26
|
+
resolve(name: string, version: string, scopeKey?: string): Promise<ToolBinding>;
|
|
27
|
+
validateInput(name: string, version: string, value: JsonValue, scopeKey?: string): boolean;
|
|
28
|
+
describeInvalidInput(name: string, version: string, value: JsonValue, scopeKey?: string): string | undefined;
|
|
29
|
+
validateOutput(name: string, version: string, value: JsonValue): boolean;
|
|
30
|
+
specs(config: RunConfig): Promise<readonly ToolSpec[]>;
|
|
31
|
+
private requireBinding;
|
|
32
|
+
}
|
|
33
|
+
export {};
|
package/dist/registry.js
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { canonicalJson, RuntimeError, toolAbortGraceIssue } from '@saturn-universe/core';
|
|
4
|
+
const toolTiers = { shared: 0, 'team-variant': 1, tail: 2 };
|
|
5
|
+
const keyOf = (name, version, scopeKey) => JSON.stringify([name, version, scopeKey]);
|
|
6
|
+
export class Registry {
|
|
7
|
+
version;
|
|
8
|
+
versions;
|
|
9
|
+
hash;
|
|
10
|
+
bindings = new Map();
|
|
11
|
+
constructor(version = '1', versions = [version], hash = (value) => createHash('sha256').update(canonicalJson(value)).digest('hex')) {
|
|
12
|
+
this.version = version;
|
|
13
|
+
this.versions = versions;
|
|
14
|
+
this.hash = hash;
|
|
15
|
+
}
|
|
16
|
+
register(definition, handler, versions = this.versions, { order } = {}) {
|
|
17
|
+
const key = keyOf(definition.name, definition.version, definition.scopeKey);
|
|
18
|
+
if (this.bindings.has(key) ||
|
|
19
|
+
!definition.name.match(/^[a-zA-Z0-9_-]{1,64}$/) ||
|
|
20
|
+
definition.timeoutMs < 1 ||
|
|
21
|
+
toolAbortGraceIssue(definition.abortGraceMs) !== undefined ||
|
|
22
|
+
(order && (!Object.hasOwn(toolTiers, order.tier) || !Number.isFinite(order.priority ?? 0))) ||
|
|
23
|
+
(definition.effects === 'non_idempotent_write' && definition.concurrency !== 'serial_per_run'))
|
|
24
|
+
throw new RuntimeError('TOOL_CONFIG', 'Invalid tool registration');
|
|
25
|
+
const input = z.fromJSONSchema(definition.inputSchema);
|
|
26
|
+
const output = definition.outputSchema ? z.fromJSONSchema(definition.outputSchema) : undefined;
|
|
27
|
+
const registration = Symbol();
|
|
28
|
+
this.bindings.set(key, {
|
|
29
|
+
definition: structuredClone(definition),
|
|
30
|
+
handler,
|
|
31
|
+
active: true,
|
|
32
|
+
registration,
|
|
33
|
+
versions: [...versions],
|
|
34
|
+
input,
|
|
35
|
+
...(output ? { output } : {}),
|
|
36
|
+
...(order ? { order: { tier: order.tier, priority: order.priority ?? 0 } } : {}),
|
|
37
|
+
});
|
|
38
|
+
return () => {
|
|
39
|
+
const binding = this.bindings.get(key);
|
|
40
|
+
if (binding?.registration === registration)
|
|
41
|
+
binding.active = false;
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
deactivate(name, version, scopeKey) {
|
|
45
|
+
const binding = this.bindings.get(keyOf(name, version, scopeKey));
|
|
46
|
+
if (binding)
|
|
47
|
+
binding.active = false;
|
|
48
|
+
}
|
|
49
|
+
activate(name, version, scopeKey) {
|
|
50
|
+
const binding = this.requireBinding(name, version, scopeKey);
|
|
51
|
+
binding.active = true;
|
|
52
|
+
}
|
|
53
|
+
isActive(name, version, scopeKey) {
|
|
54
|
+
return this.bindings.get(keyOf(name, version, scopeKey))?.active ?? false;
|
|
55
|
+
}
|
|
56
|
+
release(name, version, scopeKey) {
|
|
57
|
+
return this.bindings.delete(keyOf(name, version, scopeKey));
|
|
58
|
+
}
|
|
59
|
+
async snapshot(config) {
|
|
60
|
+
if (config.toolSnapshot) {
|
|
61
|
+
if (config.toolSnapshot.version !== config.toolSetVersion)
|
|
62
|
+
throw new RuntimeError('TOOL_CONFIG', 'Frozen tool set version mismatch');
|
|
63
|
+
if (config.toolSnapshot.definitions.some(({ abortGraceMs }) => toolAbortGraceIssue(abortGraceMs)))
|
|
64
|
+
throw new RuntimeError('TOOL_CONFIG', 'Invalid frozen tool abort grace');
|
|
65
|
+
return structuredClone(config.toolSnapshot);
|
|
66
|
+
}
|
|
67
|
+
if (config.pluginBindings)
|
|
68
|
+
return {
|
|
69
|
+
version: config.toolSetVersion,
|
|
70
|
+
definitions: await Promise.all(config.pluginBindings.tools.map((binding) => this.resolvePinned(binding))),
|
|
71
|
+
};
|
|
72
|
+
return this.select(config, false);
|
|
73
|
+
}
|
|
74
|
+
snapshotForAdmission(config, overrides, omitInactive = () => false) {
|
|
75
|
+
return this.select(config, true, overrides, omitInactive);
|
|
76
|
+
}
|
|
77
|
+
select(config, admission, overrides, omitInactive) {
|
|
78
|
+
if (!this.versions.includes(config.toolSetVersion))
|
|
79
|
+
throw new RuntimeError('TOOL_CONFIG', 'Tool set version unavailable');
|
|
80
|
+
const allowed = config.contextExtensions?.mode?.allowedTools;
|
|
81
|
+
const denied = config.contextExtensions?.mode?.deniedTools;
|
|
82
|
+
const selected = [...this.bindings.values()].filter(({ definition: { name, version, scopeKey }, versions }) => {
|
|
83
|
+
const override = overrides?.get(name);
|
|
84
|
+
return ((!allowed || allowed.includes(name)) &&
|
|
85
|
+
(!denied || !denied.includes(name)) &&
|
|
86
|
+
(override
|
|
87
|
+
? override.version === version && override.scopeKey === scopeKey
|
|
88
|
+
: versions.includes(config.toolSetVersion)));
|
|
89
|
+
});
|
|
90
|
+
const active = selected.filter((binding) => binding.active);
|
|
91
|
+
if (admission) {
|
|
92
|
+
const names = new Set(active.map(({ definition }) => definition.name));
|
|
93
|
+
const inactive = selected.find(({ definition }) => !names.has(definition.name) && !omitInactive?.(definition));
|
|
94
|
+
if (inactive)
|
|
95
|
+
throw new RuntimeError('PLUGIN_INACTIVE', `Tool ${inactive.definition.name} is inactive`);
|
|
96
|
+
if (names.size !== active.length)
|
|
97
|
+
throw new RuntimeError('TOOL_CONFIG', 'Multiple active versions of a selected tool');
|
|
98
|
+
}
|
|
99
|
+
return {
|
|
100
|
+
version: config.toolSetVersion,
|
|
101
|
+
definitions: active.sort(compareTools).map((value) => structuredClone(value.definition)),
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
pin(definition) {
|
|
105
|
+
const { name, version, source, scopeKey } = definition;
|
|
106
|
+
return {
|
|
107
|
+
name,
|
|
108
|
+
version,
|
|
109
|
+
source,
|
|
110
|
+
...(scopeKey === undefined ? {} : { scopeKey }),
|
|
111
|
+
definitionDigest: this.hash(definition),
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
async verifyBound(config) {
|
|
115
|
+
const definitions = config.toolSnapshot ? (await this.snapshot(config)).definitions : undefined;
|
|
116
|
+
if (config.pluginBindings) {
|
|
117
|
+
const pinned = await Promise.all(config.pluginBindings.tools.map((binding) => this.resolvePinned(binding)));
|
|
118
|
+
if (definitions && canonicalJson(definitions) !== canonicalJson(pinned))
|
|
119
|
+
throw new RuntimeError('PLUGIN_VERSION_UNAVAILABLE', 'Frozen tools disagree with Run bindings');
|
|
120
|
+
}
|
|
121
|
+
else if (definitions) {
|
|
122
|
+
for (const definition of definitions)
|
|
123
|
+
await this.resolveFrozen(definition);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
async resolveFrozen(definition) {
|
|
127
|
+
const binding = await this.resolveAvailable(definition.name, definition.version, definition.scopeKey);
|
|
128
|
+
if (canonicalJson(binding.definition) !== canonicalJson(definition))
|
|
129
|
+
throw this.unavailable(definition.name, definition.version);
|
|
130
|
+
return binding;
|
|
131
|
+
}
|
|
132
|
+
async resolvePinned(binding) {
|
|
133
|
+
const { name, version, source, definitionDigest, scopeKey } = binding;
|
|
134
|
+
const { definition } = await this.resolveAvailable(name, version, scopeKey);
|
|
135
|
+
if (canonicalJson(definition.source) !== canonicalJson(source) ||
|
|
136
|
+
(definitionDigest !== undefined && this.hash(definition) !== definitionDigest))
|
|
137
|
+
throw this.unavailable(name, version);
|
|
138
|
+
return definition;
|
|
139
|
+
}
|
|
140
|
+
async resolveAvailable(name, version, scopeKey) {
|
|
141
|
+
try {
|
|
142
|
+
return await this.resolve(name, version, scopeKey);
|
|
143
|
+
}
|
|
144
|
+
catch (error) {
|
|
145
|
+
if (error instanceof RuntimeError && error.code === 'TOOL_UNAVAILABLE')
|
|
146
|
+
throw this.unavailable(name, version);
|
|
147
|
+
throw error;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
unavailable(name, version) {
|
|
151
|
+
return new RuntimeError('PLUGIN_VERSION_UNAVAILABLE', `Tool ${name}@${version} is unavailable or changed`);
|
|
152
|
+
}
|
|
153
|
+
async resolve(name, version, scopeKey) {
|
|
154
|
+
const binding = this.requireBinding(name, version, scopeKey);
|
|
155
|
+
return { definition: structuredClone(binding.definition), handler: binding.handler };
|
|
156
|
+
}
|
|
157
|
+
validateInput(name, version, value, scopeKey) {
|
|
158
|
+
return this.requireBinding(name, version, scopeKey).input.safeParse(value).success;
|
|
159
|
+
}
|
|
160
|
+
describeInvalidInput(name, version, value, scopeKey) {
|
|
161
|
+
const parsed = this.requireBinding(name, version, scopeKey).input.safeParse(value);
|
|
162
|
+
if (parsed.success)
|
|
163
|
+
return;
|
|
164
|
+
const issue = parsed.error.issues[0];
|
|
165
|
+
if (!issue)
|
|
166
|
+
return;
|
|
167
|
+
if (issue.code === 'unrecognized_keys')
|
|
168
|
+
return 'Unexpected argument field';
|
|
169
|
+
const field = issue.path.map(String).join('.');
|
|
170
|
+
if (!field)
|
|
171
|
+
return;
|
|
172
|
+
if (issue.code === 'too_small' && issue.origin === 'string' && issue.minimum === 1)
|
|
173
|
+
return `${field} must not be empty`;
|
|
174
|
+
if (issue.code === 'too_big' && issue.origin === 'string')
|
|
175
|
+
return `${field} must contain at most ${issue.maximum} characters`;
|
|
176
|
+
if (issue.code === 'too_big' && issue.origin === 'array')
|
|
177
|
+
return `${field} must contain at most ${issue.maximum} items`;
|
|
178
|
+
if ((issue.code === 'too_big' || issue.code === 'too_small') && issue.origin === 'number')
|
|
179
|
+
return field + ': ' + issue.message;
|
|
180
|
+
if (issue.code === 'invalid_type') {
|
|
181
|
+
if (name === 'edit_file' &&
|
|
182
|
+
field === 'new_text' &&
|
|
183
|
+
value &&
|
|
184
|
+
typeof value === 'object' &&
|
|
185
|
+
!Array.isArray(value) &&
|
|
186
|
+
!Object.hasOwn(value, 'new_text') &&
|
|
187
|
+
['3', '4'].includes(version))
|
|
188
|
+
return 'Missing required field new_text; pass an empty string to delete the selected text';
|
|
189
|
+
return `Expected ${issue.expected} for ${field}`;
|
|
190
|
+
}
|
|
191
|
+
return `Invalid value for ${field}`;
|
|
192
|
+
}
|
|
193
|
+
validateOutput(name, version, value) {
|
|
194
|
+
const output = this.requireBinding(name, version).output;
|
|
195
|
+
return !output || output.safeParse(value).success;
|
|
196
|
+
}
|
|
197
|
+
async specs(config) {
|
|
198
|
+
return (await this.snapshot(config)).definitions.map((definition) => ({
|
|
199
|
+
canonicalName: definition.name,
|
|
200
|
+
wireName: definition.name,
|
|
201
|
+
version: definition.version,
|
|
202
|
+
description: definition.description,
|
|
203
|
+
inputSchema: definition.inputSchema,
|
|
204
|
+
}));
|
|
205
|
+
}
|
|
206
|
+
requireBinding(name, version, scopeKey) {
|
|
207
|
+
const binding = this.bindings.get(keyOf(name, version, scopeKey));
|
|
208
|
+
if (!binding)
|
|
209
|
+
throw new RuntimeError('TOOL_UNAVAILABLE', 'Tool version unavailable');
|
|
210
|
+
return binding;
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
function compareTools(a, b) {
|
|
214
|
+
if (!a.order)
|
|
215
|
+
return b.order ? -1 : 0;
|
|
216
|
+
if (!b.order)
|
|
217
|
+
return 1;
|
|
218
|
+
return (toolTiers[a.order.tier] - toolTiers[b.order.tier] ||
|
|
219
|
+
(a.order.priority ?? 0) - (b.order.priority ?? 0) ||
|
|
220
|
+
compareStrings(a.definition.name, b.definition.name) ||
|
|
221
|
+
compareStrings(a.definition.version, b.definition.version));
|
|
222
|
+
}
|
|
223
|
+
function compareStrings(a, b) {
|
|
224
|
+
if (a < b)
|
|
225
|
+
return -1;
|
|
226
|
+
return a > b ? 1 : 0;
|
|
227
|
+
}
|
package/dist/search.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { ToolBinding } from '@saturn-universe/core';
|
|
2
|
+
export declare const exploreHypothesesToolName = "explore_hypotheses";
|
|
3
|
+
export interface ExploreHypothesisInput {
|
|
4
|
+
readonly id: string;
|
|
5
|
+
readonly summary: string;
|
|
6
|
+
readonly strategy: string;
|
|
7
|
+
readonly verification?: string;
|
|
8
|
+
}
|
|
9
|
+
export declare function createExploreHypothesesTool(): ToolBinding;
|
package/dist/search.js
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
export const exploreHypothesesToolName = 'explore_hypotheses';
|
|
2
|
+
export function createExploreHypothesesTool() {
|
|
3
|
+
return {
|
|
4
|
+
definition: {
|
|
5
|
+
name: exploreHypothesesToolName,
|
|
6
|
+
version: '1',
|
|
7
|
+
description: 'Request parallel runtime exploration of 2-4 competing diagnostic or implementation hypotheses. Use only when root cause is uncertain, strategies compete, or prior attempts stalled; keep simple tasks linear. End your turn immediately after calling this tool so the runtime can execute the branches and deliver converged results in the next turn.',
|
|
8
|
+
inputSchema: {
|
|
9
|
+
type: 'object',
|
|
10
|
+
properties: {
|
|
11
|
+
goal: { type: 'string', minLength: 1, maxLength: 1000 },
|
|
12
|
+
hypotheses: {
|
|
13
|
+
type: 'array',
|
|
14
|
+
minItems: 2,
|
|
15
|
+
maxItems: 4,
|
|
16
|
+
items: {
|
|
17
|
+
type: 'object',
|
|
18
|
+
properties: {
|
|
19
|
+
id: { type: 'string', pattern: '^[A-Za-z0-9._-]{1,32}$' },
|
|
20
|
+
summary: { type: 'string', minLength: 1, maxLength: 500 },
|
|
21
|
+
strategy: { type: 'string', minLength: 1, maxLength: 2000 },
|
|
22
|
+
verification: { type: 'string', minLength: 1, maxLength: 500 },
|
|
23
|
+
},
|
|
24
|
+
required: ['id', 'summary', 'strategy'],
|
|
25
|
+
additionalProperties: false,
|
|
26
|
+
},
|
|
27
|
+
},
|
|
28
|
+
isolation: { type: 'string', enum: ['readonly', 'isolated'] },
|
|
29
|
+
},
|
|
30
|
+
required: ['goal', 'hypotheses'],
|
|
31
|
+
additionalProperties: false,
|
|
32
|
+
},
|
|
33
|
+
source: { kind: 'builtin' },
|
|
34
|
+
effects: 'read',
|
|
35
|
+
supportsIdempotencyKey: false,
|
|
36
|
+
supportsReconcile: false,
|
|
37
|
+
concurrency: 'serial_per_run',
|
|
38
|
+
timeoutMs: 10000,
|
|
39
|
+
},
|
|
40
|
+
handler: {
|
|
41
|
+
async invoke(input) {
|
|
42
|
+
const parsed = input;
|
|
43
|
+
const goal = parsed.goal.trim();
|
|
44
|
+
if (!goal)
|
|
45
|
+
return invalidSearch('goal must not be empty');
|
|
46
|
+
const isolation = parsed.isolation ?? 'readonly';
|
|
47
|
+
const seen = new Set();
|
|
48
|
+
const hypotheses = [];
|
|
49
|
+
for (const item of parsed.hypotheses) {
|
|
50
|
+
const id = item.id.trim();
|
|
51
|
+
const summary = item.summary.trim();
|
|
52
|
+
const strategy = item.strategy.trim();
|
|
53
|
+
const verification = item.verification?.trim();
|
|
54
|
+
if (!id || !summary || !strategy)
|
|
55
|
+
return invalidSearch('hypothesis id, summary, and strategy must not be empty');
|
|
56
|
+
if (seen.has(id))
|
|
57
|
+
return invalidSearch(`duplicate hypothesis id "${id}"`);
|
|
58
|
+
seen.add(id);
|
|
59
|
+
hypotheses.push({
|
|
60
|
+
id,
|
|
61
|
+
summary,
|
|
62
|
+
strategy,
|
|
63
|
+
...(verification ? { verification } : {}),
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
return {
|
|
67
|
+
effect: 'none',
|
|
68
|
+
outcome: {
|
|
69
|
+
status: 'success',
|
|
70
|
+
content: [
|
|
71
|
+
{
|
|
72
|
+
type: 'text',
|
|
73
|
+
text: `Exploration request recorded for ${hypotheses.length} hypotheses (isolation=${isolation}). End your turn now without calling submit_plan; the runtime will execute the exploration branches and provide the converged findings and reflections in the next turn.`,
|
|
74
|
+
},
|
|
75
|
+
],
|
|
76
|
+
data: {
|
|
77
|
+
kind: exploreHypothesesToolName,
|
|
78
|
+
goal,
|
|
79
|
+
isolation,
|
|
80
|
+
hypotheses,
|
|
81
|
+
},
|
|
82
|
+
},
|
|
83
|
+
};
|
|
84
|
+
},
|
|
85
|
+
},
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
function invalidSearch(message) {
|
|
89
|
+
return {
|
|
90
|
+
effect: 'none',
|
|
91
|
+
outcome: {
|
|
92
|
+
status: 'error',
|
|
93
|
+
error: { code: 'INVALID_ARGUMENTS', message, retryable: false },
|
|
94
|
+
},
|
|
95
|
+
};
|
|
96
|
+
}
|
package/dist/team.d.ts
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { RunId, ToolBinding, ToolContext } from '@saturn-universe/core';
|
|
2
|
+
export declare const spawnTeamToolName = "spawn_team";
|
|
3
|
+
export declare const teamNotifyParentToolName = "team_notify_parent";
|
|
4
|
+
export interface SpawnTeamCallerContext {
|
|
5
|
+
readonly memberId: string;
|
|
6
|
+
readonly depth: number;
|
|
7
|
+
readonly maxDepth: number;
|
|
8
|
+
readonly modeRef?: string | undefined;
|
|
9
|
+
readonly maxActiveDepth1?: number | undefined;
|
|
10
|
+
readonly activeDepth1Count?: number | undefined;
|
|
11
|
+
readonly maxConcurrentWorkers?: number | undefined;
|
|
12
|
+
}
|
|
13
|
+
export interface CreateSpawnTeamToolOptions {
|
|
14
|
+
readonly includeSandboxProfile?: boolean;
|
|
15
|
+
readonly includeWorkSubpath?: boolean;
|
|
16
|
+
readonly resolveCaller?: (ctx: ToolContext) => Promise<SpawnTeamCallerContext>;
|
|
17
|
+
}
|
|
18
|
+
export declare function createSpawnTeamTool(options?: CreateSpawnTeamToolOptions): ToolBinding;
|
|
19
|
+
export interface TeamNotifyParentCallerContext {
|
|
20
|
+
readonly memberId: string;
|
|
21
|
+
readonly parentId?: string | null;
|
|
22
|
+
readonly depth: number;
|
|
23
|
+
}
|
|
24
|
+
export interface TeamNotifyParentDelivery {
|
|
25
|
+
readonly runId: RunId;
|
|
26
|
+
readonly from: string;
|
|
27
|
+
readonly to: string;
|
|
28
|
+
readonly messageId: string;
|
|
29
|
+
readonly text: string;
|
|
30
|
+
readonly kind?: string;
|
|
31
|
+
}
|
|
32
|
+
export interface CreateTeamNotifyParentToolOptions {
|
|
33
|
+
readonly resolveCaller?: (ctx: ToolContext) => Promise<TeamNotifyParentCallerContext>;
|
|
34
|
+
readonly notifyParent?: (delivery: TeamNotifyParentDelivery) => Promise<void>;
|
|
35
|
+
}
|
|
36
|
+
export declare function createTeamNotifyParentTool(options?: CreateTeamNotifyParentToolOptions): ToolBinding;
|