@zenera/neo 1.1.55 → 1.1.57
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/dist/memory/files.d.ts +37 -3
- package/dist/memory/files.js +26 -14
- package/dist/memory/grep.js +2 -2
- package/dist/memory/index.d.ts +14 -3
- package/dist/memory/index.js +17 -0
- package/dist/memory/render.js +2 -1
- package/dist/memory/tools.js +62 -9
- package/dist/memory/types.d.ts +1 -1
- package/dist/memory/types.js +1 -1
- package/dist/project/config.d.ts +1 -24
- package/dist/project/config.js +18 -5
- package/dist/project/load.d.ts +6 -8
- package/dist/project/load.js +3 -4
- package/dist/runner.d.ts +3 -2
- package/dist/runner.js +1 -1
- package/dist/services.d.ts +8 -6
- package/dist/services.js +7 -6
- package/dist/tools/files.d.ts +28 -37
- package/dist/tools/files.js +106 -84
- package/dist/tools/identity.d.ts +12 -0
- package/dist/tools/identity.js +14 -0
- package/dist/tools/index.d.ts +1 -0
- package/dist/tools/index.js +3 -0
- package/dist/tools/sandbox.d.ts +2 -269
- package/dist/tools/sandbox.js +10 -741
- package/dist/types.d.ts +1 -0
- package/dist/types.js +1 -0
- package/package.json +2 -1
- package/dist/tools/workspace.d.ts +0 -79
- package/dist/tools/workspace.js +0 -1470
package/dist/tools/sandbox.js
CHANGED
|
@@ -1,7 +1,5 @@
|
|
|
1
|
-
import { spawn } from 'node:child_process';
|
|
2
|
-
import { createHash } from 'node:crypto';
|
|
3
|
-
import { posix } from 'node:path';
|
|
4
1
|
import { tool } from "../types.js";
|
|
2
|
+
import { SandboxError, WORKSPACE_MOUNT } from '@zenera/sandbox';
|
|
5
3
|
// ---------------------------------------------------------------------------
|
|
6
4
|
// Sandbox tools
|
|
7
5
|
//
|
|
@@ -23,741 +21,12 @@ import { tool } from "../types.js";
|
|
|
23
21
|
// whatever front end is driving this — the library only reports, clearly, that
|
|
24
22
|
// the engine did not answer.
|
|
25
23
|
// ---------------------------------------------------------------------------
|
|
26
|
-
/** Where the workspace appears inside the container. */
|
|
27
|
-
export const SANDBOX_MOUNT = '/workspace';
|
|
28
|
-
/** Where background jobs keep their logs. Inside the container, not the host. */
|
|
29
|
-
const JOBS = '/tmp/zenera-jobs';
|
|
30
|
-
/** One command's output is capped, so a `cat` of a log file cannot fill the context. */
|
|
31
|
-
const MAX_OUTPUT = 64 * 1024;
|
|
32
|
-
/** ...and a job's log is read in windows of this many lines. */
|
|
33
|
-
const MAX_LOG_LINES = 400;
|
|
34
|
-
const DEFAULT_IMAGE = 'docker.io/library/python:3.14-slim-bookworm';
|
|
35
|
-
/** The image a project gets when it does not name one. */
|
|
36
|
-
export const DEFAULT_SANDBOX_IMAGE = DEFAULT_IMAGE;
|
|
37
|
-
const DEFAULT_TIMEOUT_MS = 120_000;
|
|
38
|
-
const MAX_TIMEOUT_MS = 3_600_000;
|
|
39
|
-
const DEFAULT_PIDS = 1024;
|
|
40
|
-
/** How long a container gets to stop itself before it is killed. */
|
|
41
|
-
const STOP_GRACE_S = 2;
|
|
42
|
-
/** SIGKILL, which is how the kernel's out-of-memory killer arrives. */
|
|
43
|
-
const KILLED = 137;
|
|
44
|
-
// Standard mode's resource ceilings. Even without the strict profile, an
|
|
45
|
-
// unbounded container can exhaust host cores or memory during runaway builds.
|
|
46
|
-
const DEFAULT_CPUS = 4;
|
|
47
|
-
const DEFAULT_MEMORY = 4096;
|
|
48
|
-
// Strict mode's own defaults. A limit that is only there when someone
|
|
49
|
-
// remembered to write it down is not a limit, so the profile supplies one for
|
|
50
|
-
// each of the four exhaustible things: cores, memory, processes and disk.
|
|
51
|
-
const STRICT_CPUS = 2;
|
|
52
|
-
const STRICT_MEMORY = 2048;
|
|
53
|
-
const STRICT_TMPFS = 'rw,noexec,nosuid,nodev';
|
|
54
|
-
const STRICT_TMP_SIZE = '64m';
|
|
55
24
|
/** The family name config selects the whole set by: `tools: [sandbox:*]`. */
|
|
56
25
|
export const SANDBOX_GROUP = 'sandbox';
|
|
57
|
-
/** A failure the caller can do something about — a missing engine, usually. */
|
|
58
|
-
export class SandboxError extends Error {
|
|
59
|
-
hint;
|
|
60
|
-
constructor(message, hint) {
|
|
61
|
-
super(message);
|
|
62
|
-
this.name = 'SandboxError';
|
|
63
|
-
this.hint = hint;
|
|
64
|
-
}
|
|
65
|
-
}
|
|
66
|
-
export const runProcess = (bin, args, opts = {}) => new Promise((settle, fail) => {
|
|
67
|
-
const max = opts.maxBytes ?? MAX_OUTPUT;
|
|
68
|
-
const out = [];
|
|
69
|
-
const err = [];
|
|
70
|
-
let outSize = 0;
|
|
71
|
-
let errSize = 0;
|
|
72
|
-
let truncated = false;
|
|
73
|
-
let timedOut = false;
|
|
74
|
-
let done = false;
|
|
75
|
-
const child = spawn(bin, [...args], { shell: false, stdio: ['pipe', 'pipe', 'pipe'] });
|
|
76
|
-
const keep = (into, size, chunk) => {
|
|
77
|
-
const room = max - size;
|
|
78
|
-
if (room <= 0) {
|
|
79
|
-
truncated = true;
|
|
80
|
-
return size;
|
|
81
|
-
}
|
|
82
|
-
if (chunk.length > room) {
|
|
83
|
-
truncated = true;
|
|
84
|
-
into.push(chunk.subarray(0, room));
|
|
85
|
-
return max;
|
|
86
|
-
}
|
|
87
|
-
into.push(chunk);
|
|
88
|
-
return size + chunk.length;
|
|
89
|
-
};
|
|
90
|
-
child.stdout.on('data', (c) => (outSize = keep(out, outSize, c)));
|
|
91
|
-
child.stderr.on('data', (c) => (errSize = keep(err, errSize, c)));
|
|
92
|
-
// SIGTERM first so a well-behaved process can flush; SIGKILL after, so
|
|
93
|
-
// one that ignores it cannot hold the turn open forever.
|
|
94
|
-
let hard;
|
|
95
|
-
const stop = () => {
|
|
96
|
-
child.kill('SIGTERM');
|
|
97
|
-
hard = setTimeout(() => child.kill('SIGKILL'), 2000);
|
|
98
|
-
hard.unref();
|
|
99
|
-
};
|
|
100
|
-
const timer = opts.timeoutMs
|
|
101
|
-
? setTimeout(() => {
|
|
102
|
-
timedOut = true;
|
|
103
|
-
stop();
|
|
104
|
-
}, Math.min(opts.timeoutMs, MAX_TIMEOUT_MS))
|
|
105
|
-
: undefined;
|
|
106
|
-
const onAbort = () => stop();
|
|
107
|
-
opts.signal?.addEventListener('abort', onAbort, { once: true });
|
|
108
|
-
const finish = (fn) => {
|
|
109
|
-
if (done) {
|
|
110
|
-
return;
|
|
111
|
-
}
|
|
112
|
-
done = true;
|
|
113
|
-
clearTimeout(timer);
|
|
114
|
-
clearTimeout(hard);
|
|
115
|
-
opts.signal?.removeEventListener('abort', onAbort);
|
|
116
|
-
fn();
|
|
117
|
-
};
|
|
118
|
-
child.on('error', (e) => {
|
|
119
|
-
finish(() => fail(e.code === 'ENOENT'
|
|
120
|
-
? new SandboxError(`${bin} is not installed, or not on PATH`)
|
|
121
|
-
: e));
|
|
122
|
-
});
|
|
123
|
-
child.on('close', (code) => {
|
|
124
|
-
finish(() => settle({
|
|
125
|
-
code: code ?? (timedOut ? 124 : 1),
|
|
126
|
-
stdout: Buffer.concat(out).toString('utf8'),
|
|
127
|
-
stderr: Buffer.concat(err).toString('utf8'),
|
|
128
|
-
truncated,
|
|
129
|
-
timedOut,
|
|
130
|
-
}));
|
|
131
|
-
});
|
|
132
|
-
if (opts.input !== undefined) {
|
|
133
|
-
child.stdin.on('error', () => {
|
|
134
|
-
// A command that exits before reading its script closes the
|
|
135
|
-
// pipe under us. That is the command's answer, not an error.
|
|
136
|
-
});
|
|
137
|
-
child.stdin.end(opts.input);
|
|
138
|
-
}
|
|
139
|
-
else {
|
|
140
|
-
child.stdin.end();
|
|
141
|
-
}
|
|
142
|
-
});
|
|
143
|
-
// ---------------------------------------------------------------------------
|
|
144
|
-
// Reaching the engine at all
|
|
145
|
-
//
|
|
146
|
-
// On macOS and Windows the client is remote: unless it has been pointed at the
|
|
147
|
-
// machine's forwarded endpoint, every invocation opens its own ssh connection
|
|
148
|
-
// into the virtual machine, and sshd refuses new ones past `MaxStartups` — ten
|
|
149
|
-
// by default, with a random drop above that. A wide batch therefore loses
|
|
150
|
-
// calls for a reason that has nothing to do with the command, on a different
|
|
151
|
-
// task each time.
|
|
152
|
-
//
|
|
153
|
-
// A refused connection is the one failure that can be retried without asking
|
|
154
|
-
// what the command was: it happened before authentication, so nothing ran.
|
|
155
|
-
// ---------------------------------------------------------------------------
|
|
156
|
-
const TRANSPORT = /kex_exchange_identification|ssh: handshake failed|ssh: unexpected packet|connection closed by remote host|connection reset by peer|connection refused/i;
|
|
157
|
-
const ATTEMPTS = 4;
|
|
158
|
-
/**
|
|
159
|
-
* `run`, retried while the engine could not be reached at all.
|
|
160
|
-
*
|
|
161
|
-
* Empty stdout is the guard that keeps this from retrying real work: a command
|
|
162
|
-
* that produced output ran, whatever its stderr says afterwards. The wait is
|
|
163
|
-
* jittered because the burst being backed off from is N clients arriving
|
|
164
|
-
* together, and a fixed delay would only reassemble it.
|
|
165
|
-
*/
|
|
166
|
-
export function resilient(run, attempts = ATTEMPTS) {
|
|
167
|
-
return async (bin, args, opts = {}) => {
|
|
168
|
-
for (let n = 1;; n++) {
|
|
169
|
-
const res = await run(bin, args, opts);
|
|
170
|
-
if (n >= attempts ||
|
|
171
|
-
res.code === 0 ||
|
|
172
|
-
res.stdout !== '' ||
|
|
173
|
-
opts.signal?.aborted ||
|
|
174
|
-
!TRANSPORT.test(res.stderr)) {
|
|
175
|
-
return res;
|
|
176
|
-
}
|
|
177
|
-
await new Promise((go) => setTimeout(go, 2 ** n * 50 + Math.random() * 100));
|
|
178
|
-
}
|
|
179
|
-
};
|
|
180
|
-
}
|
|
181
|
-
/**
|
|
182
|
-
* Asked of the container after a kill. Builtins only: a slim image may have no
|
|
183
|
-
* `awk`, and strict hardening leaves nowhere writable to install one. `oom_kill`
|
|
184
|
-
* counts kills in this container's cgroup and no other, which is what separates
|
|
185
|
-
* the two cases. Unreadable values print empty, and the caller reads that as
|
|
186
|
-
* "could not tell".
|
|
187
|
-
*/
|
|
188
|
-
const CGROUP = [
|
|
189
|
-
`peak=; kills=`,
|
|
190
|
-
`read peak < /sys/fs/cgroup/memory.peak 2>/dev/null`,
|
|
191
|
-
`while read -r k v; do [ "$k" = oom_kill ] && kills=$v; done < /sys/fs/cgroup/memory.events 2>/dev/null`,
|
|
192
|
-
`echo "peak=$peak kills=$kills"`,
|
|
193
|
-
].join('\n');
|
|
194
|
-
/**
|
|
195
|
-
* The container, started when it is first needed and not before. A project
|
|
196
|
-
* whose agents never shell out never pays for an image pull, and a session
|
|
197
|
-
* that only ever asks a question never leaves anything behind.
|
|
198
|
-
*/
|
|
199
|
-
export class Sandbox {
|
|
200
|
-
name;
|
|
201
|
-
spec;
|
|
202
|
-
#run;
|
|
203
|
-
#jobs = new Map();
|
|
204
|
-
#ready;
|
|
205
|
-
#created = false;
|
|
206
|
-
/** kills counted in this container's cgroup as of the last probe */
|
|
207
|
-
#kills;
|
|
208
|
-
constructor(opts) {
|
|
209
|
-
this.spec = resolveSpec(opts);
|
|
210
|
-
this.#run = resilient(opts.exec ?? runProcess);
|
|
211
|
-
this.name = containerName(this.spec);
|
|
212
|
-
}
|
|
213
|
-
/** Whether anything was actually started — `dispose` is free when not. */
|
|
214
|
-
get started() {
|
|
215
|
-
return this.#created;
|
|
216
|
-
}
|
|
217
|
-
/**
|
|
218
|
-
* Idempotent, and single-flight: several tool calls in one batch all await
|
|
219
|
-
* the same start rather than racing to create the same container.
|
|
220
|
-
*/
|
|
221
|
-
start() {
|
|
222
|
-
this.#ready ??= this.#bring().catch((err) => {
|
|
223
|
-
// A failed start must not be remembered as a start, or every later
|
|
224
|
-
// call in the session inherits a failure it could have retried.
|
|
225
|
-
this.#ready = undefined;
|
|
226
|
-
throw err;
|
|
227
|
-
});
|
|
228
|
-
return this.#ready;
|
|
229
|
-
}
|
|
230
|
-
async #bring() {
|
|
231
|
-
const status = await this.#podman([
|
|
232
|
-
'container',
|
|
233
|
-
'inspect',
|
|
234
|
-
this.name,
|
|
235
|
-
'--format',
|
|
236
|
-
'{{.State.Status}}',
|
|
237
|
-
]);
|
|
238
|
-
if (status.code === 0) {
|
|
239
|
-
const state = status.stdout.trim();
|
|
240
|
-
if (state !== 'running') {
|
|
241
|
-
await this.#must(['start', this.name], `could not start container ${this.name}`);
|
|
242
|
-
}
|
|
243
|
-
this.#created = true;
|
|
244
|
-
return;
|
|
245
|
-
}
|
|
246
|
-
const made = await this.#podman(this.#createArgs());
|
|
247
|
-
if (made.code !== 0) {
|
|
248
|
-
throw new SandboxError(`could not create container ${this.name}: ${message(made)}`, LOCKS.test(made.stderr) ? locksHint(this.spec.engine) : undefined);
|
|
249
|
-
}
|
|
250
|
-
this.#created = true;
|
|
251
|
-
}
|
|
252
|
-
#createArgs() {
|
|
253
|
-
const s = this.spec;
|
|
254
|
-
const args = ['run', '--detach', '--name', this.name];
|
|
255
|
-
args.push('--label', 'zenera=1', '--label', `zenera.key=${s.key}`);
|
|
256
|
-
args.push('--volume', mount({ host: s.root, at: s.workdir, readOnly: s.readOnly }));
|
|
257
|
-
for (const m of s.mounts) {
|
|
258
|
-
args.push('--volume', mount(m));
|
|
259
|
-
}
|
|
260
|
-
args.push('--workdir', s.workdir);
|
|
261
|
-
args.push('--network', s.network);
|
|
262
|
-
if (s.cpus > 0) {
|
|
263
|
-
args.push('--cpus', String(s.cpus));
|
|
264
|
-
}
|
|
265
|
-
if (s.memory > 0) {
|
|
266
|
-
args.push('--memory', `${s.memory}m`);
|
|
267
|
-
}
|
|
268
|
-
args.push('--pids-limit', String(DEFAULT_PIDS));
|
|
269
|
-
// `no-new-privileges` costs nothing here and closes setuid escalation.
|
|
270
|
-
// Under `standard` the capabilities are deliberately *not* dropped
|
|
271
|
-
// wholesale: installing a package is the ordinary use of this tool, and
|
|
272
|
-
// `--cap-drop=ALL` breaks every package manager there is. The container
|
|
273
|
-
// is the boundary. `strict` makes the opposite trade, below.
|
|
274
|
-
args.push('--security-opt', 'no-new-privileges');
|
|
275
|
-
// Background jobs orphan processes; without an init they accumulate as
|
|
276
|
-
// zombies until the pids limit stops the sandbox dead.
|
|
277
|
-
args.push('--init');
|
|
278
|
-
args.push('--restart', 'no');
|
|
279
|
-
if (s.hardening === 'strict') {
|
|
280
|
-
args.push('--cap-drop', 'ALL');
|
|
281
|
-
// The image's own files become reference material: a command can
|
|
282
|
-
// read a binary and run it, and can write nowhere but the mounts
|
|
283
|
-
// and the tmpfs below.
|
|
284
|
-
args.push('--read-only');
|
|
285
|
-
// `noexec` is safe for the job launcher because a job script is
|
|
286
|
-
// *interpreted* (`/bin/sh <file>`), never executed as a program.
|
|
287
|
-
// `/run` is left to podman's own read-only tmpfs: `--init` mounts
|
|
288
|
-
// catatonit under it and has to be able to exec it.
|
|
289
|
-
args.push('--tmpfs', `/tmp:${STRICT_TMPFS},size=${STRICT_TMP_SIZE}`);
|
|
290
|
-
if (!s.user) {
|
|
291
|
-
// Rootless podman maps container uid 0 to the host account, so
|
|
292
|
-
// the default container root is already unprivileged on the
|
|
293
|
-
// host — but it is uid 0 *inside*, where the setuid binaries
|
|
294
|
-
// are. `keep-id` runs the process as the host's own uid, which
|
|
295
|
-
// is both non-zero and the owner of every bind mount, so the
|
|
296
|
-
// workspace stays writable without a chown.
|
|
297
|
-
args.push('--userns', 'keep-id');
|
|
298
|
-
}
|
|
299
|
-
}
|
|
300
|
-
if (s.user) {
|
|
301
|
-
args.push('--user', s.user);
|
|
302
|
-
}
|
|
303
|
-
for (const [k, v] of Object.entries(s.env)) {
|
|
304
|
-
args.push('--env', `${k}=${v}`);
|
|
305
|
-
}
|
|
306
|
-
// No `=`, and so no value: podman reads each one from its own
|
|
307
|
-
// environment. A key passed this way is not in the argv of a process
|
|
308
|
-
// any user on the machine can list.
|
|
309
|
-
for (const name of s.secrets) {
|
|
310
|
-
if (process.env[name]) {
|
|
311
|
-
args.push('--env', name);
|
|
312
|
-
}
|
|
313
|
-
}
|
|
314
|
-
args.push(s.image, 'sleep', 'infinity');
|
|
315
|
-
return args;
|
|
316
|
-
}
|
|
317
|
-
/**
|
|
318
|
-
* `podman exec` for a command the agent asked for, with the run's own
|
|
319
|
-
* environment. The script still arrives on stdin; when a path has to be
|
|
320
|
-
* extended, the shell that reads it is started by a fixed `-c` line that
|
|
321
|
-
* exports the variable and `exec`s it — built from host-chosen names and
|
|
322
|
-
* paths only, so no text of the agent's is ever part of a parse here.
|
|
323
|
-
*/
|
|
324
|
-
#exec(options = []) {
|
|
325
|
-
const env = Object.entries(this.spec.execEnv).flatMap(([k, v]) => ['--env', `${k}=${v}`]);
|
|
326
|
-
const paths = Object.entries(this.spec.execPaths).filter(([, dirs]) => dirs.length);
|
|
327
|
-
const shell = paths.length
|
|
328
|
-
? [
|
|
329
|
-
'/bin/sh',
|
|
330
|
-
'-c',
|
|
331
|
-
[
|
|
332
|
-
...paths.map(([name, dirs]) => `export ${name}=${quote(dirs.join(':'))}"\${${name}:+:\$${name}}"`),
|
|
333
|
-
'exec /bin/sh -s',
|
|
334
|
-
].join('; '),
|
|
335
|
-
]
|
|
336
|
-
: ['/bin/sh', '-s'];
|
|
337
|
-
return ['exec', '--interactive', ...env, ...options, this.name, ...shell];
|
|
338
|
-
}
|
|
339
|
-
/**
|
|
340
|
-
* Runs one command and waits for it. The script goes down stdin, so no part
|
|
341
|
-
* of it is ever parsed by a shell on this side of the container.
|
|
342
|
-
*/
|
|
343
|
-
async exec(command, opts = {}) {
|
|
344
|
-
await this.start();
|
|
345
|
-
const cwd = this.inside(opts.cwd);
|
|
346
|
-
const timeoutMs = this.#timeout(opts.timeout);
|
|
347
|
-
const startedAt = Date.now();
|
|
348
|
-
const once = () => this.#run(this.spec.engine, this.#exec(['--workdir', cwd]), {
|
|
349
|
-
input: command,
|
|
350
|
-
timeoutMs,
|
|
351
|
-
signal: opts.signal,
|
|
352
|
-
});
|
|
353
|
-
let res = await once();
|
|
354
|
-
if (gone(res)) {
|
|
355
|
-
// podman refused before running anything, so the retry cannot run the command twice.
|
|
356
|
-
await this.#revive(res);
|
|
357
|
-
res = await once();
|
|
358
|
-
}
|
|
359
|
-
return {
|
|
360
|
-
exit_code: res.code,
|
|
361
|
-
stdout: res.stdout,
|
|
362
|
-
stderr: res.stderr,
|
|
363
|
-
truncated: res.truncated || undefined,
|
|
364
|
-
timed_out: res.timedOut || undefined,
|
|
365
|
-
duration_ms: Date.now() - startedAt,
|
|
366
|
-
out_of_memory: await this.#oom(res.code, res.timedOut, opts.signal),
|
|
367
|
-
};
|
|
368
|
-
}
|
|
369
|
-
/**
|
|
370
|
-
* Starts a command and returns. The wrapper writes the log and the exit
|
|
371
|
-
* code to files the container owns, which is what makes the job readable
|
|
372
|
-
* after the `exec` that started it has long returned.
|
|
373
|
-
*/
|
|
374
|
-
async startJob(command, opts = {}) {
|
|
375
|
-
await this.start();
|
|
376
|
-
const cwd = this.inside(opts.cwd);
|
|
377
|
-
const id = jobId();
|
|
378
|
-
// The command reaches the container as a *file*, written by `cat` from
|
|
379
|
-
// stdin. Interpolating it into the launcher script would put user text
|
|
380
|
-
// back into a shell parse, which is the one thing this design avoids.
|
|
381
|
-
const body = await this.#run(this.spec.engine, [
|
|
382
|
-
'exec',
|
|
383
|
-
'--interactive',
|
|
384
|
-
this.name,
|
|
385
|
-
'/bin/sh',
|
|
386
|
-
'-c',
|
|
387
|
-
`mkdir -p ${JOBS} && cat > ${JOBS}/${id}.sh`,
|
|
388
|
-
], { input: command, timeoutMs: 30_000 });
|
|
389
|
-
if (body.code !== 0) {
|
|
390
|
-
throw new SandboxError(`could not write the job: ${message(body)}`);
|
|
391
|
-
}
|
|
392
|
-
// One logical line, because a newline would end the group command and
|
|
393
|
-
// leave the redirection and the `&` on a statement of their own — the
|
|
394
|
-
// job would then run in the foreground of this `exec`, with its output
|
|
395
|
-
// going to the caller instead of the log.
|
|
396
|
-
//
|
|
397
|
-
// `setsid` puts the job in a session of its own so that stopping it can
|
|
398
|
-
// signal a process group rather than one process; a shell without job
|
|
399
|
-
// control leaves background jobs in its own group, and signalling that
|
|
400
|
-
// would take down the `exec` shell with them. It is not required: where
|
|
401
|
-
// it is missing the job still runs, and stopping falls back to the
|
|
402
|
-
// single pid. The leader writes its own pid, since with `setsid` the
|
|
403
|
-
// launching shell's `$!` is no longer the process to signal.
|
|
404
|
-
const inner = `echo $$ > ${JOBS}/${id}.pid; ` +
|
|
405
|
-
`/bin/sh ${JOBS}/${id}.sh; echo $? > ${JOBS}/${id}.exit`;
|
|
406
|
-
const launch = [
|
|
407
|
-
`cd ${quote(cwd)}`,
|
|
408
|
-
`S=; command -v setsid > /dev/null 2>&1 && S=setsid`,
|
|
409
|
-
`$S /bin/sh -c ${quote(inner)} > ${JOBS}/${id}.log 2>&1 < /dev/null &`,
|
|
410
|
-
// The pid file is written by the child, so the launcher waits for
|
|
411
|
-
// it: a read or a stop arriving immediately after must not find
|
|
412
|
-
// the job missing.
|
|
413
|
-
`i=0; while [ ! -s ${JOBS}/${id}.pid ] && [ $i -lt 50 ]; do i=$((i+1)); sleep 0.1; done`,
|
|
414
|
-
].join('\n');
|
|
415
|
-
const started = await this.#run(this.spec.engine, this.#exec(), {
|
|
416
|
-
input: launch,
|
|
417
|
-
timeoutMs: 30_000,
|
|
418
|
-
});
|
|
419
|
-
if (started.code !== 0) {
|
|
420
|
-
throw new SandboxError(`could not start the job: ${message(started)}`);
|
|
421
|
-
}
|
|
422
|
-
const job = { id, command, cwd, startedAt: Date.now() };
|
|
423
|
-
this.#jobs.set(id, job);
|
|
424
|
-
return job;
|
|
425
|
-
}
|
|
426
|
-
/** A window of a job's log, plus whether it is still going. */
|
|
427
|
-
async readJob(id, from = 1) {
|
|
428
|
-
const job = this.#jobs.get(id);
|
|
429
|
-
if (!job) {
|
|
430
|
-
return { error: `no such job: ${id}`, hint: 'ids come from run_command_background' };
|
|
431
|
-
}
|
|
432
|
-
await this.start();
|
|
433
|
-
const first = Math.max(1, Math.trunc(from));
|
|
434
|
-
const script = [
|
|
435
|
-
`cd ${JOBS} || exit 0`,
|
|
436
|
-
`printf 'lines=%s\\n' "$(wc -l < ${id}.log 2>/dev/null || echo 0)"`,
|
|
437
|
-
`if [ -f ${id}.exit ]; then printf 'exit=%s\\n' "$(cat ${id}.exit)"; fi`,
|
|
438
|
-
`printf -- '---\\n'`,
|
|
439
|
-
`tail -n +${first} ${id}.log 2>/dev/null | head -n ${MAX_LOG_LINES}`,
|
|
440
|
-
].join('\n');
|
|
441
|
-
const res = await this.#run(this.spec.engine, ['exec', '--interactive', this.name, '/bin/sh', '-s'], { input: script, timeoutMs: 30_000 });
|
|
442
|
-
const [head, ...rest] = res.stdout.split('\n---\n');
|
|
443
|
-
const meta = Object.fromEntries(head
|
|
444
|
-
.split('\n')
|
|
445
|
-
.filter(Boolean)
|
|
446
|
-
.map((l) => l.split('=', 2)));
|
|
447
|
-
const output = rest.join('\n---\n');
|
|
448
|
-
const lines = Number(meta.lines ?? 0);
|
|
449
|
-
const shown = output ? output.replace(/\n$/, '').split('\n').length : 0;
|
|
450
|
-
const exit = meta.exit === undefined ? undefined : Number(meta.exit);
|
|
451
|
-
// Kept on the job: a second read would find the kill counter unchanged
|
|
452
|
-
// and report this container's own overrun as the machine's doing.
|
|
453
|
-
if (exit === KILLED && !job.oom) {
|
|
454
|
-
job.oom = await this.#oom(exit, false);
|
|
455
|
-
}
|
|
456
|
-
return {
|
|
457
|
-
job_id: id,
|
|
458
|
-
command: job.command,
|
|
459
|
-
running: meta.exit === undefined,
|
|
460
|
-
exit_code: exit,
|
|
461
|
-
duration_ms: Date.now() - job.startedAt,
|
|
462
|
-
start_line: first,
|
|
463
|
-
end_line: first + shown - 1,
|
|
464
|
-
lines,
|
|
465
|
-
truncated: first + shown - 1 < lines || undefined,
|
|
466
|
-
output,
|
|
467
|
-
out_of_memory: job.oom,
|
|
468
|
-
};
|
|
469
|
-
}
|
|
470
|
-
/** Signals a job's whole process group, so its children go too. */
|
|
471
|
-
async stopJob(id) {
|
|
472
|
-
if (!this.#jobs.has(id)) {
|
|
473
|
-
return { error: `no such job: ${id}`, hint: 'ids come from run_command_background' };
|
|
474
|
-
}
|
|
475
|
-
await this.start();
|
|
476
|
-
const script = [
|
|
477
|
-
`pid=$(cat ${JOBS}/${id}.pid 2>/dev/null)`,
|
|
478
|
-
`[ -n "$pid" ] || { echo "already gone"; exit 0; }`,
|
|
479
|
-
`kill -TERM -"$pid" 2>/dev/null || kill -TERM "$pid" 2>/dev/null || true`,
|
|
480
|
-
`sleep 1`,
|
|
481
|
-
`kill -KILL -"$pid" 2>/dev/null || true`,
|
|
482
|
-
`echo stopped`,
|
|
483
|
-
].join('\n');
|
|
484
|
-
const res = await this.#run(this.spec.engine, ['exec', '--interactive', this.name, '/bin/sh', '-s'], { input: script, timeoutMs: 30_000 });
|
|
485
|
-
this.#jobs.delete(id);
|
|
486
|
-
return { job_id: id, stopped: res.code === 0 };
|
|
487
|
-
}
|
|
488
|
-
/**
|
|
489
|
-
* Stops a persisted container and removes an ephemeral one. Stopping
|
|
490
|
-
* rather than removing is what makes `persist` mean anything: a stopped
|
|
491
|
-
* container costs disk, a running one costs the machine's whole budget.
|
|
492
|
-
*/
|
|
493
|
-
async dispose() {
|
|
494
|
-
if (!this.#created) {
|
|
495
|
-
return;
|
|
496
|
-
}
|
|
497
|
-
this.#created = false;
|
|
498
|
-
this.#ready = undefined;
|
|
499
|
-
await this.#podman(this.spec.persist
|
|
500
|
-
? ['stop', '--time', String(STOP_GRACE_S), this.name]
|
|
501
|
-
: ['rm', '--force', '--volumes', this.name]).catch(() => undefined);
|
|
502
|
-
}
|
|
503
|
-
/**
|
|
504
|
-
* A path inside the container, contained to the working directory. Purely
|
|
505
|
-
* lexical, and correctly so: this is the container's path space, not this
|
|
506
|
-
* machine's, and there is nothing here to resolve a symlink against.
|
|
507
|
-
*/
|
|
508
|
-
inside(path) {
|
|
509
|
-
const base = this.spec.workdir;
|
|
510
|
-
if (!path) {
|
|
511
|
-
return base;
|
|
512
|
-
}
|
|
513
|
-
if (path.includes('\0')) {
|
|
514
|
-
throw new SandboxError('path contains a null byte');
|
|
515
|
-
}
|
|
516
|
-
const at = posix.resolve(base, path);
|
|
517
|
-
if (at !== base && !at.startsWith(`${base}/`)) {
|
|
518
|
-
throw new SandboxError(`outside ${base}: ${path}`, `paths are relative to ${base}`);
|
|
519
|
-
}
|
|
520
|
-
return at;
|
|
521
|
-
}
|
|
522
|
-
#timeout(seconds) {
|
|
523
|
-
const wanted = seconds && seconds > 0 ? seconds * 1000 : this.spec.timeout * 1000;
|
|
524
|
-
return Math.min(wanted || DEFAULT_TIMEOUT_MS, MAX_TIMEOUT_MS);
|
|
525
|
-
}
|
|
526
|
-
/**
|
|
527
|
-
* Turns a bare 137 into a reason, by asking the container which cgroup did
|
|
528
|
-
* the killing. Only a kill counted against *this* container is the caller's
|
|
529
|
-
* to fix; the rest is the machine being busy, and telling someone to shrink
|
|
530
|
-
* a command that already fit would send them off after the wrong thing.
|
|
531
|
-
*/
|
|
532
|
-
async #oom(code, timedOut, signal) {
|
|
533
|
-
// A timeout or a cancel kills podman on this side, not the container,
|
|
534
|
-
// and an uncapped container has no limit it could have exceeded.
|
|
535
|
-
if (code !== KILLED || timedOut || signal?.aborted || this.spec.memory <= 0) {
|
|
536
|
-
return undefined;
|
|
537
|
-
}
|
|
538
|
-
const res = await this.#run(this.spec.engine, ['exec', '--interactive', this.name, '/bin/sh', '-s'], { input: CGROUP, timeoutMs: 15_000 }).catch(() => undefined);
|
|
539
|
-
const out = res?.stdout ?? '';
|
|
540
|
-
const peak = Number(/peak=(\d+)/.exec(out)?.[1]);
|
|
541
|
-
const kills = Number(/kills=(\d+)/.exec(out)?.[1]);
|
|
542
|
-
const counted = Number.isFinite(kills);
|
|
543
|
-
// Nothing readable is read as our own doing: that costs one wasted
|
|
544
|
-
// retry, where the other guess costs an agent retrying forever a
|
|
545
|
-
// command that was never going to fit.
|
|
546
|
-
const own = !counted || kills > (this.#kills ?? 0);
|
|
547
|
-
if (counted) {
|
|
548
|
-
this.#kills = kills;
|
|
549
|
-
}
|
|
550
|
-
const limit = this.spec.memory;
|
|
551
|
-
return {
|
|
552
|
-
limit_mib: limit,
|
|
553
|
-
peak_mib: Number.isFinite(peak) ? Math.round(peak / (1024 * 1024)) : undefined,
|
|
554
|
-
retryable: !own,
|
|
555
|
-
hint: own
|
|
556
|
-
? `this container is limited to ${limit} MiB and the command wanted more. ` +
|
|
557
|
-
`Running it again unchanged will end the same way: give the sandbox more ` +
|
|
558
|
-
`memory in the project configuration, or do the work in smaller pieces.`
|
|
559
|
-
: `the machine ran out of memory while this container was inside its ` +
|
|
560
|
-
`${limit} MiB limit, so it was killed for something another container did. ` +
|
|
561
|
-
`The command itself does not need to change, and may work once the machine ` +
|
|
562
|
-
`is less busy.`,
|
|
563
|
-
};
|
|
564
|
-
}
|
|
565
|
-
#podman(args) {
|
|
566
|
-
return this.#run(this.spec.engine, args, { timeoutMs: 120_000 });
|
|
567
|
-
}
|
|
568
|
-
/** The container stopped or vanished under us (machine slept, restarted, or someone removed it). */
|
|
569
|
-
async #revive(res) {
|
|
570
|
-
this.#ready = undefined;
|
|
571
|
-
try {
|
|
572
|
-
await this.start();
|
|
573
|
-
}
|
|
574
|
-
catch (err) {
|
|
575
|
-
throw new SandboxError(`the sandbox container ${this.name} stopped (${message(res)}) and could not be restarted: ` +
|
|
576
|
-
(err instanceof Error ? err.message : String(err)), `the ${this.spec.engine} machine may have stopped or restarted — check \`${this.spec.engine} machine list\`, ` +
|
|
577
|
-
`start it with \`${this.spec.engine} machine start\`, then retry`);
|
|
578
|
-
}
|
|
579
|
-
}
|
|
580
|
-
async #must(args, what) {
|
|
581
|
-
const res = await this.#podman(args);
|
|
582
|
-
if (res.code !== 0) {
|
|
583
|
-
throw new SandboxError(`${what}: ${message(res)}`);
|
|
584
|
-
}
|
|
585
|
-
return res;
|
|
586
|
-
}
|
|
587
|
-
}
|
|
588
|
-
function mount(m) {
|
|
589
|
-
return `${m.host}:${m.at}${m.readOnly ? ':ro' : ''}`;
|
|
590
|
-
}
|
|
591
|
-
function message(res) {
|
|
592
|
-
return (res.stderr.trim() || res.stdout.trim() || `exit ${res.code}`).split('\n')[0];
|
|
593
|
-
}
|
|
594
|
-
/** podman's words for "every lock is taken": `allocating lock … exceeded num_locks (2048)`. */
|
|
595
|
-
const LOCKS = /exceeded num_locks|allocating lock/i;
|
|
596
|
-
/**
|
|
597
|
-
* A stopped container holds a lock as surely as a running one, and a
|
|
598
|
-
* persisted sandbox is stopped, never removed — so they pile up one per
|
|
599
|
-
* session until the engine can create nothing at all, for anyone.
|
|
600
|
-
*/
|
|
601
|
-
function locksHint(engine) {
|
|
602
|
-
return (`the ${engine} engine has no locks left: every container it holds, stopped ones ` +
|
|
603
|
-
`included, takes one. Remove the stopped sandbox containers with ` +
|
|
604
|
-
`\`${engine} container prune --force --filter label=zenera=1\`, then retry`);
|
|
605
|
-
}
|
|
606
|
-
/** podman's own exit code for "could not exec at all", with the two reasons that mean the container is not there to exec in. */
|
|
607
|
-
function gone(res) {
|
|
608
|
-
return (res.code === 125 &&
|
|
609
|
-
/can only create exec sessions on running containers|container state improper|no such container/i.test(res.stderr));
|
|
610
|
-
}
|
|
611
|
-
/** Only ever applied to paths this module derived, never to a model's text. */
|
|
612
|
-
function quote(s) {
|
|
613
|
-
return `'${s.replaceAll("'", `'\\''`)}'`;
|
|
614
|
-
}
|
|
615
|
-
function jobId() {
|
|
616
|
-
return `job-${createHash('sha256').update(`${Date.now()}${Math.random()}`).digest('hex').slice(0, 6)}`;
|
|
617
|
-
}
|
|
618
|
-
function resolveSpec(opts) {
|
|
619
|
-
const workdir = opts.workdir ?? SANDBOX_MOUNT;
|
|
620
|
-
if (!posix.isAbsolute(workdir)) {
|
|
621
|
-
throw new SandboxError(`sandbox workdir must be absolute: ${workdir}`);
|
|
622
|
-
}
|
|
623
|
-
const hardening = opts.hardening ?? 'standard';
|
|
624
|
-
const strict = hardening === 'strict';
|
|
625
|
-
for (const name of [...Object.keys(opts.execEnv ?? {}), ...Object.keys(opts.execPaths ?? {})]) {
|
|
626
|
-
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) {
|
|
627
|
-
throw new SandboxError(`not a variable name: ${JSON.stringify(name)}`);
|
|
628
|
-
}
|
|
629
|
-
}
|
|
630
|
-
return {
|
|
631
|
-
root: opts.root,
|
|
632
|
-
key: opts.key,
|
|
633
|
-
image: opts.image ?? DEFAULT_IMAGE,
|
|
634
|
-
cpus: opts.cpus ?? (strict ? STRICT_CPUS : DEFAULT_CPUS),
|
|
635
|
-
memory: opts.memory ?? (strict ? STRICT_MEMORY : DEFAULT_MEMORY),
|
|
636
|
-
explicitCpus: opts.cpus !== undefined,
|
|
637
|
-
explicitMemory: opts.memory !== undefined,
|
|
638
|
-
network: opts.network ?? (strict ? 'none' : 'bridge'),
|
|
639
|
-
workdir,
|
|
640
|
-
timeout: opts.timeout ?? DEFAULT_TIMEOUT_MS / 1000,
|
|
641
|
-
hardening,
|
|
642
|
-
user: opts.user,
|
|
643
|
-
persist: opts.persist ?? false,
|
|
644
|
-
env: opts.env ?? {},
|
|
645
|
-
secrets: opts.secrets ?? [],
|
|
646
|
-
readOnly: opts.readOnly ?? false,
|
|
647
|
-
mounts: opts.mounts ?? [],
|
|
648
|
-
engine: opts.engine ?? 'podman',
|
|
649
|
-
execEnv: opts.execEnv ?? {},
|
|
650
|
-
execPaths: opts.execPaths ?? {},
|
|
651
|
-
};
|
|
652
|
-
}
|
|
653
|
-
/**
|
|
654
|
-
* What a spec's ceilings come to, for a report that has no container to ask.
|
|
655
|
-
*
|
|
656
|
-
* It exists so `zen sandbox status` cannot disagree with what a run actually
|
|
657
|
-
* applies: the defaults are stated once, here and in `resolveSpec`, and
|
|
658
|
-
* nothing outside this module repeats them.
|
|
659
|
-
*/
|
|
660
|
-
export function sandboxLimits(spec = {}) {
|
|
661
|
-
const hardening = spec.hardening ?? 'standard';
|
|
662
|
-
const strict = hardening === 'strict';
|
|
663
|
-
return {
|
|
664
|
-
memory: spec.memory ?? (strict ? STRICT_MEMORY : DEFAULT_MEMORY),
|
|
665
|
-
cpus: spec.cpus ?? (strict ? STRICT_CPUS : DEFAULT_CPUS),
|
|
666
|
-
hardening,
|
|
667
|
-
declared: spec.memory !== undefined || spec.cpus !== undefined,
|
|
668
|
-
};
|
|
669
|
-
}
|
|
670
|
-
/**
|
|
671
|
-
* The container's name is a function of its configuration. Change the image
|
|
672
|
-
* and a new container appears rather than an old one quietly persisting with
|
|
673
|
-
* the wrong rootfs — which is the failure mode `persist` would otherwise have.
|
|
674
|
-
*
|
|
675
|
-
* Secrets contribute their names and not their values: what a container is
|
|
676
|
-
* depends on which credentials reach it, not on what they happen to say today,
|
|
677
|
-
* and hashing the values would throw away a persisted container's filesystem
|
|
678
|
-
* every time a key was rotated.
|
|
679
|
-
*/
|
|
680
|
-
function containerName(spec) {
|
|
681
|
-
// Unconfigured cpus and memory hash 0 under standard and strict's own
|
|
682
|
-
// defaults under strict, so introducing defaults did not rename every
|
|
683
|
-
// existing container.
|
|
684
|
-
const hashCpus = spec.explicitCpus ? spec.cpus : spec.hardening === 'strict' ? STRICT_CPUS : 0;
|
|
685
|
-
const hashMemory = spec.explicitMemory
|
|
686
|
-
? spec.memory
|
|
687
|
-
: spec.hardening === 'strict'
|
|
688
|
-
? STRICT_MEMORY
|
|
689
|
-
: 0;
|
|
690
|
-
const digest = createHash('sha256')
|
|
691
|
-
.update(JSON.stringify([
|
|
692
|
-
spec.root,
|
|
693
|
-
spec.image,
|
|
694
|
-
hashCpus,
|
|
695
|
-
hashMemory,
|
|
696
|
-
spec.network,
|
|
697
|
-
spec.workdir,
|
|
698
|
-
spec.user ?? null,
|
|
699
|
-
spec.readOnly,
|
|
700
|
-
spec.mounts,
|
|
701
|
-
Object.entries(spec.env).sort(),
|
|
702
|
-
[...spec.secrets].sort(),
|
|
703
|
-
// Appended only when it is set, so adding the profile did not
|
|
704
|
-
// rename every container that existed before it.
|
|
705
|
-
...(spec.hardening === 'strict' ? ['strict'] : []),
|
|
706
|
-
]))
|
|
707
|
-
.digest('hex')
|
|
708
|
-
.slice(0, 10);
|
|
709
|
-
const key = spec.key
|
|
710
|
-
.toLowerCase()
|
|
711
|
-
.replace(/[^a-z0-9]+/g, '-')
|
|
712
|
-
.replace(/^-|-$/g, '');
|
|
713
|
-
return `zn-${key || 'session'}-${digest}`;
|
|
714
|
-
}
|
|
715
|
-
// ---------------------------------------------------------------------------
|
|
716
|
-
// One container per configuration
|
|
717
|
-
//
|
|
718
|
-
// Agents share a sandbox by default, and that is usually what an author means:
|
|
719
|
-
// they already share the workspace, and a hand-off is supposed to be
|
|
720
|
-
// continuous — whatever the first agent installed should still be there when
|
|
721
|
-
// the second one takes over.
|
|
722
|
-
//
|
|
723
|
-
// It stops being what they mean the moment two agents need different images.
|
|
724
|
-
// So the tool object stays single — one name, one schema, one prompt-cache
|
|
725
|
-
// prefix — and picks its container from `tc.agent` at call time. Two agents
|
|
726
|
-
// that resolve to the same spec still share one container, because the name is
|
|
727
|
-
// derived from the spec rather than from who asked.
|
|
728
|
-
// ---------------------------------------------------------------------------
|
|
729
|
-
export class SandboxPool {
|
|
730
|
-
#base;
|
|
731
|
-
#agents;
|
|
732
|
-
#boxes = new Map();
|
|
733
|
-
constructor(opts) {
|
|
734
|
-
const { agents, ...base } = opts;
|
|
735
|
-
this.#base = base;
|
|
736
|
-
this.#agents = agents ?? {};
|
|
737
|
-
}
|
|
738
|
-
for(agent) {
|
|
739
|
-
const override = agent ? this.#agents[agent] : undefined;
|
|
740
|
-
const box = new Sandbox(override ? { ...this.#base, ...override } : this.#base);
|
|
741
|
-
const existing = this.#boxes.get(box.name);
|
|
742
|
-
if (existing) {
|
|
743
|
-
return existing;
|
|
744
|
-
}
|
|
745
|
-
this.#boxes.set(box.name, box);
|
|
746
|
-
return box;
|
|
747
|
-
}
|
|
748
|
-
/** The containers that were actually started, for a status line. */
|
|
749
|
-
get running() {
|
|
750
|
-
return [...this.#boxes.values()].filter((b) => b.started);
|
|
751
|
-
}
|
|
752
|
-
async dispose() {
|
|
753
|
-
await Promise.all([...this.#boxes.values()].map((b) => b.dispose()));
|
|
754
|
-
}
|
|
755
|
-
}
|
|
756
26
|
// ---------------------------------------------------------------------------
|
|
757
27
|
// The tools
|
|
758
28
|
// ---------------------------------------------------------------------------
|
|
759
|
-
export function sandboxTools(
|
|
760
|
-
const pool = opts instanceof SandboxPool ? opts : new SandboxPool(opts);
|
|
29
|
+
export function sandboxTools(sandbox) {
|
|
761
30
|
const where = {
|
|
762
31
|
type: 'object',
|
|
763
32
|
properties: {
|
|
@@ -767,7 +36,7 @@ export function sandboxTools(opts) {
|
|
|
767
36
|
},
|
|
768
37
|
cwd: {
|
|
769
38
|
type: 'string',
|
|
770
|
-
description: `Directory to run in, relative to ${
|
|
39
|
+
description: `Directory to run in, relative to ${WORKSPACE_MOUNT}.`,
|
|
771
40
|
},
|
|
772
41
|
},
|
|
773
42
|
required: ['command'],
|
|
@@ -777,7 +46,7 @@ export function sandboxTools(opts) {
|
|
|
777
46
|
name: 'run_command',
|
|
778
47
|
group: SANDBOX_GROUP,
|
|
779
48
|
description: 'Runs a shell command in a Linux container and waits for it to finish. The ' +
|
|
780
|
-
`workspace is mounted at ${
|
|
49
|
+
`workspace is mounted at ${WORKSPACE_MOUNT} and is the working directory, so files you ` +
|
|
781
50
|
'read and write here are the same files the file tools see. Everything ' +
|
|
782
51
|
'else is throwaway. Use this for builds, tests, and package installs; use ' +
|
|
783
52
|
'run_command_background for anything that does not end on its own, such as a ' +
|
|
@@ -789,7 +58,7 @@ export function sandboxTools(opts) {
|
|
|
789
58
|
timeout: { type: 'integer', description: 'Seconds to allow before killing it.' },
|
|
790
59
|
},
|
|
791
60
|
},
|
|
792
|
-
execute: (args, tc) => guard(() =>
|
|
61
|
+
execute: (args, tc) => guard(() => sandbox.exec(args.command, {
|
|
793
62
|
cwd: args.cwd,
|
|
794
63
|
timeout: args.timeout,
|
|
795
64
|
signal: tc.signal,
|
|
@@ -803,10 +72,10 @@ export function sandboxTools(opts) {
|
|
|
803
72
|
'stop_command. Use this for servers, watchers, and anything you want to keep ' +
|
|
804
73
|
'running while you do something else.',
|
|
805
74
|
parameters: where,
|
|
806
|
-
execute: (args
|
|
807
|
-
const
|
|
75
|
+
execute: (args) => guard(async () => {
|
|
76
|
+
const id = await sandbox.startJob(args.command, { cwd: args.cwd });
|
|
808
77
|
return {
|
|
809
|
-
job_id:
|
|
78
|
+
job_id: id,
|
|
810
79
|
started: true,
|
|
811
80
|
hint: 'read_command_output shows what it has printed so far',
|
|
812
81
|
};
|
|
@@ -826,7 +95,7 @@ export function sandboxTools(opts) {
|
|
|
826
95
|
required: ['job_id'],
|
|
827
96
|
additionalProperties: false,
|
|
828
97
|
},
|
|
829
|
-
execute: (args
|
|
98
|
+
execute: (args) => guard(() => sandbox.readJob(args.job_id, args.start_line)),
|
|
830
99
|
});
|
|
831
100
|
const stop = tool({
|
|
832
101
|
name: 'stop_command',
|
|
@@ -838,7 +107,7 @@ export function sandboxTools(opts) {
|
|
|
838
107
|
required: ['job_id'],
|
|
839
108
|
additionalProperties: false,
|
|
840
109
|
},
|
|
841
|
-
execute: (args
|
|
110
|
+
execute: (args) => guard(() => sandbox.stopJob(args.job_id)),
|
|
842
111
|
});
|
|
843
112
|
return [runCommand, runBackground, readOutput, stop];
|
|
844
113
|
}
|