@cogitator-ai/bridge 0.0.0-stage → 0.3.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 +21 -0
- package/README.md +330 -2
- package/dist/adapter.d.ts +123 -0
- package/dist/adapter.d.ts.map +1 -0
- package/dist/adapter.js +2 -0
- package/dist/adapter.js.map +1 -0
- package/dist/adapters/claude.d.ts +90 -0
- package/dist/adapters/claude.d.ts.map +1 -0
- package/dist/adapters/claude.js +359 -0
- package/dist/adapters/claude.js.map +1 -0
- package/dist/adapters/codex.d.ts +58 -0
- package/dist/adapters/codex.d.ts.map +1 -0
- package/dist/adapters/codex.js +330 -0
- package/dist/adapters/codex.js.map +1 -0
- package/dist/adapters/exec.d.ts +57 -0
- package/dist/adapters/exec.d.ts.map +1 -0
- package/dist/adapters/exec.js +149 -0
- package/dist/adapters/exec.js.map +1 -0
- package/dist/adapters/hosted.d.ts +168 -0
- package/dist/adapters/hosted.d.ts.map +1 -0
- package/dist/adapters/hosted.js +361 -0
- package/dist/adapters/hosted.js.map +1 -0
- package/dist/client.d.ts +81 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +216 -0
- package/dist/client.js.map +1 -0
- package/dist/dispatcher.d.ts +296 -0
- package/dist/dispatcher.d.ts.map +1 -0
- package/dist/dispatcher.js +1524 -0
- package/dist/dispatcher.js.map +1 -0
- package/dist/errors.d.ts +10 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +16 -0
- package/dist/errors.js.map +1 -0
- package/dist/guards.d.ts +36 -0
- package/dist/guards.d.ts.map +1 -0
- package/dist/guards.js +85 -0
- package/dist/guards.js.map +1 -0
- package/dist/host.d.ts +49 -0
- package/dist/host.d.ts.map +1 -0
- package/dist/host.js +150 -0
- package/dist/host.js.map +1 -0
- package/dist/index.d.ts +50 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +32 -0
- package/dist/index.js.map +1 -0
- package/dist/inputs.d.ts +184 -0
- package/dist/inputs.d.ts.map +1 -0
- package/dist/inputs.js +116 -0
- package/dist/inputs.js.map +1 -0
- package/dist/job-record.d.ts +47 -0
- package/dist/job-record.d.ts.map +1 -0
- package/dist/job-record.js +65 -0
- package/dist/job-record.js.map +1 -0
- package/dist/letters.d.ts +49 -0
- package/dist/letters.d.ts.map +1 -0
- package/dist/letters.js +96 -0
- package/dist/letters.js.map +1 -0
- package/dist/paths.d.ts +38 -0
- package/dist/paths.d.ts.map +1 -0
- package/dist/paths.js +149 -0
- package/dist/paths.js.map +1 -0
- package/dist/protocol.d.ts +83 -0
- package/dist/protocol.d.ts.map +1 -0
- package/dist/protocol.js +71 -0
- package/dist/protocol.js.map +1 -0
- package/dist/registry.d.ts +62 -0
- package/dist/registry.d.ts.map +1 -0
- package/dist/registry.js +185 -0
- package/dist/registry.js.map +1 -0
- package/dist/server.d.ts +31 -0
- package/dist/server.d.ts.map +1 -0
- package/dist/server.js +254 -0
- package/dist/server.js.map +1 -0
- package/dist/store/sqlite.d.ts +56 -0
- package/dist/store/sqlite.d.ts.map +1 -0
- package/dist/store/sqlite.js +737 -0
- package/dist/store/sqlite.js.map +1 -0
- package/dist/store/store.d.ts +128 -0
- package/dist/store/store.d.ts.map +1 -0
- package/dist/store/store.js +2 -0
- package/dist/store/store.js.map +1 -0
- package/dist/testing/conformance.d.ts +65 -0
- package/dist/testing/conformance.d.ts.map +1 -0
- package/dist/testing/conformance.js +217 -0
- package/dist/testing/conformance.js.map +1 -0
- package/dist/testing/fake-harnesses.d.ts +101 -0
- package/dist/testing/fake-harnesses.d.ts.map +1 -0
- package/dist/testing/fake-harnesses.js +291 -0
- package/dist/testing/fake-harnesses.js.map +1 -0
- package/dist/testing/index.d.ts +5 -0
- package/dist/testing/index.d.ts.map +1 -0
- package/dist/testing/index.js +3 -0
- package/dist/testing/index.js.map +1 -0
- package/dist/types.d.ts +286 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +132 -0
- package/dist/types.js.map +1 -0
- package/dist/waiter.d.ts +36 -0
- package/dist/waiter.d.ts.map +1 -0
- package/dist/waiter.js +92 -0
- package/dist/waiter.js.map +1 -0
- package/fakes/claude.mjs +450 -0
- package/fakes/codex.mjs +391 -0
- package/fakes/lib.mjs +507 -0
- package/package.json +76 -3
package/fakes/lib.mjs
ADDED
|
@@ -0,0 +1,507 @@
|
|
|
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 }} 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
|
+
/**
|
|
104
|
+
* Splits arguments into option values and positionals. An option that takes a value consumes
|
|
105
|
+
* the next argument whatever it looks like, `--name=value` works for long names, `--` ends the
|
|
106
|
+
* options and a lone `-` is a positional. An unknown option is {@link Unsupported}.
|
|
107
|
+
* @param {string[]} argv
|
|
108
|
+
* @param {Record<string, Flag>} flags by the name on the command line, such as `--json` or `-C`
|
|
109
|
+
* @returns {{ values: Record<string, string | true>, positionals: string[] }}
|
|
110
|
+
*/
|
|
111
|
+
export function parseArgs(argv, flags) {
|
|
112
|
+
const values = {};
|
|
113
|
+
const positionals = [];
|
|
114
|
+
const rest = [...argv];
|
|
115
|
+
while (rest.length > 0) {
|
|
116
|
+
const arg = rest.shift();
|
|
117
|
+
if (arg === '--') positionals.push(...rest.splice(0));
|
|
118
|
+
else if (arg === '-' || !arg.startsWith('-')) positionals.push(arg);
|
|
119
|
+
else Object.assign(values, readOption(arg, rest, flags));
|
|
120
|
+
}
|
|
121
|
+
return { values, positionals };
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function readOption(arg, rest, flags) {
|
|
125
|
+
const cut = arg.startsWith('--') ? arg.indexOf('=') : -1;
|
|
126
|
+
const name = cut === -1 ? arg : arg.slice(0, cut);
|
|
127
|
+
const inline = cut === -1 ? undefined : arg.slice(cut + 1);
|
|
128
|
+
if (!Object.hasOwn(flags, name)) throw new Unsupported();
|
|
129
|
+
const { key, takesValue } = flags[name];
|
|
130
|
+
if (!takesValue) {
|
|
131
|
+
if (inline !== undefined) throw new Unsupported();
|
|
132
|
+
return { [key]: true };
|
|
133
|
+
}
|
|
134
|
+
const value = inline ?? rest.shift();
|
|
135
|
+
if (value === undefined) throw new Unsupported();
|
|
136
|
+
return { [key]: value };
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* The comma list of an environment variable such as FAKE_CLAUDE_MISSING.
|
|
141
|
+
* @param {string} variable
|
|
142
|
+
* @returns {Set<string>}
|
|
143
|
+
*/
|
|
144
|
+
export function listedIn(variable) {
|
|
145
|
+
const items = (process.env[variable] ?? '').split(',').map((item) => item.trim());
|
|
146
|
+
return new Set(items.filter(Boolean));
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* A help text without the lines of the features an imitated old version lacks.
|
|
151
|
+
* @param {(string | [feature: string, line: string])[]} lines
|
|
152
|
+
* @param {Set<string>} missing
|
|
153
|
+
*/
|
|
154
|
+
export function renderHelp(lines, missing) {
|
|
155
|
+
return lines
|
|
156
|
+
.filter((line) => typeof line === 'string' || !missing.has(line[0]))
|
|
157
|
+
.map((line) => (typeof line === 'string' ? line : line[1]))
|
|
158
|
+
.join('\n');
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** @param {string} path the absolute path with links resolved, as `process.cwd()` reports it */
|
|
162
|
+
export function canonical(path) {
|
|
163
|
+
const absolute = resolve(path);
|
|
164
|
+
try {
|
|
165
|
+
return realpathSync(absolute);
|
|
166
|
+
} catch {
|
|
167
|
+
return absolute;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** @returns {boolean} whether `folder` is `parent` or lies below it */
|
|
172
|
+
export function isWithin(folder, parent) {
|
|
173
|
+
const hops = relative(canonical(parent), canonical(folder));
|
|
174
|
+
return hops !== '..' && !hops.startsWith(`..${sep}`);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** @returns {boolean} whether an id is safe as a file name inside a state folder */
|
|
178
|
+
export function isStateName(id) {
|
|
179
|
+
return /^[\w-]+$/.test(id);
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function unlessMissing(read, fallback) {
|
|
183
|
+
try {
|
|
184
|
+
return read();
|
|
185
|
+
} catch (error) {
|
|
186
|
+
if (error.code === 'ENOENT') return fallback;
|
|
187
|
+
throw error;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** @returns the parsed file, or `fallback` when it does not exist */
|
|
192
|
+
export function readJson(file, fallback) {
|
|
193
|
+
return unlessMissing(() => JSON.parse(readFileSync(file, 'utf8')), fallback);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** Replaces a state file in one step: readers see the old content or the new, never a part */
|
|
197
|
+
export function writeJson(file, value) {
|
|
198
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
199
|
+
const draft = `${file}.${process.pid}.tmp`;
|
|
200
|
+
writeFileSync(draft, JSON.stringify(value, null, 2));
|
|
201
|
+
renameSync(draft, file);
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* Merges fields into a state file, `undefined` drops a field. A file that is gone stays gone.
|
|
206
|
+
* @returns the new content, or `undefined` when the file does not exist
|
|
207
|
+
*/
|
|
208
|
+
export function patchJson(file, patch) {
|
|
209
|
+
const current = readJson(file);
|
|
210
|
+
if (current === undefined) return undefined;
|
|
211
|
+
const next = { ...current, ...patch };
|
|
212
|
+
writeJson(file, next);
|
|
213
|
+
return next;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** @returns {object[]} every record (`*.json`) of a state folder */
|
|
217
|
+
export function listRecords(dir) {
|
|
218
|
+
return unlessMissing(() => readdirSync(dir), [])
|
|
219
|
+
.filter((name) => name.endsWith('.json'))
|
|
220
|
+
.map((name) => readJson(join(dir, name)))
|
|
221
|
+
.filter((record) => record !== undefined);
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** Resolves with a record another process is about to write, or `undefined` when it never comes */
|
|
225
|
+
export async function awaitJson(file) {
|
|
226
|
+
const deadline = Date.now() + STOP_GRACE_MS;
|
|
227
|
+
while (!existsSync(file)) {
|
|
228
|
+
if (Date.now() >= deadline) return undefined;
|
|
229
|
+
await sleep(POLL_MS);
|
|
230
|
+
}
|
|
231
|
+
return readJson(file);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
let enqueued = 0;
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* Adds a message to a spool folder as one file. Names sort by arrival time, a message shows up
|
|
238
|
+
* under its name only when it is complete.
|
|
239
|
+
*/
|
|
240
|
+
export function enqueue(dir, message) {
|
|
241
|
+
mkdirSync(dir, { recursive: true });
|
|
242
|
+
const stamp = [Date.now(), process.pid, enqueued++].map((part) => String(part).padStart(15, '0'));
|
|
243
|
+
const name = `${stamp.join('-')}.json`;
|
|
244
|
+
writeFileSync(join(dir, `.${name}`), JSON.stringify(message));
|
|
245
|
+
renameSync(join(dir, `.${name}`), join(dir, name));
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/** @returns {string[]} the names of the messages waiting in a spool folder, oldest first */
|
|
249
|
+
export function pending(dir) {
|
|
250
|
+
return unlessMissing(() => readdirSync(dir), [])
|
|
251
|
+
.filter((name) => !name.startsWith('.'))
|
|
252
|
+
.sort();
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* Takes the oldest message out of a spool folder. It is renamed away first, so no message is
|
|
257
|
+
* taken twice even when several processes look at one folder.
|
|
258
|
+
* @returns the message, or `undefined` when nothing waits
|
|
259
|
+
*/
|
|
260
|
+
export function takeNext(dir) {
|
|
261
|
+
const [name] = pending(dir);
|
|
262
|
+
if (name === undefined) return undefined;
|
|
263
|
+
const taken = join(dir, `.taken-${process.pid}-${name}`);
|
|
264
|
+
return unlessMissing(() => {
|
|
265
|
+
renameSync(join(dir, name), taken);
|
|
266
|
+
const message = JSON.parse(readFileSync(taken, 'utf8'));
|
|
267
|
+
rmSync(taken);
|
|
268
|
+
return message;
|
|
269
|
+
}, undefined);
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/** Lock files this process holds, released when it stops */
|
|
273
|
+
const heldLocks = new Set();
|
|
274
|
+
|
|
275
|
+
/**
|
|
276
|
+
* Tries to take a lock file. The file appears with the pid of its holder already in it, and a
|
|
277
|
+
* lock whose holder died is cleared for the next attempt.
|
|
278
|
+
* @returns {boolean} whether this process holds the lock now
|
|
279
|
+
*/
|
|
280
|
+
export function tryLock(file) {
|
|
281
|
+
const draft = `${file}.${process.pid}.tmp`;
|
|
282
|
+
writeFileSync(draft, String(process.pid));
|
|
283
|
+
try {
|
|
284
|
+
linkSync(draft, file);
|
|
285
|
+
heldLocks.add(file);
|
|
286
|
+
return true;
|
|
287
|
+
} catch (error) {
|
|
288
|
+
if (error.code !== 'EEXIST') throw error;
|
|
289
|
+
clearStaleLock(file);
|
|
290
|
+
return false;
|
|
291
|
+
} finally {
|
|
292
|
+
rmSync(draft, { force: true });
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
function clearStaleLock(file) {
|
|
297
|
+
const holder = unlessMissing(() => Number(readFileSync(file, 'utf8')), undefined);
|
|
298
|
+
if (holder !== undefined && !isAlive(holder)) rmSync(file, { force: true });
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/** Waits for a lock file however long its holder keeps it */
|
|
302
|
+
export async function lock(file) {
|
|
303
|
+
while (!tryLock(file)) await sleep(POLL_MS);
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
export function unlock(file) {
|
|
307
|
+
heldLocks.delete(file);
|
|
308
|
+
rmSync(file, { force: true });
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/** @returns {boolean} whether a process with this pid exists */
|
|
312
|
+
export function isAlive(pid) {
|
|
313
|
+
try {
|
|
314
|
+
process.kill(pid, 0);
|
|
315
|
+
return true;
|
|
316
|
+
} catch (error) {
|
|
317
|
+
return error.code === 'EPERM';
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
function send(pid, signal) {
|
|
322
|
+
try {
|
|
323
|
+
process.kill(pid, signal);
|
|
324
|
+
} catch {
|
|
325
|
+
return;
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
async function isGone(pid) {
|
|
330
|
+
const deadline = Date.now() + STOP_GRACE_MS;
|
|
331
|
+
while (isAlive(pid)) {
|
|
332
|
+
if (Date.now() >= deadline) return false;
|
|
333
|
+
await sleep(POLL_MS);
|
|
334
|
+
}
|
|
335
|
+
return true;
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/** Asks a process to stop and waits until it is gone, killing it when it does not listen */
|
|
339
|
+
export async function terminate(pid) {
|
|
340
|
+
send(pid, 'SIGTERM');
|
|
341
|
+
if (await isGone(pid)) return;
|
|
342
|
+
send(pid, 'SIGKILL');
|
|
343
|
+
await isGone(pid);
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/**
|
|
347
|
+
* Starts a script of a fake as a process that outlives the command, with the environment and
|
|
348
|
+
* the folder of the command.
|
|
349
|
+
* @returns {number} its pid
|
|
350
|
+
*/
|
|
351
|
+
export function spawnDetached(script, args) {
|
|
352
|
+
const child = spawn(process.execPath, [script, ...args], { detached: true, stdio: 'ignore' });
|
|
353
|
+
child.unref();
|
|
354
|
+
return child.pid;
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
function maxLifeMs() {
|
|
358
|
+
const value = Number(process.env.FAKE_HARNESS_MAX_LIFE_MS);
|
|
359
|
+
return Number.isFinite(value) && value > 0 ? value : DEFAULT_MAX_LIFE_MS;
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/** Calls `stop` when the process is asked to end */
|
|
363
|
+
export function onStopSignal(stop) {
|
|
364
|
+
for (const signal of STOP_SIGNALS) process.on(signal, stop);
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/**
|
|
368
|
+
* Keeps a long-lived process from outliving a test run: `stop` is called on a stop signal, after
|
|
369
|
+
* FAKE_HARNESS_MAX_LIFE_MS and when the state file of the process is removed.
|
|
370
|
+
*/
|
|
371
|
+
export function boundLife(stateFile, stop) {
|
|
372
|
+
onStopSignal(stop);
|
|
373
|
+
setTimeout(stop, maxLifeMs());
|
|
374
|
+
setInterval(() => {
|
|
375
|
+
if (!existsSync(stateFile)) stop();
|
|
376
|
+
}, STATE_WATCH_MS);
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
/** Child shells of this process that still run */
|
|
380
|
+
const shells = new Set();
|
|
381
|
+
|
|
382
|
+
function signalGroup(pid, signal) {
|
|
383
|
+
if (pid !== undefined) send(-pid, signal);
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
/**
|
|
387
|
+
* @typedef {object} ShellResult
|
|
388
|
+
* @property {number | null} code `null` when a signal ended the shell or it never started
|
|
389
|
+
* @property {string} stdout
|
|
390
|
+
* @property {string} stderr
|
|
391
|
+
* @property {boolean} timedOut
|
|
392
|
+
*/
|
|
393
|
+
|
|
394
|
+
/**
|
|
395
|
+
* Starts `sh -c <command>` in a process group of its own, so that a kill reaches whatever the
|
|
396
|
+
* command started.
|
|
397
|
+
* @param {string} command
|
|
398
|
+
* @param {object} options
|
|
399
|
+
* @param {string} options.cwd
|
|
400
|
+
* @param {NodeJS.ProcessEnv} options.env
|
|
401
|
+
* @param {number} options.timeoutMs
|
|
402
|
+
* @param {NodeJS.Signals} options.killSignal sent to the group when the time is up
|
|
403
|
+
* @param {string} [options.input] written to stdin, which is then closed
|
|
404
|
+
* @returns {{ pid: number | undefined, done: Promise<ShellResult> }}
|
|
405
|
+
*/
|
|
406
|
+
export function startShell(command, { cwd, env, timeoutMs, killSignal, input }) {
|
|
407
|
+
const child = spawn('sh', ['-c', command], {
|
|
408
|
+
cwd,
|
|
409
|
+
env,
|
|
410
|
+
detached: true,
|
|
411
|
+
stdio: [input === undefined ? 'ignore' : 'pipe', 'pipe', 'pipe'],
|
|
412
|
+
});
|
|
413
|
+
shells.add(child);
|
|
414
|
+
const done = new Promise((settle) => {
|
|
415
|
+
const output = { stdout: '', stderr: '' };
|
|
416
|
+
let timedOut = false;
|
|
417
|
+
for (const stream of ['stdout', 'stderr']) {
|
|
418
|
+
child[stream].setEncoding('utf8').on('data', (chunk) => (output[stream] += chunk));
|
|
419
|
+
}
|
|
420
|
+
const timer = setTimeout(() => {
|
|
421
|
+
timedOut = true;
|
|
422
|
+
signalGroup(child.pid, killSignal);
|
|
423
|
+
}, timeoutMs);
|
|
424
|
+
const finish = (code) => {
|
|
425
|
+
clearTimeout(timer);
|
|
426
|
+
shells.delete(child);
|
|
427
|
+
settle({ code, ...output, timedOut });
|
|
428
|
+
};
|
|
429
|
+
child.on('error', (error) => {
|
|
430
|
+
output.stderr += error.message;
|
|
431
|
+
finish(null);
|
|
432
|
+
});
|
|
433
|
+
child.on('close', finish);
|
|
434
|
+
});
|
|
435
|
+
if (input !== undefined) {
|
|
436
|
+
child.stdin.on('error', () => undefined);
|
|
437
|
+
child.stdin.end(input);
|
|
438
|
+
}
|
|
439
|
+
return { pid: child.pid, done };
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
/** Ends what this process still has going before it stops: its child shells and its locks */
|
|
443
|
+
export function abandonWork() {
|
|
444
|
+
for (const child of shells) signalGroup(child.pid, 'SIGTERM');
|
|
445
|
+
for (const file of [...heldLocks]) unlock(file);
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
/** @typedef {{ command: string, code: number | null, stdout: string, stderr: string }} CommandRun */
|
|
449
|
+
|
|
450
|
+
/** @typedef {{ at: string, input: string, ran: CommandRun[], answer: string }} TurnOutcome */
|
|
451
|
+
|
|
452
|
+
/**
|
|
453
|
+
* The directives of an input, in the order of its lines. A line counts after its leading
|
|
454
|
+
* whitespace is trimmed, a quoted line (`> run: ...`) is not a directive.
|
|
455
|
+
* @returns {{ kind: 'run' | 'sleep' | 'say', value: string }[]}
|
|
456
|
+
*/
|
|
457
|
+
function directives(input) {
|
|
458
|
+
return input.split(/\r?\n/).flatMap((line) => {
|
|
459
|
+
const match = /^(run|sleep|say): (.+)$/.exec(line.trimStart());
|
|
460
|
+
if (!match) return [];
|
|
461
|
+
const [, kind, text] = match;
|
|
462
|
+
const value = text.trim();
|
|
463
|
+
return kind === 'sleep' && !/^\d+$/.test(value) ? [] : [{ kind, value }];
|
|
464
|
+
});
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
async function runCommand(command, cwd, env) {
|
|
468
|
+
const shell = startShell(command, { cwd, env, timeoutMs: RUN_TIMEOUT_MS, killSignal: 'SIGKILL' });
|
|
469
|
+
const { code, stdout, stderr } = await shell.done;
|
|
470
|
+
return { command, code, stdout, stderr };
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
/**
|
|
474
|
+
* The scripted model: runs every `run: <command>` line with `sh -c` and waits out every
|
|
475
|
+
* `sleep: <ms>` line, one after another, and answers with the last `say: <text>` line, or `ok`.
|
|
476
|
+
* @param {object} turn
|
|
477
|
+
* @param {string} turn.input
|
|
478
|
+
* @param {string} turn.cwd where the commands run
|
|
479
|
+
* @param {NodeJS.ProcessEnv} turn.env what the commands see
|
|
480
|
+
* @returns {Promise<TurnOutcome>}
|
|
481
|
+
*/
|
|
482
|
+
export async function performTurn({ input, cwd, env }) {
|
|
483
|
+
const at = new Date().toISOString();
|
|
484
|
+
const ran = [];
|
|
485
|
+
let answer = 'ok';
|
|
486
|
+
for (const { kind, value } of directives(input)) {
|
|
487
|
+
if (kind === 'run') ran.push(await runCommand(value, cwd, env));
|
|
488
|
+
else if (kind === 'sleep') await sleep(Number(value));
|
|
489
|
+
else answer = value;
|
|
490
|
+
}
|
|
491
|
+
return { at, input, ran, answer };
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
function countLines(file) {
|
|
495
|
+
return unlessMissing(() => readFileSync(file, 'utf8'), '').split('\n').length - 1;
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
/**
|
|
499
|
+
* Appends a finished turn to a transcript as one JSON line.
|
|
500
|
+
* @param {string} transcript
|
|
501
|
+
* @param {TurnOutcome} outcome
|
|
502
|
+
* @param {'prompt' | 'user' | 'hook' | 'queue' | 'exec'} wokenBy what started the turn
|
|
503
|
+
*/
|
|
504
|
+
export function recordTurn(transcript, { at, input, ran, answer }, wokenBy) {
|
|
505
|
+
const turn = { turn: countLines(transcript) + 1, at, input, ran, answer, wokenBy };
|
|
506
|
+
appendFileSync(transcript, `${JSON.stringify(turn)}\n`);
|
|
507
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,79 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cogitator-ai/bridge",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.3.0",
|
|
4
|
+
"description": "Agent bridge for Cogitator: Claude Code, Codex and other agents hand each other jobs, ask questions and report back, each in its own window (experimental)",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"cogitator",
|
|
7
|
+
"ai",
|
|
8
|
+
"agents",
|
|
9
|
+
"llm",
|
|
10
|
+
"multi-agent",
|
|
11
|
+
"bridge",
|
|
12
|
+
"claude-code",
|
|
13
|
+
"codex",
|
|
14
|
+
"a2a",
|
|
15
|
+
"orchestration"
|
|
16
|
+
],
|
|
17
|
+
"type": "module",
|
|
18
|
+
"main": "./dist/index.js",
|
|
19
|
+
"types": "./dist/index.d.ts",
|
|
20
|
+
"exports": {
|
|
21
|
+
".": {
|
|
22
|
+
"types": "./dist/index.d.ts",
|
|
23
|
+
"import": "./dist/index.js",
|
|
24
|
+
"default": "./dist/index.js"
|
|
25
|
+
},
|
|
26
|
+
"./testing": {
|
|
27
|
+
"types": "./dist/testing/index.d.ts",
|
|
28
|
+
"import": "./dist/testing/index.js",
|
|
29
|
+
"default": "./dist/testing/index.js"
|
|
30
|
+
}
|
|
31
|
+
},
|
|
32
|
+
"sideEffects": false,
|
|
33
|
+
"files": [
|
|
34
|
+
"dist",
|
|
35
|
+
"fakes",
|
|
36
|
+
"README.md"
|
|
37
|
+
],
|
|
38
|
+
"dependencies": {
|
|
39
|
+
"@cogitator-ai/a2a": "0.12.0",
|
|
40
|
+
"@cogitator-ai/server-shared": "0.17.0",
|
|
41
|
+
"zod": "^4.6.6"
|
|
42
|
+
},
|
|
43
|
+
"devDependencies": {
|
|
44
|
+
"@types/better-sqlite3": "^9.6.0",
|
|
45
|
+
"@types/node": "^22.20.4",
|
|
46
|
+
"better-sqlite3": "^13.0.3",
|
|
47
|
+
"typescript": "^6.0.3",
|
|
48
|
+
"vitest": "^5.0.3"
|
|
49
|
+
},
|
|
50
|
+
"peerDependencies": {
|
|
51
|
+
"better-sqlite3": "^11.0.0 || ^12.0.0 || ^13.0.0"
|
|
52
|
+
},
|
|
53
|
+
"peerDependenciesMeta": {
|
|
54
|
+
"better-sqlite3": {
|
|
55
|
+
"optional": true
|
|
56
|
+
}
|
|
57
|
+
},
|
|
58
|
+
"engines": {
|
|
59
|
+
"node": ">=22.12.0"
|
|
60
|
+
},
|
|
61
|
+
"repository": {
|
|
62
|
+
"type": "git",
|
|
63
|
+
"url": "git+https://github.com/cogitator-ai/Cogitator-AI.git",
|
|
64
|
+
"directory": "packages/bridge"
|
|
65
|
+
},
|
|
66
|
+
"publishConfig": {
|
|
67
|
+
"access": "public"
|
|
68
|
+
},
|
|
69
|
+
"license": "MIT",
|
|
70
|
+
"scripts": {
|
|
71
|
+
"build": "tsc && tsx ../../scripts/fix-esm-imports.ts .",
|
|
72
|
+
"dev": "tsc --watch",
|
|
73
|
+
"test": "vitest run",
|
|
74
|
+
"typecheck": "tsc --noEmit -p tsconfig.test.json",
|
|
75
|
+
"test:watch": "vitest",
|
|
76
|
+
"lint": "eslint src",
|
|
77
|
+
"clean": "rm -rf dist"
|
|
78
|
+
}
|
|
6
79
|
}
|