@cogitator-ai/bridge 0.2.0 → 0.4.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.
Files changed (116) hide show
  1. package/README.md +242 -8
  2. package/dist/adapter.d.ts +130 -0
  3. package/dist/adapter.d.ts.map +1 -0
  4. package/dist/adapter.js +2 -0
  5. package/dist/adapter.js.map +1 -0
  6. package/dist/adapters/claude.d.ts +145 -0
  7. package/dist/adapters/claude.d.ts.map +1 -0
  8. package/dist/adapters/claude.js +537 -0
  9. package/dist/adapters/claude.js.map +1 -0
  10. package/dist/adapters/codex.d.ts +71 -0
  11. package/dist/adapters/codex.d.ts.map +1 -0
  12. package/dist/adapters/codex.js +379 -0
  13. package/dist/adapters/codex.js.map +1 -0
  14. package/dist/adapters/exec.d.ts +70 -0
  15. package/dist/adapters/exec.d.ts.map +1 -0
  16. package/dist/adapters/exec.js +161 -0
  17. package/dist/adapters/exec.js.map +1 -0
  18. package/dist/adapters/hosted.d.ts +168 -0
  19. package/dist/adapters/hosted.d.ts.map +1 -0
  20. package/dist/adapters/hosted.js +361 -0
  21. package/dist/adapters/hosted.js.map +1 -0
  22. package/dist/adapters/tools-server.d.ts +21 -0
  23. package/dist/adapters/tools-server.d.ts.map +1 -0
  24. package/dist/adapters/tools-server.js +19 -0
  25. package/dist/adapters/tools-server.js.map +1 -0
  26. package/dist/client.d.ts +9 -2
  27. package/dist/client.d.ts.map +1 -1
  28. package/dist/client.js +17 -3
  29. package/dist/client.js.map +1 -1
  30. package/dist/dispatcher.d.ts +69 -17
  31. package/dist/dispatcher.d.ts.map +1 -1
  32. package/dist/dispatcher.js +243 -17
  33. package/dist/dispatcher.js.map +1 -1
  34. package/dist/host.d.ts +1 -1
  35. package/dist/host.d.ts.map +1 -1
  36. package/dist/index.d.ts +18 -3
  37. package/dist/index.d.ts.map +1 -1
  38. package/dist/index.js +9 -1
  39. package/dist/index.js.map +1 -1
  40. package/dist/inputs.d.ts +40 -1
  41. package/dist/inputs.d.ts.map +1 -1
  42. package/dist/inputs.js +25 -2
  43. package/dist/inputs.js.map +1 -1
  44. package/dist/paths.d.ts +6 -0
  45. package/dist/paths.d.ts.map +1 -1
  46. package/dist/paths.js +19 -0
  47. package/dist/paths.js.map +1 -1
  48. package/dist/protocol.d.ts +5 -0
  49. package/dist/protocol.d.ts.map +1 -1
  50. package/dist/protocol.js +5 -0
  51. package/dist/protocol.js.map +1 -1
  52. package/dist/server.d.ts.map +1 -1
  53. package/dist/server.js +6 -1
  54. package/dist/server.js.map +1 -1
  55. package/dist/setup/claude.d.ts +53 -0
  56. package/dist/setup/claude.d.ts.map +1 -0
  57. package/dist/setup/claude.js +261 -0
  58. package/dist/setup/claude.js.map +1 -0
  59. package/dist/setup/codex.d.ts +22 -0
  60. package/dist/setup/codex.d.ts.map +1 -0
  61. package/dist/setup/codex.js +95 -0
  62. package/dist/setup/codex.js.map +1 -0
  63. package/dist/setup/files.d.ts +22 -0
  64. package/dist/setup/files.d.ts.map +1 -0
  65. package/dist/setup/files.js +86 -0
  66. package/dist/setup/files.js.map +1 -0
  67. package/dist/setup/index.d.ts +6 -0
  68. package/dist/setup/index.d.ts.map +1 -0
  69. package/dist/setup/index.js +3 -0
  70. package/dist/setup/index.js.map +1 -0
  71. package/dist/setup/setup.d.ts +52 -0
  72. package/dist/setup/setup.d.ts.map +1 -0
  73. package/dist/setup/setup.js +2 -0
  74. package/dist/setup/setup.js.map +1 -0
  75. package/dist/testing/conformance.d.ts +65 -0
  76. package/dist/testing/conformance.d.ts.map +1 -0
  77. package/dist/testing/conformance.js +217 -0
  78. package/dist/testing/conformance.js.map +1 -0
  79. package/dist/testing/fake-harnesses.d.ts +121 -0
  80. package/dist/testing/fake-harnesses.d.ts.map +1 -0
  81. package/dist/testing/fake-harnesses.js +303 -0
  82. package/dist/testing/fake-harnesses.js.map +1 -0
  83. package/dist/testing/index.d.ts +5 -0
  84. package/dist/testing/index.d.ts.map +1 -0
  85. package/dist/testing/index.js +3 -0
  86. package/dist/testing/index.js.map +1 -0
  87. package/dist/tools/caller.d.ts +39 -0
  88. package/dist/tools/caller.d.ts.map +1 -0
  89. package/dist/tools/caller.js +92 -0
  90. package/dist/tools/caller.js.map +1 -0
  91. package/dist/tools/guidance.d.ts +33 -0
  92. package/dist/tools/guidance.d.ts.map +1 -0
  93. package/dist/tools/guidance.js +92 -0
  94. package/dist/tools/guidance.js.map +1 -0
  95. package/dist/tools/index.d.ts +27 -0
  96. package/dist/tools/index.d.ts.map +1 -0
  97. package/dist/tools/index.js +24 -0
  98. package/dist/tools/index.js.map +1 -0
  99. package/dist/tools/tools.d.ts +38 -0
  100. package/dist/tools/tools.d.ts.map +1 -0
  101. package/dist/tools/tools.js +354 -0
  102. package/dist/tools/tools.js.map +1 -0
  103. package/dist/types.d.ts +3 -39
  104. package/dist/types.d.ts.map +1 -1
  105. package/dist/types.js +2 -0
  106. package/dist/types.js.map +1 -1
  107. package/dist/waiter.d.ts +36 -0
  108. package/dist/waiter.d.ts.map +1 -0
  109. package/dist/waiter.js +92 -0
  110. package/dist/waiter.js.map +1 -0
  111. package/fakes/claude.mjs +715 -0
  112. package/fakes/codex.mjs +571 -0
  113. package/fakes/lib.mjs +585 -0
  114. package/fakes/mcp.mjs +151 -0
  115. package/fakes/sandbox.mjs +84 -0
  116. package/package.json +19 -1
