@saturn-universe/tools 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +661 -0
- package/dist/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,423 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
3
|
+
import { link, mkdir, open, readFile, readdir, unlink } from 'node:fs/promises';
|
|
4
|
+
import net from 'node:net';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { RuntimeError } from '@saturn-universe/core';
|
|
7
|
+
import { isContainedPath } from './path-containment.js';
|
|
8
|
+
import { processWorkerSource } from './process-worker.js';
|
|
9
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
10
|
+
const matchesScope = (record, scope) => Object.entries(scope).every(([key, value]) => record.scope[key] === value);
|
|
11
|
+
export function processEnvironment() {
|
|
12
|
+
const env = {};
|
|
13
|
+
for (const key of ['SystemRoot', 'WINDIR', 'TEMP', 'TMP', 'TMPDIR', 'LANG', 'PATHEXT', 'ComSpec'])
|
|
14
|
+
if (process.env[key] !== undefined)
|
|
15
|
+
env[key] = process.env[key];
|
|
16
|
+
const value = process.env.PATH ?? process.env.Path;
|
|
17
|
+
if (value !== undefined)
|
|
18
|
+
env.PATH = value;
|
|
19
|
+
return env;
|
|
20
|
+
}
|
|
21
|
+
/** Persisted supervisor instances, rather than PIDs, are the unit of ownership. */
|
|
22
|
+
export function createProcessManager(options) {
|
|
23
|
+
const directory = path.resolve(options.directory);
|
|
24
|
+
const starts = new Map();
|
|
25
|
+
const startFingerprints = new Map();
|
|
26
|
+
const stoppedRuns = new Set();
|
|
27
|
+
let closed = false;
|
|
28
|
+
const idFor = (scope, executionKey) => createHash('sha256')
|
|
29
|
+
.update(JSON.stringify([scope.workspaceId, scope.runId, scope.agentId, executionKey]))
|
|
30
|
+
.digest('hex');
|
|
31
|
+
const filename = (id) => {
|
|
32
|
+
if (!/^[a-f0-9]{64}$/.test(id))
|
|
33
|
+
throw new RuntimeError('PROCESS_NOT_FOUND', 'Process handle is unavailable');
|
|
34
|
+
return path.join(directory, id + '.json');
|
|
35
|
+
};
|
|
36
|
+
const load = async (id) => {
|
|
37
|
+
try {
|
|
38
|
+
const value = JSON.parse(await readFile(filename(id), 'utf8'));
|
|
39
|
+
if (value.version !== 1 || value.processId !== id)
|
|
40
|
+
throw new Error('Invalid process record');
|
|
41
|
+
return value;
|
|
42
|
+
}
|
|
43
|
+
catch (error) {
|
|
44
|
+
if (error.code === 'ENOENT')
|
|
45
|
+
return undefined;
|
|
46
|
+
throw new RuntimeError('PROCESS_RECORD_INVALID', 'Process record cannot be read safely');
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
const scoped = async (id, scope) => {
|
|
50
|
+
validateScope(scope, 'handle');
|
|
51
|
+
const record = await load(id);
|
|
52
|
+
if (!record || !matchesScope(record, scope))
|
|
53
|
+
throw new RuntimeError('PROCESS_NOT_FOUND', 'Process handle is unavailable in this workspace, run and agent');
|
|
54
|
+
return record;
|
|
55
|
+
};
|
|
56
|
+
const refresh = async (record) => {
|
|
57
|
+
if (record.status === 'exited' || record.status === 'unknown')
|
|
58
|
+
return record;
|
|
59
|
+
try {
|
|
60
|
+
return await request(record, 'read');
|
|
61
|
+
}
|
|
62
|
+
catch {
|
|
63
|
+
const latest = (await load(record.processId)) ?? record;
|
|
64
|
+
return latest.status === 'exited'
|
|
65
|
+
? latest
|
|
66
|
+
: { ...latest, status: 'unknown', terminationConfirmed: false };
|
|
67
|
+
}
|
|
68
|
+
};
|
|
69
|
+
const list = async (scope = {}) => {
|
|
70
|
+
let entries;
|
|
71
|
+
try {
|
|
72
|
+
entries = await readdir(directory);
|
|
73
|
+
}
|
|
74
|
+
catch (error) {
|
|
75
|
+
if (error.code === 'ENOENT')
|
|
76
|
+
return [];
|
|
77
|
+
throw error;
|
|
78
|
+
}
|
|
79
|
+
const records = [];
|
|
80
|
+
for (const entry of entries) {
|
|
81
|
+
if (!/^[a-f0-9]{64}\.json$/.test(entry))
|
|
82
|
+
continue;
|
|
83
|
+
try {
|
|
84
|
+
const record = await load(entry.slice(0, -5));
|
|
85
|
+
if (record && matchesScope(record, scope))
|
|
86
|
+
records.push(record);
|
|
87
|
+
}
|
|
88
|
+
catch {
|
|
89
|
+
options.onRecordError?.(entry.slice(0, -5), 'Invalid process record was retained; inspect it before retrying');
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return records;
|
|
93
|
+
};
|
|
94
|
+
const stopRecord = async (record) => {
|
|
95
|
+
if (record.status === 'exited') {
|
|
96
|
+
if (!record.terminationConfirmed && record.stopCommand) {
|
|
97
|
+
const cleaned = await runStopCommand(record.stopCommand, record.env);
|
|
98
|
+
if (cleaned)
|
|
99
|
+
return snapshot({ ...record, terminationConfirmed: true });
|
|
100
|
+
}
|
|
101
|
+
return snapshot(record);
|
|
102
|
+
}
|
|
103
|
+
if (record.status === 'unknown') {
|
|
104
|
+
if (record.stopCommand)
|
|
105
|
+
await runStopCommand(record.stopCommand, record.env);
|
|
106
|
+
return snapshot(record);
|
|
107
|
+
}
|
|
108
|
+
try {
|
|
109
|
+
// The stop request authenticates the supervisor itself. A preceding read
|
|
110
|
+
// adds latency and could suppress cleanup after a transient read timeout.
|
|
111
|
+
const stopTimeoutMs = record.stopCommand
|
|
112
|
+
? Math.max(4000, (record.stopCommand.timeoutMs ?? 5000) + 2000)
|
|
113
|
+
: 4000;
|
|
114
|
+
return snapshot(await request(record, 'stop', {}, stopTimeoutMs));
|
|
115
|
+
}
|
|
116
|
+
catch {
|
|
117
|
+
if (record.stopCommand)
|
|
118
|
+
await runStopCommand(record.stopCommand, record.env);
|
|
119
|
+
return snapshot(await refresh(record));
|
|
120
|
+
}
|
|
121
|
+
};
|
|
122
|
+
return {
|
|
123
|
+
start(input, scope, executionKey, signal) {
|
|
124
|
+
if (closed || stoppedRuns.has(scope.runId))
|
|
125
|
+
return Promise.reject(new RuntimeError('PROCESS_MANAGER_CLOSED', 'Process manager is closed'));
|
|
126
|
+
validateScope(scope, executionKey);
|
|
127
|
+
const id = idFor(scope, executionKey);
|
|
128
|
+
const fingerprint = createHash('sha256')
|
|
129
|
+
.update(JSON.stringify([input.program, input.args, input.cwd, input.timeoutMs ?? 900000]))
|
|
130
|
+
.digest('hex');
|
|
131
|
+
const pending = starts.get(id);
|
|
132
|
+
if (pending)
|
|
133
|
+
return startFingerprints.get(id) === fingerprint
|
|
134
|
+
? pending
|
|
135
|
+
: Promise.reject(new RuntimeError('PROCESS_KEY_CONFLICT', 'Execution key input changed'));
|
|
136
|
+
const start = async () => {
|
|
137
|
+
signal?.throwIfAborted();
|
|
138
|
+
const timeoutMs = input.timeoutMs ?? 900000;
|
|
139
|
+
if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 86400000)
|
|
140
|
+
throw new RuntimeError('INVALID_ARGUMENTS', 'Process timeout must be 1..86400000 ms');
|
|
141
|
+
const existing = await load(id);
|
|
142
|
+
if (existing) {
|
|
143
|
+
if (existing.fingerprint !== fingerprint)
|
|
144
|
+
throw new RuntimeError('PROCESS_KEY_CONFLICT', 'Execution key was already used for another process');
|
|
145
|
+
return snapshot(await refresh(existing));
|
|
146
|
+
}
|
|
147
|
+
const runDeadline = await options.getRunDeadline?.(scope.runId);
|
|
148
|
+
const deadlineAt = Math.min(Date.now() + timeoutMs, runDeadline ?? Infinity);
|
|
149
|
+
if (deadlineAt <= Date.now())
|
|
150
|
+
throw new RuntimeError('TIMEOUT', 'Run deadline has already elapsed');
|
|
151
|
+
const record = {
|
|
152
|
+
version: 1,
|
|
153
|
+
processId: id,
|
|
154
|
+
scope,
|
|
155
|
+
executionKey,
|
|
156
|
+
fingerprint,
|
|
157
|
+
token: randomUUID(),
|
|
158
|
+
program: input.program,
|
|
159
|
+
args: input.args,
|
|
160
|
+
cwd: input.cwd,
|
|
161
|
+
env: input.env ?? processEnvironment(),
|
|
162
|
+
...(input.stopCommand ? { stopCommand: input.stopCommand } : {}),
|
|
163
|
+
status: 'starting',
|
|
164
|
+
exitCode: null,
|
|
165
|
+
signal: null,
|
|
166
|
+
terminationConfirmed: false,
|
|
167
|
+
stdout: '',
|
|
168
|
+
stderr: '',
|
|
169
|
+
stdoutOffset: 0,
|
|
170
|
+
stderrOffset: 0,
|
|
171
|
+
deadlineAt,
|
|
172
|
+
};
|
|
173
|
+
await mkdir(directory, { recursive: true, mode: 0o700 });
|
|
174
|
+
signal?.throwIfAborted();
|
|
175
|
+
if (closed || stoppedRuns.has(scope.runId))
|
|
176
|
+
throw new RuntimeError('PROCESS_MANAGER_CLOSED', 'Process scope has ended');
|
|
177
|
+
const temporary = path.join(directory, `.reservation-${randomUUID()}.tmp`);
|
|
178
|
+
const handle = await open(temporary, 'wx', 0o600);
|
|
179
|
+
try {
|
|
180
|
+
await handle.writeFile(JSON.stringify(record));
|
|
181
|
+
await handle.sync();
|
|
182
|
+
}
|
|
183
|
+
finally {
|
|
184
|
+
await handle.close();
|
|
185
|
+
}
|
|
186
|
+
try {
|
|
187
|
+
// Atomic exclusive publication prevents partial reservations and double launch.
|
|
188
|
+
await link(temporary, filename(id));
|
|
189
|
+
}
|
|
190
|
+
catch (error) {
|
|
191
|
+
if (error.code !== 'EEXIST')
|
|
192
|
+
throw error;
|
|
193
|
+
// A crash between reservation and launch is ambiguous; never repeat it.
|
|
194
|
+
const prior = await scoped(id, scope);
|
|
195
|
+
if (prior.fingerprint !== fingerprint)
|
|
196
|
+
throw new RuntimeError('PROCESS_KEY_CONFLICT', 'Execution key input changed');
|
|
197
|
+
return snapshot(await refresh(prior));
|
|
198
|
+
}
|
|
199
|
+
finally {
|
|
200
|
+
await unlink(temporary).catch(() => { });
|
|
201
|
+
}
|
|
202
|
+
// The durable reservation now exists. Cancellation must not erase it.
|
|
203
|
+
try {
|
|
204
|
+
const worker = spawn(process.execPath, ['-e', processWorkerSource, filename(id)], {
|
|
205
|
+
cwd: process.cwd(),
|
|
206
|
+
env: processEnvironment(),
|
|
207
|
+
detached: true,
|
|
208
|
+
windowsHide: true,
|
|
209
|
+
stdio: 'ignore',
|
|
210
|
+
});
|
|
211
|
+
let launchError = false;
|
|
212
|
+
worker.once('error', () => {
|
|
213
|
+
launchError = true;
|
|
214
|
+
});
|
|
215
|
+
worker.unref();
|
|
216
|
+
for (let i = 0; i < 100 && !launchError; i++) {
|
|
217
|
+
const latest = (await load(id));
|
|
218
|
+
if (latest.status !== 'starting')
|
|
219
|
+
return snapshot(await refresh(latest));
|
|
220
|
+
await sleep(20);
|
|
221
|
+
}
|
|
222
|
+
return snapshot(await refresh((await load(id))));
|
|
223
|
+
}
|
|
224
|
+
catch {
|
|
225
|
+
// Once published, local I/O failure cannot establish that launch had
|
|
226
|
+
// no effect. Leave the reservation for later identity reconciliation.
|
|
227
|
+
return snapshot({ ...record, status: 'unknown' });
|
|
228
|
+
}
|
|
229
|
+
};
|
|
230
|
+
const result = start().finally(() => {
|
|
231
|
+
starts.delete(id);
|
|
232
|
+
startFingerprints.delete(id);
|
|
233
|
+
});
|
|
234
|
+
starts.set(id, result);
|
|
235
|
+
startFingerprints.set(id, fingerprint);
|
|
236
|
+
return result;
|
|
237
|
+
},
|
|
238
|
+
async read(id, scope, input = {}, signal) {
|
|
239
|
+
const waitMs = input.waitMs ?? 0;
|
|
240
|
+
if (!Number.isInteger(waitMs) || waitMs < 0 || waitMs > 30000)
|
|
241
|
+
throw new RuntimeError('INVALID_ARGUMENTS', 'waitMs must be 0..30000');
|
|
242
|
+
const deadline = Date.now() + waitMs;
|
|
243
|
+
for (;;) {
|
|
244
|
+
signal?.throwIfAborted();
|
|
245
|
+
const value = snapshot(await refresh(await scoped(id, scope)), input);
|
|
246
|
+
if (value.status !== 'running' || value.stdout || value.stderr || Date.now() >= deadline)
|
|
247
|
+
return value;
|
|
248
|
+
await sleep(Math.min(25, deadline - Date.now()));
|
|
249
|
+
}
|
|
250
|
+
},
|
|
251
|
+
async write(id, scope, input, executionKey) {
|
|
252
|
+
validateScope(scope, executionKey);
|
|
253
|
+
if (Buffer.byteLength(input.input ?? '') > 65536 || (input.input === undefined && !input.eof))
|
|
254
|
+
throw new RuntimeError('INVALID_ARGUMENTS', 'Write requires input up to 64 KiB or explicit EOF');
|
|
255
|
+
const record = await scoped(id, scope);
|
|
256
|
+
try {
|
|
257
|
+
return snapshot(await request(record, 'write', { ...input, executionKey }));
|
|
258
|
+
}
|
|
259
|
+
catch {
|
|
260
|
+
throw new RuntimeError('PROCESS_INPUT_UNKNOWN', 'Input could not be confirmed; reuse the same execution key to reconcile, never repeat with a new key');
|
|
261
|
+
}
|
|
262
|
+
},
|
|
263
|
+
async stop(id, scope) {
|
|
264
|
+
return stopRecord(await scoped(id, scope));
|
|
265
|
+
},
|
|
266
|
+
async reconcile(key, scope) {
|
|
267
|
+
validateScope(scope, key);
|
|
268
|
+
const record = await load(idFor(scope, key));
|
|
269
|
+
return record ? snapshot(await refresh(record)) : undefined;
|
|
270
|
+
},
|
|
271
|
+
async recover(scope = {}) {
|
|
272
|
+
return Promise.all((await list(scope)).map(async (record) => snapshot(await refresh(record))));
|
|
273
|
+
},
|
|
274
|
+
async stopRun(runId) {
|
|
275
|
+
stoppedRuns.add(runId);
|
|
276
|
+
await Promise.allSettled([...starts.values()]);
|
|
277
|
+
return Promise.all((await list({ runId })).map(stopRecord));
|
|
278
|
+
},
|
|
279
|
+
async stopWorkspace(workingDirectory, includeDescendants = false) {
|
|
280
|
+
await Promise.allSettled([...starts.values()]);
|
|
281
|
+
const normalize = (directory) => {
|
|
282
|
+
const resolved = path.resolve(directory);
|
|
283
|
+
return process.platform === 'win32' ? resolved.toLowerCase() : resolved;
|
|
284
|
+
};
|
|
285
|
+
const target = normalize(workingDirectory);
|
|
286
|
+
return Promise.all((await list())
|
|
287
|
+
.filter((record) => {
|
|
288
|
+
const candidate = normalize(record.cwd);
|
|
289
|
+
return candidate === target || (includeDescendants && isContainedPath(target, candidate));
|
|
290
|
+
})
|
|
291
|
+
.map(stopRecord));
|
|
292
|
+
},
|
|
293
|
+
async close() {
|
|
294
|
+
closed = true;
|
|
295
|
+
await Promise.allSettled([...starts.values()]);
|
|
296
|
+
await Promise.all((await list()).map(stopRecord));
|
|
297
|
+
},
|
|
298
|
+
};
|
|
299
|
+
}
|
|
300
|
+
function validateScope(scope, executionKey) {
|
|
301
|
+
if (![scope.workspaceId, scope.runId, scope.agentId, executionKey].every((value) => typeof value === 'string' && value.length > 0))
|
|
302
|
+
throw new RuntimeError('PROCESS_SCOPE_INVALID', 'Process ownership requires workspace, run, agent and execution key');
|
|
303
|
+
}
|
|
304
|
+
function snapshot(record, options = {}) {
|
|
305
|
+
const maxBytes = options.maxBytes ?? 8192;
|
|
306
|
+
if (!Number.isInteger(maxBytes) ||
|
|
307
|
+
maxBytes < 1 ||
|
|
308
|
+
maxBytes > 65536 ||
|
|
309
|
+
[options.stdoutOffset, options.stderrOffset].some((value) => value !== undefined && (!Number.isSafeInteger(value) || value < 0)))
|
|
310
|
+
throw new RuntimeError('INVALID_ARGUMENTS', 'Output offsets must be nonnegative integers; maxBytes must be 1..65536');
|
|
311
|
+
const stdout = Buffer.from(record.stdout, 'base64'), stderr = Buffer.from(record.stderr, 'base64');
|
|
312
|
+
const outStart = Math.max(record.stdoutOffset, Math.min(options.stdoutOffset ?? record.stdoutOffset, record.stdoutOffset + stdout.length));
|
|
313
|
+
const errStart = Math.max(record.stderrOffset, Math.min(options.stderrOffset ?? record.stderrOffset, record.stderrOffset + stderr.length));
|
|
314
|
+
const out = stdout.subarray(outStart - record.stdoutOffset, outStart - record.stdoutOffset + maxBytes);
|
|
315
|
+
const err = stderr.subarray(errStart - record.stderrOffset, errStart - record.stderrOffset + Math.max(0, maxBytes - out.length));
|
|
316
|
+
return {
|
|
317
|
+
processId: record.processId,
|
|
318
|
+
scope: record.scope,
|
|
319
|
+
status: record.status,
|
|
320
|
+
...(record.pid === undefined ? {} : { pid: record.pid }),
|
|
321
|
+
exitCode: record.exitCode,
|
|
322
|
+
signal: record.signal,
|
|
323
|
+
terminationConfirmed: record.terminationConfirmed,
|
|
324
|
+
stdout: out.toString('utf8'),
|
|
325
|
+
stderr: err.toString('utf8'),
|
|
326
|
+
stdoutOffset: outStart,
|
|
327
|
+
stderrOffset: errStart,
|
|
328
|
+
nextStdoutOffset: outStart + out.length,
|
|
329
|
+
nextStderrOffset: errStart + err.length,
|
|
330
|
+
truncated: (options.stdoutOffset ?? 0) < record.stdoutOffset ||
|
|
331
|
+
(options.stderrOffset ?? 0) < record.stderrOffset ||
|
|
332
|
+
outStart + out.length < record.stdoutOffset + stdout.length ||
|
|
333
|
+
errStart + err.length < record.stderrOffset + stderr.length,
|
|
334
|
+
deadlineAt: record.deadlineAt,
|
|
335
|
+
...(record.stopReason ? { stopReason: record.stopReason } : {}),
|
|
336
|
+
...(record.startError ? { startError: record.startError } : {}),
|
|
337
|
+
};
|
|
338
|
+
}
|
|
339
|
+
function request(record, action, input = {}, timeoutMs = 2000) {
|
|
340
|
+
if (!record.port)
|
|
341
|
+
return Promise.reject(new Error('Supervisor endpoint unavailable'));
|
|
342
|
+
return new Promise((resolve, reject) => {
|
|
343
|
+
const socket = net.createConnection({ host: '127.0.0.1', port: record.port });
|
|
344
|
+
socket.setEncoding('utf8');
|
|
345
|
+
const timer = setTimeout(() => socket.destroy(new Error('Supervisor timeout')), timeoutMs);
|
|
346
|
+
let text = '';
|
|
347
|
+
socket.once('error', reject);
|
|
348
|
+
socket.once('connect', () => socket.write(JSON.stringify({ processId: record.processId, token: record.token, action, ...input }) + '\n'));
|
|
349
|
+
socket.on('data', (chunk) => {
|
|
350
|
+
text += chunk.toString('utf8');
|
|
351
|
+
if (Buffer.byteLength(text) > 1024 * 1024) {
|
|
352
|
+
socket.destroy(new Error('Supervisor response too large'));
|
|
353
|
+
return;
|
|
354
|
+
}
|
|
355
|
+
if (!text.includes('\n'))
|
|
356
|
+
return;
|
|
357
|
+
try {
|
|
358
|
+
const response = JSON.parse(text.slice(0, text.indexOf('\n')));
|
|
359
|
+
if (response.token !== record.token || response.record?.processId !== record.processId)
|
|
360
|
+
throw new Error(response.error ?? 'Supervisor identity mismatch');
|
|
361
|
+
resolve(response.record);
|
|
362
|
+
}
|
|
363
|
+
catch (error) {
|
|
364
|
+
reject(error);
|
|
365
|
+
}
|
|
366
|
+
socket.destroy();
|
|
367
|
+
});
|
|
368
|
+
socket.once('close', () => {
|
|
369
|
+
clearTimeout(timer);
|
|
370
|
+
reject(new Error('Supervisor disconnected'));
|
|
371
|
+
});
|
|
372
|
+
});
|
|
373
|
+
}
|
|
374
|
+
async function runStopCommand(command, fallbackEnv) {
|
|
375
|
+
const timeoutMs = command.timeoutMs ?? 6000;
|
|
376
|
+
return new Promise((resolve) => {
|
|
377
|
+
let settled = false;
|
|
378
|
+
let child;
|
|
379
|
+
try {
|
|
380
|
+
child = spawn(command.program, [...command.args], {
|
|
381
|
+
cwd: command.cwd ?? process.cwd(),
|
|
382
|
+
env: command.env ?? fallbackEnv,
|
|
383
|
+
shell: false,
|
|
384
|
+
windowsHide: true,
|
|
385
|
+
stdio: ['ignore', 'ignore', 'pipe'],
|
|
386
|
+
});
|
|
387
|
+
}
|
|
388
|
+
catch {
|
|
389
|
+
resolve(false);
|
|
390
|
+
return;
|
|
391
|
+
}
|
|
392
|
+
const errChunks = [];
|
|
393
|
+
let errBytes = 0;
|
|
394
|
+
const finish = (ok) => {
|
|
395
|
+
if (settled)
|
|
396
|
+
return;
|
|
397
|
+
settled = true;
|
|
398
|
+
clearTimeout(timer);
|
|
399
|
+
resolve(ok);
|
|
400
|
+
};
|
|
401
|
+
const timer = setTimeout(() => {
|
|
402
|
+
try {
|
|
403
|
+
child.kill('SIGKILL');
|
|
404
|
+
}
|
|
405
|
+
catch {
|
|
406
|
+
// Ignore kill error on already exited child
|
|
407
|
+
}
|
|
408
|
+
finish(false);
|
|
409
|
+
}, timeoutMs);
|
|
410
|
+
child.stderr?.on('data', (chunk) => {
|
|
411
|
+
if (errBytes < 4096) {
|
|
412
|
+
const slice = chunk.subarray(0, 4096 - errBytes);
|
|
413
|
+
errChunks.push(slice);
|
|
414
|
+
errBytes += slice.length;
|
|
415
|
+
}
|
|
416
|
+
});
|
|
417
|
+
child.once('error', () => finish(false));
|
|
418
|
+
child.once('close', (code) => {
|
|
419
|
+
const stderr = Buffer.concat(errChunks).toString('utf8');
|
|
420
|
+
finish(code === 0 || /no such container|is not running/i.test(stderr));
|
|
421
|
+
});
|
|
422
|
+
});
|
|
423
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
export declare const maxProcessOutputBytes: number;
|
|
2
|
+
export declare const maxProcessOutputSpillBytes: number;
|
|
3
|
+
export declare function isProcessOutputPath(relative: string): boolean;
|
|
4
|
+
/** Capture in the order that chunks arrive from the two pipes. */
|
|
5
|
+
export declare class ProcessOutput {
|
|
6
|
+
private readonly root;
|
|
7
|
+
private readonly key;
|
|
8
|
+
private readonly head;
|
|
9
|
+
private readonly headStreams;
|
|
10
|
+
private readonly tail;
|
|
11
|
+
private readonly tailStreams;
|
|
12
|
+
private totalBytes;
|
|
13
|
+
private newlines;
|
|
14
|
+
private lastByte;
|
|
15
|
+
private file?;
|
|
16
|
+
private spillPath;
|
|
17
|
+
private spillBytes;
|
|
18
|
+
private spillLimitExceeded;
|
|
19
|
+
private spillError?;
|
|
20
|
+
constructor(root: string, key: readonly string[]);
|
|
21
|
+
get outputLimitExceeded(): boolean;
|
|
22
|
+
append(chunk: Buffer, stream: 0 | 1): Promise<void> | undefined;
|
|
23
|
+
private spill;
|
|
24
|
+
finish(): Promise<{
|
|
25
|
+
spillError?: string;
|
|
26
|
+
spillLimitExceeded?: boolean;
|
|
27
|
+
spillPath?: string;
|
|
28
|
+
stdout: string;
|
|
29
|
+
stderr: string;
|
|
30
|
+
truncated: boolean;
|
|
31
|
+
totalBytes: number;
|
|
32
|
+
totalLines: number;
|
|
33
|
+
}>;
|
|
34
|
+
}
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { lstat, mkdir, open, realpath, unlink } from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
export const maxProcessOutputBytes = 64 * 1024;
|
|
5
|
+
export const maxProcessOutputSpillBytes = 8 * 1024 * 1024;
|
|
6
|
+
const headBytes = 8 * 1024;
|
|
7
|
+
const tailBytes = maxProcessOutputBytes - headBytes;
|
|
8
|
+
const spillDirectory = ['.saturn', 'tmp'];
|
|
9
|
+
export function isProcessOutputPath(relative) {
|
|
10
|
+
const parts = relative.split(path.sep);
|
|
11
|
+
return (parts.length === 3 &&
|
|
12
|
+
parts[0] === spillDirectory[0] &&
|
|
13
|
+
parts[1] === spillDirectory[1] &&
|
|
14
|
+
/^saturn-output-[a-f0-9]{64}\.log$/.test(parts[2]));
|
|
15
|
+
}
|
|
16
|
+
/** Capture in the order that chunks arrive from the two pipes. */
|
|
17
|
+
export class ProcessOutput {
|
|
18
|
+
root;
|
|
19
|
+
key;
|
|
20
|
+
head = Buffer.alloc(headBytes);
|
|
21
|
+
headStreams = Buffer.alloc(headBytes);
|
|
22
|
+
tail = Buffer.alloc(tailBytes);
|
|
23
|
+
tailStreams = Buffer.alloc(tailBytes);
|
|
24
|
+
totalBytes = 0;
|
|
25
|
+
newlines = 0;
|
|
26
|
+
lastByte;
|
|
27
|
+
file;
|
|
28
|
+
spillPath;
|
|
29
|
+
spillBytes = 0;
|
|
30
|
+
spillLimitExceeded = false;
|
|
31
|
+
spillError;
|
|
32
|
+
constructor(root, key) {
|
|
33
|
+
this.root = root;
|
|
34
|
+
this.key = key;
|
|
35
|
+
}
|
|
36
|
+
get outputLimitExceeded() {
|
|
37
|
+
return this.spillLimitExceeded;
|
|
38
|
+
}
|
|
39
|
+
append(chunk, stream) {
|
|
40
|
+
const before = this.totalBytes;
|
|
41
|
+
const after = before + chunk.length;
|
|
42
|
+
let pending;
|
|
43
|
+
if (after > maxProcessOutputBytes && !this.spillError && !this.spillLimitExceeded) {
|
|
44
|
+
if (before <= maxProcessOutputBytes) {
|
|
45
|
+
const prefix = Buffer.concat([
|
|
46
|
+
this.head.subarray(0, Math.min(before, headBytes)),
|
|
47
|
+
this.tail.subarray(0, Math.max(0, before - headBytes)),
|
|
48
|
+
]);
|
|
49
|
+
pending = this.spill(chunk, prefix);
|
|
50
|
+
}
|
|
51
|
+
else {
|
|
52
|
+
pending = this.spill(chunk);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
for (let index = chunk.indexOf(10); index !== -1; index = chunk.indexOf(10, index + 1))
|
|
56
|
+
this.newlines++;
|
|
57
|
+
this.lastByte = chunk.at(-1) ?? this.lastByte;
|
|
58
|
+
this.totalBytes = after;
|
|
59
|
+
const headLength = Math.max(0, Math.min(chunk.length, headBytes - before));
|
|
60
|
+
if (headLength) {
|
|
61
|
+
chunk.copy(this.head, before, 0, headLength);
|
|
62
|
+
this.headStreams.fill(stream, before, before + headLength);
|
|
63
|
+
}
|
|
64
|
+
// The tail is a ring indexed by absolute output position after the head.
|
|
65
|
+
const start = Math.max(headLength, chunk.length - tailBytes);
|
|
66
|
+
if (start < chunk.length) {
|
|
67
|
+
const cursor = (before + start - headBytes) % tailBytes;
|
|
68
|
+
const count = Math.min(chunk.length - start, tailBytes - cursor);
|
|
69
|
+
chunk.copy(this.tail, cursor, start, start + count);
|
|
70
|
+
this.tailStreams.fill(stream, cursor, cursor + count);
|
|
71
|
+
const remaining = chunk.length - start - count;
|
|
72
|
+
if (remaining) {
|
|
73
|
+
chunk.copy(this.tail, 0, start + count);
|
|
74
|
+
this.tailStreams.fill(stream, 0, remaining);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return pending;
|
|
78
|
+
}
|
|
79
|
+
async spill(chunk, prefix) {
|
|
80
|
+
try {
|
|
81
|
+
if (prefix) {
|
|
82
|
+
let directory = await realpath(this.root);
|
|
83
|
+
for (const part of spillDirectory) {
|
|
84
|
+
directory = path.join(directory, part);
|
|
85
|
+
await mkdir(directory, { mode: 0o700 }).catch((error) => {
|
|
86
|
+
if (error.code !== 'EEXIST')
|
|
87
|
+
throw error;
|
|
88
|
+
});
|
|
89
|
+
if (!(await lstat(directory)).isDirectory() || path.relative(directory, await realpath(directory)))
|
|
90
|
+
throw new Error('Workspace temporary directory must be a regular directory');
|
|
91
|
+
}
|
|
92
|
+
const id = createHash('sha256').update(JSON.stringify(this.key)).digest('hex');
|
|
93
|
+
const filename = path.join(directory, 'saturn-output-' + id + '.log');
|
|
94
|
+
this.file = await open(filename, 'wx', 0o600);
|
|
95
|
+
this.spillPath = filename;
|
|
96
|
+
await this.file.writeFile(prefix);
|
|
97
|
+
this.spillBytes += prefix.length;
|
|
98
|
+
}
|
|
99
|
+
const remaining = maxProcessOutputSpillBytes - this.spillBytes;
|
|
100
|
+
if (remaining <= 0) {
|
|
101
|
+
this.spillLimitExceeded = true;
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
const writable = chunk.subarray(0, Math.min(chunk.length, remaining));
|
|
105
|
+
await this.file.writeFile(writable);
|
|
106
|
+
this.spillBytes += writable.length;
|
|
107
|
+
if (writable.length < chunk.length)
|
|
108
|
+
this.spillLimitExceeded = true;
|
|
109
|
+
}
|
|
110
|
+
catch (error) {
|
|
111
|
+
this.spillError = error instanceof Error ? error.message : String(error);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
async finish() {
|
|
115
|
+
try {
|
|
116
|
+
await this.file?.close();
|
|
117
|
+
}
|
|
118
|
+
catch (error) {
|
|
119
|
+
this.spillError ??= error instanceof Error ? error.message : String(error);
|
|
120
|
+
}
|
|
121
|
+
if (this.spillError && this.spillPath) {
|
|
122
|
+
await unlink(this.spillPath).catch(() => { });
|
|
123
|
+
this.spillPath = undefined;
|
|
124
|
+
}
|
|
125
|
+
const headLength = Math.min(this.totalBytes, headBytes);
|
|
126
|
+
const tailLength = Math.min(Math.max(0, this.totalBytes - headBytes), tailBytes);
|
|
127
|
+
const truncated = this.totalBytes > maxProcessOutputBytes;
|
|
128
|
+
const cursor = truncated ? (this.totalBytes - headBytes) % tailBytes : 0;
|
|
129
|
+
const head = separateStreams(this.head, this.headStreams, 0, headLength);
|
|
130
|
+
const tail = separateStreams(this.tail, this.tailStreams, cursor, tailLength);
|
|
131
|
+
const inline = (stream) => {
|
|
132
|
+
const first = head[stream];
|
|
133
|
+
const last = tail[stream];
|
|
134
|
+
if (truncated && first.length && last.length)
|
|
135
|
+
return first.toString('utf8') + '\n… (truncated)\n' + last.toString('utf8');
|
|
136
|
+
return Buffer.concat([first, last]).toString('utf8');
|
|
137
|
+
};
|
|
138
|
+
return {
|
|
139
|
+
stdout: inline(0),
|
|
140
|
+
stderr: inline(1),
|
|
141
|
+
truncated,
|
|
142
|
+
totalBytes: this.totalBytes,
|
|
143
|
+
totalLines: this.newlines + (this.lastByte !== undefined && this.lastByte !== 10 ? 1 : 0),
|
|
144
|
+
...(this.spillPath ? { spillPath: this.spillPath } : {}),
|
|
145
|
+
...(this.spillLimitExceeded ? { spillLimitExceeded: true } : {}),
|
|
146
|
+
...(this.spillError ? { spillError: this.spillError } : {}),
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
function separateStreams(bytes, streams, start, length) {
|
|
151
|
+
const parts = [[], []];
|
|
152
|
+
for (let offset = 0; offset < length;) {
|
|
153
|
+
const index = (start + offset) % bytes.length;
|
|
154
|
+
const stream = streams[index];
|
|
155
|
+
const bound = Math.min(bytes.length, index + length - offset);
|
|
156
|
+
const change = streams.indexOf(1 - stream, index);
|
|
157
|
+
const end = change === -1 ? bound : Math.min(change, bound);
|
|
158
|
+
parts[stream].push(bytes.subarray(index, end));
|
|
159
|
+
offset += end - index;
|
|
160
|
+
}
|
|
161
|
+
return [Buffer.concat(parts[0]), Buffer.concat(parts[1])];
|
|
162
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const processWorkerSource: string;
|