package/fakes/lib.mjs ADDED
@@ -0,0 +1,585 @@
1
+ /**
2
+ * Shared code of the fake `claude` and `codex` executables the bridge tests run in place of the
3
+ * real command lines: state guarded by FAKE_HARNESS_HOME, atomic files, message spools, locks,
4
+ * child shells, the scripted model and the life cycle of the processes a fake leaves running.
5
+ */
6
+ import { spawn } from 'node:child_process';
7
+ import {
8
+ appendFileSync,
9
+ existsSync,
10
+ linkSync,
11
+ mkdirSync,
12
+ readFileSync,
13
+ readdirSync,
14
+ realpathSync,
15
+ renameSync,
16
+ rmSync,
17
+ writeFileSync,
18
+ } from 'node:fs';
19
+ import { dirname, join, relative, resolve, sep } from 'node:path';
20
+ import { setTimeout as sleep } from 'node:timers/promises';
21
+
22
+ export { sleep };
23
+
24
+ /** How often a fake looks again at a spool, a lock or a process it waits for */
25
+ export const POLL_MS = 25;
26
+
27
+ const RUN_TIMEOUT_MS = 30_000;
28
+ const STOP_GRACE_MS = 5_000;
29
+ const DEFAULT_MAX_LIFE_MS = 120_000;
30
+ const STATE_WATCH_MS = 100;
31
+ const STOP_SIGNALS = ['SIGTERM', 'SIGINT'];
32
+
33
+ /** A failure the command reports on stderr together with its exit code */
34
+ export class CliError extends Error {
35
+ /**
36
+ * @param {string} message
37
+ * @param {number} [code]
38
+ */
39
+ constructor(message, code = 1) {
40
+ super(message);
41
+ this.code = code;
42
+ }
43
+ }
44
+
45
+ /** Arguments a fake does not imitate, reported with exit code 64 */
46
+ export class Unsupported extends Error {}
47
+
48
+ /**
49
+ * The folder one fake keeps its state in. Throws without FAKE_HARNESS_HOME, so that a fake never
50
+ * touches a real `~/.claude` or `~/.codex`.
51
+ * @param {string} name `claude` or `codex`
52
+ */
53
+ export function stateRoot(name) {
54
+ const home = process.env.FAKE_HARNESS_HOME;
55
+ if (!home) {
56
+ throw new CliError(
57
+ `fake ${name}: FAKE_HARNESS_HOME is not set, refusing to touch a real home folder`,
58
+ 2
59
+ );
60
+ }
61
+ return resolve(home, name);
62
+ }
63
+
64
+ /**
65
+ * Runs a command of a fake. Failures end up on stderr with their exit code, and the process ends
66
+ * by itself afterwards, so that everything written reaches a reader on a pipe.
67
+ * @param {string} name `claude` or `codex`
68
+ * @param {(argv: string[]) => Promise<void>} main
69
+ */
70
+ export async function runCli(name, main) {
71
+ const argv = process.argv.slice(2);
72
+ try {
73
+ stateRoot(name);
74
+ await main(argv);
75
+ } catch (error) {
76
+ const failure =
77
+ error instanceof Unsupported
78
+ ? new CliError(`fake ${name}: unsupported: ${argv.join(' ')}`, 64)
79
+ : error;
80
+ if (!(failure instanceof CliError)) throw failure;
81
+ process.stderr.write(`${failure.message}\n`);
82
+ process.exitCode = failure.code;
83
+ }
84
+ }
85
+
86
+ /**
87
+ * Writes a line to stdout and resolves once it left the process: a reader sees it before
88
+ * anything that happens next.
89
+ * @param {string} text
90
+ */
91
+ export function print(text) {
92
+ return new Promise((done) => process.stdout.write(`${text}\n`, () => done()));
93
+ }
94
+
95
+ /** @typedef {{ key: string, takesValue: boolean, repeats?: boolean, greedy?: boolean }} Flag */
96
+
97
+ /** @param {string} key @returns {Flag} */
98
+ export const flag = (key) => ({ key, takesValue: false });
99
+
100
+ /** @param {string} key @returns {Flag} */
101
+ export const option = (key) => ({ key, takesValue: true });
102
+
103
+ /** An option that may be given several times: its values come as an array. @param {string} key @returns {Flag} */
104
+ export const repeated = (key) => ({ key, takesValue: true, repeats: true });
105
+
106
+ /**
107
+ * An option that takes every argument after it up to the next option, such as
108
+ * `--mcp-config <configs...>` of Claude Code: its values come as an array. A positional that
109
+ * follows it is one of its values, not a positional.
110
+ * @param {string} key
111
+ * @returns {Flag}
112
+ */
113
+ export const several = (key) => ({ key, takesValue: true, repeats: true, greedy: true });
114
+
115
+ /**
116
+ * Splits arguments into option values and positionals. An option that takes a value consumes
117
+ * the next argument whatever it looks like, `--name=value` works for long names, `--` ends the
118
+ * options and a lone `-` is a positional. An option made with {@link several} goes on to take
119
+ * the arguments after its first value until one starts with `-`. An unknown option is
120
+ * {@link Unsupported}.
121
+ * @param {string[]} argv
122
+ * @param {Record<string, Flag>} flags by the name on the command line, such as `--json` or `-C`
123
+ * @returns {{ values: Record<string, string | string[] | true>, positionals: string[] }}
124
+ */
125
+ export function parseArgs(argv, flags) {
126
+ const values = {};
127
+ const positionals = [];
128
+ const rest = [...argv];
129
+ while (rest.length > 0) {
130
+ const arg = rest.shift();
131
+ if (arg === '--') positionals.push(...rest.splice(0));
132
+ else if (arg === '-' || !arg.startsWith('-')) positionals.push(arg);
133
+ else {
134
+ const { key, value, repeats, greedy } = readOption(arg, rest, flags);
135
+ if (!repeats) values[key] = value;
136
+ else {
137
+ const list = (values[key] ??= []);
138
+ list.push(value);
139
+ while (greedy && rest.length > 0 && !rest[0].startsWith('-')) list.push(rest.shift());
140
+ }
141
+ }
142
+ }
143
+ return { values, positionals };
144
+ }
145
+
146
+ function readOption(arg, rest, flags) {
147
+ const cut = arg.startsWith('--') ? arg.indexOf('=') : -1;
148
+ const name = cut === -1 ? arg : arg.slice(0, cut);
149
+ const inline = cut === -1 ? undefined : arg.slice(cut + 1);
150
+ if (!Object.hasOwn(flags, name)) throw new Unsupported();
151
+ const { key, takesValue, repeats, greedy } = flags[name];
152
+ if (!takesValue) {
153
+ if (inline !== undefined) throw new Unsupported();
154
+ return { key, value: true };
155
+ }
156
+ const value = inline ?? rest.shift();
157
+ if (value === undefined) throw new Unsupported();
158
+ return { key, value, repeats, greedy };
159
+ }
160
+
161
+ /**
162
+ * The comma list of an environment variable such as FAKE_CLAUDE_MISSING.
163
+ * @param {string} variable
164
+ * @returns {Set<string>}
165
+ */
166
+ export function listedIn(variable) {
167
+ const items = (process.env[variable] ?? '').split(',').map((item) => item.trim());
168
+ return new Set(items.filter(Boolean));
169
+ }
170
+
171
+ /**
172
+ * A help text without the lines of the features an imitated old version lacks.
173
+ * @param {(string | [feature: string, line: string])[]} lines
174
+ * @param {Set<string>} missing
175
+ */
176
+ export function renderHelp(lines, missing) {
177
+ return lines
178
+ .filter((line) => typeof line === 'string' || !missing.has(line[0]))
179
+ .map((line) => (typeof line === 'string' ? line : line[1]))
180
+ .join('\n');
181
+ }
182
+
183
+ /** @param {string} path the absolute path with links resolved, as `process.cwd()` reports it */
184
+ export function canonical(path) {
185
+ const absolute = resolve(path);
186
+ try {
187
+ return realpathSync(absolute);
188
+ } catch {
189
+ return absolute;
190
+ }
191
+ }
192
+
193
+ /** @returns {boolean} whether `folder` is `parent` or lies below it */
194
+ export function isWithin(folder, parent) {
195
+ const hops = relative(canonical(parent), canonical(folder));
196
+ return hops !== '..' && !hops.startsWith(`..${sep}`);
197
+ }
198
+
199
+ /** @returns {boolean} whether an id is safe as a file name inside a state folder */
200
+ export function isStateName(id) {
201
+ return /^[\w-]+$/.test(id);
202
+ }
203
+
204
+ function unlessMissing(read, fallback) {
205
+ try {
206
+ return read();
207
+ } catch (error) {
208
+ if (error.code === 'ENOENT') return fallback;
209
+ throw error;
210
+ }
211
+ }
212
+
213
+ /** @returns the parsed file, or `fallback` when it does not exist */
214
+ export function readJson(file, fallback) {
215
+ return unlessMissing(() => JSON.parse(readFileSync(file, 'utf8')), fallback);
216
+ }
217
+
218
+ /** Replaces a state file in one step: readers see the old content or the new, never a part */
219
+ export function writeJson(file, value) {
220
+ mkdirSync(dirname(file), { recursive: true });
221
+ const draft = `${file}.${process.pid}.tmp`;
222
+ writeFileSync(draft, JSON.stringify(value, null, 2));
223
+ renameSync(draft, file);
224
+ }
225
+
226
+ /**
227
+ * Merges fields into a state file, `undefined` drops a field. A file that is gone stays gone.
228
+ * @returns the new content, or `undefined` when the file does not exist
229
+ */
230
+ export function patchJson(file, patch) {
231
+ const current = readJson(file);
232
+ if (current === undefined) return undefined;
233
+ const next = { ...current, ...patch };
234
+ writeJson(file, next);
235
+ return next;
236
+ }
237
+
238
+ /** @returns {object[]} every record (`*.json`) of a state folder */
239
+ export function listRecords(dir) {
240
+ return unlessMissing(() => readdirSync(dir), [])
241
+ .filter((name) => name.endsWith('.json'))
242
+ .map((name) => readJson(join(dir, name)))
243
+ .filter((record) => record !== undefined);
244
+ }
245
+
246
+ /** Resolves with a record another process is about to write, or `undefined` when it never comes */
247
+ export async function awaitJson(file) {
248
+ const deadline = Date.now() + STOP_GRACE_MS;
249
+ while (!existsSync(file)) {
250
+ if (Date.now() >= deadline) return undefined;
251
+ await sleep(POLL_MS);
252
+ }
253
+ return readJson(file);
254
+ }
255
+
256
+ let enqueued = 0;
257
+
258
+ /**
259
+ * Adds a message to a spool folder as one file. Names sort by arrival time, a message shows up
260
+ * under its name only when it is complete.
261
+ */
262
+ export function enqueue(dir, message) {
263
+ mkdirSync(dir, { recursive: true });
264
+ const stamp = [Date.now(), process.pid, enqueued++].map((part) => String(part).padStart(15, '0'));
265
+ const name = `${stamp.join('-')}.json`;
266
+ writeFileSync(join(dir, `.${name}`), JSON.stringify(message));
267
+ renameSync(join(dir, `.${name}`), join(dir, name));
268
+ }
269
+
270
+ /** @returns {string[]} the names of the messages waiting in a spool folder, oldest first */
271
+ export function pending(dir) {
272
+ return unlessMissing(() => readdirSync(dir), [])
273
+ .filter((name) => !name.startsWith('.'))
274
+ .sort();
275
+ }
276
+
277
+ /**
278
+ * Takes the oldest message out of a spool folder. It is renamed away first, so no message is
279
+ * taken twice even when several processes look at one folder.
280
+ * @returns the message, or `undefined` when nothing waits
281
+ */
282
+ export function takeNext(dir) {
283
+ const [name] = pending(dir);
284
+ if (name === undefined) return undefined;
285
+ const taken = join(dir, `.taken-${process.pid}-${name}`);
286
+ return unlessMissing(() => {
287
+ renameSync(join(dir, name), taken);
288
+ const message = JSON.parse(readFileSync(taken, 'utf8'));
289
+ rmSync(taken);
290
+ return message;
291
+ }, undefined);
292
+ }
293
+
294
+ /** Lock files this process holds, released when it stops */
295
+ const heldLocks = new Set();
296
+
297
+ /**
298
+ * Tries to take a lock file. The file appears with the pid of its holder already in it, and a
299
+ * lock whose holder died is cleared for the next attempt.
300
+ * @returns {boolean} whether this process holds the lock now
301
+ */
302
+ export function tryLock(file) {
303
+ const draft = `${file}.${process.pid}.tmp`;
304
+ writeFileSync(draft, String(process.pid));
305
+ try {
306
+ linkSync(draft, file);
307
+ heldLocks.add(file);
308
+ return true;
309
+ } catch (error) {
310
+ if (error.code !== 'EEXIST') throw error;
311
+ clearStaleLock(file);
312
+ return false;
313
+ } finally {
314
+ rmSync(draft, { force: true });
315
+ }
316
+ }
317
+
318
+ function clearStaleLock(file) {
319
+ const holder = unlessMissing(() => Number(readFileSync(file, 'utf8')), undefined);
320
+ if (holder !== undefined && !isAlive(holder)) rmSync(file, { force: true });
321
+ }
322
+
323
+ /** Waits for a lock file however long its holder keeps it */
324
+ export async function lock(file) {
325
+ while (!tryLock(file)) await sleep(POLL_MS);
326
+ }
327
+
328
+ export function unlock(file) {
329
+ heldLocks.delete(file);
330
+ rmSync(file, { force: true });
331
+ }
332
+
333
+ /** @returns {boolean} whether a process with this pid exists */
334
+ export function isAlive(pid) {
335
+ try {
336
+ process.kill(pid, 0);
337
+ return true;
338
+ } catch (error) {
339
+ return error.code === 'EPERM';
340
+ }
341
+ }
342
+
343
+ function send(pid, signal) {
344
+ try {
345
+ process.kill(pid, signal);
346
+ } catch {
347
+ return;
348
+ }
349
+ }
350
+
351
+ async function isGone(pid) {
352
+ const deadline = Date.now() + STOP_GRACE_MS;
353
+ while (isAlive(pid)) {
354
+ if (Date.now() >= deadline) return false;
355
+ await sleep(POLL_MS);
356
+ }
357
+ return true;
358
+ }
359
+
360
+ /** Asks a process to stop and waits until it is gone, killing it when it does not listen */
361
+ export async function terminate(pid) {
362
+ send(pid, 'SIGTERM');
363
+ if (await isGone(pid)) return;
364
+ send(pid, 'SIGKILL');
365
+ await isGone(pid);
366
+ }
367
+
368
+ /**
369
+ * Starts a script of a fake as a process that outlives the command, with the environment and
370
+ * the folder of the command.
371
+ * @returns {number} its pid
372
+ */
373
+ export function spawnDetached(script, args) {
374
+ const child = spawn(process.execPath, [script, ...args], { detached: true, stdio: 'ignore' });
375
+ child.unref();
376
+ return child.pid;
377
+ }
378
+
379
+ function maxLifeMs() {
380
+ const value = Number(process.env.FAKE_HARNESS_MAX_LIFE_MS);
381
+ return Number.isFinite(value) && value > 0 ? value : DEFAULT_MAX_LIFE_MS;
382
+ }
383
+
384
+ /** Calls `stop` when the process is asked to end */
385
+ export function onStopSignal(stop) {
386
+ for (const signal of STOP_SIGNALS) process.on(signal, stop);
387
+ }
388
+
389
+ /**
390
+ * Keeps a long-lived process from outliving a test run: `stop` is called on a stop signal, after
391
+ * FAKE_HARNESS_MAX_LIFE_MS and when the state file of the process is removed.
392
+ */
393
+ export function boundLife(stateFile, stop) {
394
+ onStopSignal(stop);
395
+ setTimeout(stop, maxLifeMs());
396
+ setInterval(() => {
397
+ if (!existsSync(stateFile)) stop();
398
+ }, STATE_WATCH_MS);
399
+ }
400
+
401
+ /** Child shells of this process that still run */
402
+ const shells = new Set();
403
+
404
+ function signalGroup(pid, signal) {
405
+ if (pid !== undefined) send(-pid, signal);
406
+ }
407
+
408
+ /**
409
+ * @typedef {object} ShellResult
410
+ * @property {number | null} code `null` when a signal ended the shell or it never started
411
+ * @property {string} stdout
412
+ * @property {string} stderr
413
+ * @property {boolean} timedOut
414
+ */
415
+
416
+ /**
417
+ * Starts `sh -c <command>` in a process group of its own, so that a kill reaches whatever the
418
+ * command started.
419
+ * @param {string} command
420
+ * @param {object} options
421
+ * @param {string} options.cwd
422
+ * @param {NodeJS.ProcessEnv} options.env
423
+ * @param {number} options.timeoutMs
424
+ * @param {NodeJS.Signals} options.killSignal sent to the group when the time is up
425
+ * @param {string} [options.input] written to stdin, which is then closed
426
+ * @returns {{ pid: number | undefined, done: Promise<ShellResult> }}
427
+ */
428
+ export function startShell(command, { cwd, env, timeoutMs, killSignal, input }) {
429
+ const child = spawn('sh', ['-c', command], {
430
+ cwd,
431
+ env,
432
+ detached: true,
433
+ stdio: [input === undefined ? 'ignore' : 'pipe', 'pipe', 'pipe'],
434
+ });
435
+ shells.add(child);
436
+ const done = new Promise((settle) => {
437
+ const output = { stdout: '', stderr: '' };
438
+ let timedOut = false;
439
+ for (const stream of ['stdout', 'stderr']) {
440
+ child[stream].setEncoding('utf8').on('data', (chunk) => (output[stream] += chunk));
441
+ }
442
+ const timer = setTimeout(() => {
443
+ timedOut = true;
444
+ signalGroup(child.pid, killSignal);
445
+ }, timeoutMs);
446
+ const finish = (code) => {
447
+ clearTimeout(timer);
448
+ shells.delete(child);
449
+ settle({ code, ...output, timedOut });
450
+ };
451
+ child.on('error', (error) => {
452
+ output.stderr += error.message;
453
+ finish(null);
454
+ });
455
+ child.on('close', finish);
456
+ });
457
+ if (input !== undefined) {
458
+ child.stdin.on('error', () => undefined);
459
+ child.stdin.end(input);
460
+ }
461
+ return { pid: child.pid, done };
462
+ }
463
+
464
+ /** Ends what this process still has going before it stops: its child shells and its locks */
465
+ export function abandonWork() {
466
+ for (const child of shells) signalGroup(child.pid, 'SIGTERM');
467
+ for (const file of [...heldLocks]) unlock(file);
468
+ }
469
+
470
+ /** @typedef {{ command: string, code: number | null, stdout: string, stderr: string }} CommandRun */
471
+
472
+ /**
473
+ * A tool call of a turn: `args` as the model wrote them, `sent` as they reached the server when
474
+ * a hook changed them
475
+ * @typedef {{ tool: string, args: Record<string, unknown>, sent?: Record<string, unknown>, text: string, isError: boolean }} ToolRun
476
+ */
477
+
478
+ /** @typedef {{ at: string, input: string, ran: CommandRun[], tools: ToolRun[], answer: string }} TurnOutcome */
479
+
480
+ /** @typedef {(server: string, tool: string, args: Record<string, unknown>) => Promise<{ text: string, isError: boolean, sent?: Record<string, unknown> }>} ToolCaller */
481
+
482
+ /**
483
+ * The directives of an input, in the order of its lines. A line counts after its leading
484
+ * whitespace is trimmed, a quoted line (`> run: ...`) is not a directive.
485
+ * @returns {{ kind: 'run' | 'sleep' | 'say' | 'tool', value: string }[]}
486
+ */
487
+ function directives(input) {
488
+ return input.split(/\r?\n/).flatMap((line) => {
489
+ const match = /^(run|sleep|say|tool): (.+)$/.exec(line.trimStart());
490
+ if (!match) return [];
491
+ const [, kind, text] = match;
492
+ const value = text.trim();
493
+ return kind === 'sleep' && !/^\d+$/.test(value) ? [] : [{ kind, value }];
494
+ });
495
+ }
496
+
497
+ async function runCommand(command, cwd, env) {
498
+ const shell = startShell(command, { cwd, env, timeoutMs: RUN_TIMEOUT_MS, killSignal: 'SIGKILL' });
499
+ const { code, stdout, stderr } = await shell.done;
500
+ return { command, code, stdout, stderr };
501
+ }
502
+
503
+ /**
504
+ * A `tool:` directive: `<server>.<tool>` and then the arguments as one JSON object, or nothing.
505
+ * A line that does not read as one calls nothing and is recorded as a failed call.
506
+ * @param {string} value
507
+ * @param {ToolCaller | undefined} callTool
508
+ * @returns {Promise<ToolRun>}
509
+ */
510
+ async function runTool(value, callTool) {
511
+ const match = /^([\w-]+)\.([\w-]+)(?:\s+(\{.*\}))?$/.exec(value);
512
+ const failed = (text) => ({ tool: value.split(/\s/, 1)[0], args: {}, text, isError: true });
513
+ if (!match) return failed('not a tool call: expected <server>.<tool> {json}');
514
+ const [, server, tool, json] = match;
515
+ let args;
516
+ try {
517
+ args = json === undefined ? {} : JSON.parse(json);
518
+ } catch {
519
+ return failed('the arguments of the tool call are not JSON');
520
+ }
521
+ if (!callTool) return { ...failed('this session has no MCP servers'), args };
522
+ try {
523
+ return { tool: `${server}.${tool}`, args, ...(await callTool(server, tool, args)) };
524
+ } catch (error) {
525
+ return { tool: `${server}.${tool}`, args, text: error.message, isError: true };
526
+ }
527
+ }
528
+
529
+ /**
530
+ * The scripted model: runs every `run: <command>` line with `sh -c`, calls the tool of every
531
+ * `tool: <server>.<tool> {json}` line and waits out every `sleep: <ms>` line, one after another,
532
+ * and answers with the last `say: <text>` line, or `ok`.
533
+ * @param {object} turn
534
+ * @param {string} turn.input
535
+ * @param {string} turn.cwd where the commands run
536
+ * @param {NodeJS.ProcessEnv} turn.env what the commands see
537
+ * @param {ToolCaller} [turn.callTool] how the session calls a tool of one of its MCP servers
538
+ * @returns {Promise<TurnOutcome>}
539
+ */
540
+ export async function performTurn({ input, cwd, env, callTool }) {
541
+ const at = new Date().toISOString();
542
+ const ran = [];
543
+ const tools = [];
544
+ let answer = 'ok';
545
+ for (const { kind, value } of directives(input)) {
546
+ if (kind === 'run') ran.push(await runCommand(value, cwd, env));
547
+ else if (kind === 'tool') tools.push(await runTool(value, callTool));
548
+ else if (kind === 'sleep') await sleep(Number(value));
549
+ else answer = value;
550
+ }
551
+ return { at, input, ran, tools, answer };
552
+ }
553
+
554
+ /**
555
+ * The environment of the commands of a sandboxed session: the fake sandbox is loaded into every
556
+ * Node process among them. No sandbox, no change.
557
+ * @param {NodeJS.ProcessEnv} env
558
+ * @param {string | undefined} mode `read-only`, `workspace-write` or `danger-full-access`
559
+ * @param {string} root the folder the session may write to
560
+ */
561
+ export function sandboxedEnv(env, mode, root) {
562
+ if (mode === undefined || mode === 'danger-full-access') return env;
563
+ const preload = `--import ${new URL('./sandbox.mjs', import.meta.url).href}`;
564
+ return {
565
+ ...env,
566
+ NODE_OPTIONS: env.NODE_OPTIONS ? `${env.NODE_OPTIONS} ${preload}` : preload,
567
+ FAKE_SANDBOX: mode,
568
+ FAKE_SANDBOX_ROOT: root,
569
+ };
570
+ }
571
+
572
+ function countLines(file) {
573
+ return unlessMissing(() => readFileSync(file, 'utf8'), '').split('\n').length - 1;
574
+ }
575
+
576
+ /**
577
+ * Appends a finished turn to a transcript as one JSON line.
578
+ * @param {string} transcript
579
+ * @param {TurnOutcome} outcome
580
+ * @param {'prompt' | 'user' | 'hook' | 'queue' | 'exec'} wokenBy what started the turn
581
+ */
582
+ export function recordTurn(transcript, { at, input, ran, tools, answer }, wokenBy) {
583
+ const turn = { turn: countLines(transcript) + 1, at, input, ran, tools, answer, wokenBy };
584
+ appendFileSync(transcript, `${JSON.stringify(turn)}\n`);
585
+ }