@cogitator-ai/bridge 0.2.0 → 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.
Files changed (74) hide show
  1. package/README.md +156 -8
  2. package/dist/adapter.d.ts +123 -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 +90 -0
  7. package/dist/adapters/claude.d.ts.map +1 -0
  8. package/dist/adapters/claude.js +359 -0
  9. package/dist/adapters/claude.js.map +1 -0
  10. package/dist/adapters/codex.d.ts +58 -0
  11. package/dist/adapters/codex.d.ts.map +1 -0
  12. package/dist/adapters/codex.js +330 -0
  13. package/dist/adapters/codex.js.map +1 -0
  14. package/dist/adapters/exec.d.ts +57 -0
  15. package/dist/adapters/exec.d.ts.map +1 -0
  16. package/dist/adapters/exec.js +149 -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/client.d.ts +9 -2
  23. package/dist/client.d.ts.map +1 -1
  24. package/dist/client.js +17 -3
  25. package/dist/client.js.map +1 -1
  26. package/dist/dispatcher.d.ts +67 -17
  27. package/dist/dispatcher.d.ts.map +1 -1
  28. package/dist/dispatcher.js +240 -17
  29. package/dist/dispatcher.js.map +1 -1
  30. package/dist/host.d.ts +1 -1
  31. package/dist/host.d.ts.map +1 -1
  32. package/dist/index.d.ts +13 -2
  33. package/dist/index.d.ts.map +1 -1
  34. package/dist/index.js +6 -0
  35. package/dist/index.js.map +1 -1
  36. package/dist/inputs.d.ts +40 -1
  37. package/dist/inputs.d.ts.map +1 -1
  38. package/dist/inputs.js +25 -2
  39. package/dist/inputs.js.map +1 -1
  40. package/dist/paths.d.ts +6 -0
  41. package/dist/paths.d.ts.map +1 -1
  42. package/dist/paths.js +19 -0
  43. package/dist/paths.js.map +1 -1
  44. package/dist/protocol.d.ts +5 -0
  45. package/dist/protocol.d.ts.map +1 -1
  46. package/dist/protocol.js +5 -0
  47. package/dist/protocol.js.map +1 -1
  48. package/dist/server.d.ts.map +1 -1
  49. package/dist/server.js +6 -1
  50. package/dist/server.js.map +1 -1
  51. package/dist/testing/conformance.d.ts +65 -0
  52. package/dist/testing/conformance.d.ts.map +1 -0
  53. package/dist/testing/conformance.js +217 -0
  54. package/dist/testing/conformance.js.map +1 -0
  55. package/dist/testing/fake-harnesses.d.ts +101 -0
  56. package/dist/testing/fake-harnesses.d.ts.map +1 -0
  57. package/dist/testing/fake-harnesses.js +291 -0
  58. package/dist/testing/fake-harnesses.js.map +1 -0
  59. package/dist/testing/index.d.ts +5 -0
  60. package/dist/testing/index.d.ts.map +1 -0
  61. package/dist/testing/index.js +3 -0
  62. package/dist/testing/index.js.map +1 -0
  63. package/dist/types.d.ts +3 -39
  64. package/dist/types.d.ts.map +1 -1
  65. package/dist/types.js +2 -0
  66. package/dist/types.js.map +1 -1
  67. package/dist/waiter.d.ts +36 -0
  68. package/dist/waiter.d.ts.map +1 -0
  69. package/dist/waiter.js +92 -0
  70. package/dist/waiter.js.map +1 -0
  71. package/fakes/claude.mjs +450 -0
  72. package/fakes/codex.mjs +391 -0
  73. package/fakes/lib.mjs +507 -0
  74. package/package.json +7 -1
@@ -0,0 +1,330 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { closeSync, existsSync, mkdirSync, openSync, readFileSync } from 'node:fs';
3
+ import { join, resolve } from 'node:path';
4
+ import { isBridgeError } from '../errors.js';
5
+ import { bridgePaths, findProjectRoot } from '../paths.js';
6
+ import { HARNESSES } from '../types.js';
7
+ import { CommandMissingError, failureOf, fitsArgument, pause, runCommand, sessionEnv, tooLongNotice, } from './exec.js';
8
+ /** How letters reach a Codex thread: the thread's own message queue. */
9
+ export const CODEX_DELIVERY = 'queue';
10
+ const DEFAULT_THREAD_STARTED_MS = 60_000;
11
+ const LOG_INTERVAL_MS = 100;
12
+ const NOT_RESUMED = /could not resume thread/i;
13
+ const DAEMON_START = 'codex app-server daemon start';
14
+ /**
15
+ * What the journal says of a letter Codex queued with no local daemon to resume the thread.
16
+ * `codex queue --resume` warns the same whether the Codex app has the thread open or nobody
17
+ * does, so the note names both cases.
18
+ */
19
+ export const CODEX_NOT_RESUMED_NOTE = 'Codex queued the letter, and no local daemon runs to resume the thread. A thread open in the ' +
20
+ 'Codex app reads it at once, one open nowhere when it is opened, or at once with: ' +
21
+ DAEMON_START;
22
+ const FINISHED = ['completed', 'failed', 'canceled'];
23
+ function execLines(output) {
24
+ const lines = [];
25
+ for (const raw of output.split('\n')) {
26
+ const line = raw.trim();
27
+ if (!line)
28
+ continue;
29
+ let event;
30
+ if (line.startsWith('{')) {
31
+ try {
32
+ event = JSON.parse(line);
33
+ }
34
+ catch {
35
+ event = undefined;
36
+ }
37
+ }
38
+ lines.push(typeof event === 'object' && event !== null
39
+ ? { event: event }
40
+ : { text: line });
41
+ }
42
+ return lines;
43
+ }
44
+ function textOf(value) {
45
+ return typeof value === 'string' && value.trim() ? value.trim() : undefined;
46
+ }
47
+ /** The id of the thread `codex exec --json` says it started, when its output has it already. */
48
+ export function codexThreadId(output) {
49
+ for (const line of execLines(output)) {
50
+ const id = 'event' in line ? textOf(line.event.thread_id) : undefined;
51
+ if (id)
52
+ return id;
53
+ }
54
+ return undefined;
55
+ }
56
+ /**
57
+ * What a thread the bridge starts reads under its first letter. Such a thread often cannot reach
58
+ * the bridge from its sandbox, so the bridge reports for it.
59
+ */
60
+ export function codexReportNotice(job) {
61
+ return (`[agent bridge] Your final answer of this turn is taken as the report on job #${job}, unless you send a report yourself. ` +
62
+ 'A bridge command that fails from your sandbox needs no second try: answer here.');
63
+ }
64
+ /**
65
+ * What a `codex exec` that ended leaves to report: the last message of the thread, or why the
66
+ * turn failed. `output` is what it wrote with `--json`, `code` its exit code, null after a signal.
67
+ */
68
+ export function codexTurnReport(output, code) {
69
+ let message;
70
+ let turnFailed = false;
71
+ let reason;
72
+ const said = [];
73
+ for (const line of execLines(output)) {
74
+ if ('text' in line) {
75
+ said.push(line.text);
76
+ continue;
77
+ }
78
+ const { type, item, error } = line.event;
79
+ if (type === 'item.completed' && typeof item === 'object' && item !== null) {
80
+ const { type: kind, text } = item;
81
+ if (kind === 'agent_message')
82
+ message = textOf(text) ?? message;
83
+ }
84
+ else if (type === 'turn.failed') {
85
+ turnFailed = true;
86
+ const told = typeof error === 'object' && error !== null
87
+ ? textOf(error.message)
88
+ : undefined;
89
+ reason = told ?? reason;
90
+ }
91
+ else if (type === 'error') {
92
+ reason = textOf(line.event.message) ?? reason;
93
+ }
94
+ }
95
+ if (code === 0 && !turnFailed)
96
+ return { body: message ?? 'Done', failed: false };
97
+ const why = reason ?? failureOf({ code, stdout: '', stderr: said.join('\n') });
98
+ return {
99
+ body: `codex exec failed before the thread finished its turn: ${why}` +
100
+ (message ? `\nIts last message: ${message}` : ''),
101
+ failed: true,
102
+ };
103
+ }
104
+ /**
105
+ * Reaches Codex threads in their own windows. A letter goes into the thread's message queue
106
+ * (`codex queue --resume`): a thread open in the Codex app takes it by itself within seconds,
107
+ * one that is open nowhere needs the local daemon (`codex app-server daemon start`), which the
108
+ * bridge never starts on its own. A session for a job is a thread of `codex exec`, started with
109
+ * the job's first letter and left to finish its turn by itself. Such a thread works in a sandbox
110
+ * that usually keeps it from the bridge, so when its turn ends and it wrote nothing on the job
111
+ * itself, the adapter sends its final answer as the report, or what failed when the turn failed.
112
+ */
113
+ export function codexAdapter(options = {}) {
114
+ const command = options.command ?? 'codex';
115
+ const env = options.env ?? process.env;
116
+ const logDir = options.logDir ?? join(bridgePaths({ env }).home, 'sessions');
117
+ const bridgeHome = env.COGITATOR_BRIDGE_HOME?.trim() || undefined;
118
+ const onError = options.onError ?? (() => undefined);
119
+ let bridge;
120
+ let closed = false;
121
+ /**
122
+ * Reports for a thread whose `codex exec` ended, unless the job is over or the thread wrote on
123
+ * it itself: a thread that reaches the bridge speaks for itself.
124
+ */
125
+ async function reportFor(request, sessionId, logPath, code) {
126
+ if (closed || !bridge)
127
+ return;
128
+ const job = request.job.number;
129
+ if (FINISHED.includes((await bridge.job(job)).state))
130
+ return;
131
+ const agent = await bridge.register({
132
+ harness: HARNESSES.codex,
133
+ sessionId,
134
+ cwd: request.cwd,
135
+ project: request.project,
136
+ agentName: request.agentName,
137
+ });
138
+ const own = await bridge.letters({ job, from: agent.name, limit: 1 });
139
+ if (own.length > 0 || closed)
140
+ return;
141
+ const { body, failed } = codexTurnReport(readFileSync(logPath, 'utf8'), code);
142
+ await bridge.send(agent.name, {
143
+ job,
144
+ kind: 'report',
145
+ body: body.replaceAll('\0', ''),
146
+ ...(failed && { outcome: 'failed' }),
147
+ });
148
+ }
149
+ async function deliver({ agent, letter }) {
150
+ const result = await runCommand(command, [
151
+ 'queue',
152
+ '--thread',
153
+ agent.sessionId,
154
+ '--message',
155
+ fitsArgument(letter.text)
156
+ ? letter.text
157
+ : tooLongNotice(letter, options.bridgeCommand, bridgeHome),
158
+ '--resume',
159
+ '--cd',
160
+ agent.cwd,
161
+ ], { cwd: agent.cwd, env });
162
+ if (result.code !== 0)
163
+ throw new Error(`codex queue failed: ${failureOf(result)}`);
164
+ return NOT_RESUMED.test(result.stderr) ? { note: CODEX_NOT_RESUMED_NOTE } : undefined;
165
+ }
166
+ async function createSession(request) {
167
+ mkdirSync(logDir, { recursive: true, mode: 0o700 });
168
+ const logPath = join(logDir, `codex-${request.agentName.replace(/[^\w.-]+/g, '_')}-${Date.now()}.log`);
169
+ const log = openSync(logPath, 'a', 0o600);
170
+ let exited;
171
+ let missing = false;
172
+ let pid;
173
+ let ended;
174
+ try {
175
+ const child = spawn(command, [
176
+ 'exec',
177
+ '--json',
178
+ '--skip-git-repo-check',
179
+ '--cd',
180
+ request.cwd,
181
+ '--sandbox',
182
+ options.sandbox ?? 'workspace-write',
183
+ ...(options.sessionArgs ?? []),
184
+ '-',
185
+ ], {
186
+ cwd: request.cwd,
187
+ env: sessionEnv(env, {
188
+ harness: HARNESSES.codex,
189
+ agentName: request.agentName,
190
+ ...(request.sessionName && { sessionName: request.sessionName }),
191
+ }),
192
+ detached: true,
193
+ stdio: ['pipe', log, log],
194
+ });
195
+ ended = new Promise((settle) => {
196
+ child.once('error', (error) => {
197
+ missing = error.code === 'ENOENT';
198
+ exited = { code: null };
199
+ settle(null);
200
+ });
201
+ child.once('exit', (code) => {
202
+ exited = { code };
203
+ settle(code);
204
+ });
205
+ });
206
+ child.stdin?.on('error', () => undefined);
207
+ child.stdin?.end(`${request.firstLetter.text}\n\n${codexReportNotice(request.job.number)}`);
208
+ child.unref();
209
+ pid = child.pid;
210
+ }
211
+ finally {
212
+ closeSync(log);
213
+ }
214
+ /** The thread was never learned, so nothing could reach it: it must not work on unseen */
215
+ const abandon = (error) => {
216
+ if (pid !== undefined && !exited) {
217
+ try {
218
+ process.kill(-pid, 'SIGTERM');
219
+ }
220
+ catch {
221
+ exited = { code: null };
222
+ }
223
+ }
224
+ return error;
225
+ };
226
+ const deadline = Date.now() + (options.threadStartedMs ?? DEFAULT_THREAD_STARTED_MS);
227
+ for (;;) {
228
+ const output = readFileSync(logPath, 'utf8');
229
+ const sessionId = codexThreadId(output);
230
+ if (sessionId) {
231
+ void ended
232
+ .then((code) => reportFor(request, sessionId, logPath, code))
233
+ .catch((error) => {
234
+ if (isBridgeError(error) && error.code === 'job_finished')
235
+ return;
236
+ onError(error instanceof Error ? error : new Error(String(error)));
237
+ });
238
+ return { sessionId, deliveredFirstLetter: true };
239
+ }
240
+ if (missing) {
241
+ throw existsSync(request.cwd)
242
+ ? new CommandMissingError(command)
243
+ : new Error(`The folder ${request.cwd} does not exist`);
244
+ }
245
+ if (exited) {
246
+ throw new Error(`codex exec ended before it started a thread: ${failureOf({ code: exited.code, stdout: output, stderr: '' })}`);
247
+ }
248
+ if (Date.now() >= deadline) {
249
+ throw abandon(new Error(`codex exec did not say which thread it started, its output is in ${logPath}`));
250
+ }
251
+ await pause(LOG_INTERVAL_MS);
252
+ }
253
+ }
254
+ function identify(context) {
255
+ const sessionId = context.env.CODEX_THREAD_ID?.trim();
256
+ if (!sessionId)
257
+ return undefined;
258
+ const folder = resolve(context.cwd);
259
+ return { harness: HARNESSES.codex, sessionId, cwd: folder, project: findProjectRoot(folder) };
260
+ }
261
+ async function health() {
262
+ const checks = [];
263
+ try {
264
+ const version = await runCommand(command, ['--version'], { env });
265
+ if (version.code !== 0)
266
+ throw new Error(failureOf(version));
267
+ checks.push({ id: 'version', title: 'Codex', status: 'ok', detail: version.stdout.trim() });
268
+ }
269
+ catch (error) {
270
+ checks.push({
271
+ id: 'version',
272
+ title: 'Codex',
273
+ status: 'fail',
274
+ detail: error instanceof CommandMissingError ? error.message : String(error),
275
+ fix: 'Install Codex: https://developers.openai.com/codex/cli',
276
+ });
277
+ return checks;
278
+ }
279
+ const queue = await runCommand(command, ['queue', '--help'], { env });
280
+ const queues = queue.code === 0 && /--resume\b/.test(queue.stdout);
281
+ checks.push({
282
+ id: 'queue',
283
+ title: 'Message queue',
284
+ status: queues ? 'ok' : 'fail',
285
+ detail: queues
286
+ ? 'codex queue --resume is there'
287
+ : 'this version has no codex queue --resume: the bridge cannot hand letters to threads',
288
+ ...(!queues && { fix: 'Update Codex: codex update' }),
289
+ });
290
+ const exec = await runCommand(command, ['exec', '--help'], { env });
291
+ const starts = exec.code === 0 && /--json\b/.test(exec.stdout);
292
+ checks.push({
293
+ id: 'exec',
294
+ title: 'Starting threads',
295
+ status: starts ? 'ok' : 'fail',
296
+ detail: starts
297
+ ? 'codex exec --json is there'
298
+ : 'this version has no codex exec --json: the bridge cannot start threads',
299
+ ...(!starts && { fix: 'Update Codex: codex update' }),
300
+ });
301
+ const daemon = await runCommand(command, ['app-server', 'daemon', 'version'], { env });
302
+ const runs = daemon.code === 0;
303
+ checks.push({
304
+ id: 'daemon',
305
+ title: 'Local daemon',
306
+ status: runs ? 'ok' : 'warn',
307
+ detail: runs
308
+ ? 'runs: threads open in no app wake for their mail too'
309
+ : 'does not run: a thread open in the Codex app still wakes, one open nowhere (such as a thread the bridge started) reads its mail only when opened',
310
+ ...(!runs && { fix: DAEMON_START }),
311
+ });
312
+ return checks;
313
+ }
314
+ return {
315
+ harness: HARNESSES.codex,
316
+ delivery: CODEX_DELIVERY,
317
+ capabilities: { createSession: true, push: true, steer: false, nativeWindow: true },
318
+ attach(calls) {
319
+ bridge = calls;
320
+ },
321
+ deliver,
322
+ createSession,
323
+ identify,
324
+ health,
325
+ async close() {
326
+ closed = true;
327
+ },
328
+ };
329
+ }
330
+ //# sourceMappingURL=codex.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"codex.js","sourceRoot":"","sources":["../../src/adapters/codex.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAC3C,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,SAAS,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACnF,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAW1C,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC7C,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAC3D,OAAO,EAAE,SAAS,EAAsC,MAAM,aAAa,CAAC;AAC5E,OAAO,EACL,mBAAmB,EACnB,SAAS,EACT,YAAY,EACZ,KAAK,EACL,UAAU,EACV,UAAU,EACV,aAAa,GACd,MAAM,WAAW,CAAC;AAEnB,wEAAwE;AACxE,MAAM,CAAC,MAAM,cAAc,GAAG,OAAO,CAAC;AA2BtC,MAAM,yBAAyB,GAAG,MAAM,CAAC;AACzC,MAAM,eAAe,GAAG,GAAG,CAAC;AAC5B,MAAM,WAAW,GAAG,0BAA0B,CAAC;AAC/C,MAAM,YAAY,GAAG,+BAA+B,CAAC;AAErD;;;;GAIG;AACH,MAA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,EAAE,cAAc;QACxB,YAAY,EAAE,EAAE,aAAa,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE,YAAY,EAAE,IAAI,EAAE;QACnF,MAAM,CAAC,KAAkB;YACvB,MAAM,GAAG,KAAK,CAAC;QACjB,CAAC;QACD,OAAO;QACP,aAAa;QACb,QAAQ;QACR,MAAM;QACN,KAAK,CAAC,KAAK;YACT,MAAM,GAAG,IAAI,CAAC;QAChB,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,57 @@
1
+ import type { RenderedLetter } from '../types.js';
2
+ /** How a command of a harness ended. */
3
+ export interface CommandResult {
4
+ /** Null when a signal ended it */
5
+ code: number | null;
6
+ stdout: string;
7
+ stderr: string;
8
+ }
9
+ export interface RunCommandOptions {
10
+ cwd?: string;
11
+ env?: NodeJS.ProcessEnv;
12
+ /** Written to the command's stdin, which is then closed */
13
+ input?: string;
14
+ /** 30 s by default. The command is killed when it passes */
15
+ timeoutMs?: number;
16
+ }
17
+ /** The harness's command is not installed, or not on `PATH`. */
18
+ export declare class CommandMissingError extends Error {
19
+ readonly command: string;
20
+ constructor(command: string);
21
+ }
22
+ /**
23
+ * Runs a command of a harness to its end, without a shell.
24
+ *
25
+ * @throws CommandMissingError when the command is not there
26
+ * @throws Error when it does not end in `timeoutMs`
27
+ */
28
+ export declare function runCommand(command: string, args: readonly string[], options?: RunCommandOptions): Promise<CommandResult>;
29
+ /** What a command said when it failed: its stderr, else its stdout, on one line. */
30
+ export declare function failureOf(result: CommandResult): string;
31
+ /**
32
+ * The environment of a session the bridge starts: what belongs to the session the dispatcher
33
+ * itself may run in is taken out (the new session gets its own from its harness), and the
34
+ * bridge's name for the session goes in, so its first call is recognized.
35
+ */
36
+ export declare function sessionEnv(base: NodeJS.ProcessEnv, session: {
37
+ harness: string;
38
+ agentName: string;
39
+ sessionName?: string;
40
+ }): NodeJS.ProcessEnv;
41
+ /**
42
+ * The most bytes of text handed to a harness as one argument. The arguments and the environment
43
+ * of a process share about a megabyte on macOS, and a letter may be 200000 characters long.
44
+ */
45
+ export declare const MAX_ARGUMENT_BYTES = 120000;
46
+ export declare function fitsArgument(text: string): boolean;
47
+ /**
48
+ * What a session gets in place of a letter too long for an argument: the letter's signature and
49
+ * how to read the rest, with the bridge's command line as the session can run it. The letter
50
+ * itself stays unread in the session's inbox.
51
+ */
52
+ export declare function tooLongNotice(letter: RenderedLetter, bridgeCommand?: string, bridgeHome?: string): string;
53
+ /** A value as one word of a shell command line. */
54
+ export declare function shellQuote(value: string): string;
55
+ /** Waits `ms`. The timer does not keep the process alive. */
56
+ export declare function pause(ms: number): Promise<void>;
57
+ //# sourceMappingURL=exec.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"exec.d.ts","sourceRoot":"","sources":["../../src/adapters/exec.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAElD,wCAAwC;AACxC,MAAM,WAAW,aAAa;IAC5B,kCAAkC;IAClC,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IACpB,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,iBAAiB;IAChC,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,GAAG,CAAC,EAAE,MAAM,CAAC,UAAU,CAAC;IACxB,2DAA2D;IAC3D,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,4DAA4D;IAC5D,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,gEAAgE;AAChE,qBAAa,mBAAoB,SAAQ,KAAK;IAChC,QAAQ,CAAC,OAAO,EAAE,MAAM;gBAAf,OAAO,EAAE,MAAM;CAIrC;AAaD;;;;;GAKG;AACH,wBAAgB,UAAU,CACxB,OAAO,EAAE,MAAM,EACf,IAAI,EAAE,SAAS,MAAM,EAAE,EACvB,OAAO,GAAE,iBAAsB,GAC9B,OAAO,CAAC,aAAa,CAAC,CAkDxB;AAED,oFAAoF;AACpF,wBAAgB,SAAS,CAAC,MAAM,EAAE,aAAa,GAAG,MAAM,CAGvD;AAoBD;;;;GAIG;AACH,wBAAgB,UAAU,CACxB,IAAI,EAAE,MAAM,CAAC,UAAU,EACvB,OAAO,EAAE;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAC;IAAC,WAAW,CAAC,EAAE,MAAM,CAAA;CAAE,GACpE,MAAM,CAAC,UAAU,CASnB;AAED;;;GAGG;AACH,eAAO,MAAM,kBAAkB,SAAU,CAAC;AAE1C,wBAAgB,YAAY,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAElD;AAED;;;;GAIG;AACH,wBAAgB,aAAa,CAC3B,MAAM,EAAE,cAAc,EACtB,aAAa,SAAqB,EAClC,UAAU,CAAC,EAAE,MAAM,GAClB,MAAM,CAQR;AAED,mDAAmD;AACnD,wBAAgB,UAAU,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAEhD;AAED,6DAA6D;AAC7D,wBAAgB,KAAK,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAI/C"}
@@ -0,0 +1,149 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { existsSync } from 'node:fs';
3
+ import { AGENT_NAME_ENV, HARNESS_ENV, HARNESS_SESSION_ENV, SESSION_NAME_ENV } from '../registry.js';
4
+ /** The harness's command is not installed, or not on `PATH`. */
5
+ export class CommandMissingError extends Error {
6
+ command;
7
+ constructor(command) {
8
+ super(`${command} is not installed, or not on PATH`);
9
+ this.command = command;
10
+ this.name = 'CommandMissingError';
11
+ }
12
+ }
13
+ const DEFAULT_COMMAND_TIMEOUT_MS = 30_000;
14
+ /**
15
+ * How long the output of a command that exited is still read. A command that leaves a process
16
+ * of its own behind (a background service holding the same pipes) would otherwise never be done.
17
+ */
18
+ const DRAIN_MS = 250;
19
+ /** The most output of a command that is kept: what a harness prints for the bridge is short. */
20
+ const MAX_OUTPUT_CHARS = 1_000_000;
21
+ /**
22
+ * Runs a command of a harness to its end, without a shell.
23
+ *
24
+ * @throws CommandMissingError when the command is not there
25
+ * @throws Error when it does not end in `timeoutMs`
26
+ */
27
+ export function runCommand(command, args, options = {}) {
28
+ const timeoutMs = options.timeoutMs ?? DEFAULT_COMMAND_TIMEOUT_MS;
29
+ return new Promise((resolve, reject) => {
30
+ const child = spawn(command, [...args], {
31
+ ...(options.cwd !== undefined && { cwd: options.cwd }),
32
+ env: options.env ?? process.env,
33
+ stdio: ['pipe', 'pipe', 'pipe'],
34
+ });
35
+ let stdout = '';
36
+ let stderr = '';
37
+ let timedOut = false;
38
+ const timer = setTimeout(() => {
39
+ timedOut = true;
40
+ child.kill('SIGKILL');
41
+ }, timeoutMs);
42
+ child.stdout.setEncoding('utf8').on('data', (chunk) => {
43
+ if (stdout.length < MAX_OUTPUT_CHARS)
44
+ stdout += chunk;
45
+ });
46
+ child.stderr.setEncoding('utf8').on('data', (chunk) => {
47
+ if (stderr.length < MAX_OUTPUT_CHARS)
48
+ stderr += chunk;
49
+ });
50
+ child.stdin.on('error', () => undefined);
51
+ child.stdin.end(options.input ?? '');
52
+ child.once('error', (error) => {
53
+ clearTimeout(timer);
54
+ if (error.code !== 'ENOENT')
55
+ reject(error);
56
+ else if (options.cwd !== undefined && !existsSync(options.cwd)) {
57
+ reject(new Error(`The folder ${options.cwd} does not exist`));
58
+ }
59
+ else
60
+ reject(new CommandMissingError(command));
61
+ });
62
+ child.once('exit', (code) => {
63
+ clearTimeout(timer);
64
+ const settle = () => {
65
+ clearTimeout(drain);
66
+ child.stdout.destroy();
67
+ child.stderr.destroy();
68
+ if (timedOut) {
69
+ reject(new Error(`${command} ${args[0] ?? ''} did not answer in ${Math.round(timeoutMs / 1000)} s`));
70
+ return;
71
+ }
72
+ resolve({ code, stdout, stderr });
73
+ };
74
+ const drain = setTimeout(settle, DRAIN_MS);
75
+ child.once('close', settle);
76
+ });
77
+ });
78
+ }
79
+ /** What a command said when it failed: its stderr, else its stdout, on one line. */
80
+ export function failureOf(result) {
81
+ const said = (result.stderr.trim() || result.stdout.trim()).split(/\r?\n/).slice(0, 3).join(' ');
82
+ return said || `it ended with ${result.code === null ? 'a signal' : `exit code ${result.code}`}`;
83
+ }
84
+ /**
85
+ * What a harness puts into the environment of one session about that session: which session it
86
+ * is, how it was entered, the socket and the token its own messages go through. A dispatcher
87
+ * started from inside a session has them, and a session it starts must not: it is another
88
+ * session, often of another harness.
89
+ */
90
+ const SURROUNDING_SESSION_ENV = [
91
+ 'CLAUDECODE',
92
+ 'CLAUDE_PID',
93
+ 'CLAUDE_PROJECT_DIR',
94
+ 'CLAUDE_CODE_ENTRYPOINT',
95
+ 'CLAUDE_CODE_HOST_SESSION_ID',
96
+ 'CLAUDE_CODE_CHILD_SESSION',
97
+ 'CLAUDE_CODE_SESSION_ATTENDED',
98
+ 'CLAUDE_CODE_MESSAGING_SOCKET',
99
+ 'CLAUDE_CODE_MESSAGING_TOKEN',
100
+ ];
101
+ /**
102
+ * The environment of a session the bridge starts: what belongs to the session the dispatcher
103
+ * itself may run in is taken out (the new session gets its own from its harness), and the
104
+ * bridge's name for the session goes in, so its first call is recognized.
105
+ */
106
+ export function sessionEnv(base, session) {
107
+ const env = { ...base };
108
+ for (const { variable } of HARNESS_SESSION_ENV)
109
+ delete env[variable];
110
+ for (const variable of SURROUNDING_SESSION_ENV)
111
+ delete env[variable];
112
+ delete env[SESSION_NAME_ENV];
113
+ env[HARNESS_ENV] = session.harness;
114
+ env[AGENT_NAME_ENV] = session.agentName;
115
+ if (session.sessionName)
116
+ env[SESSION_NAME_ENV] = session.sessionName;
117
+ return env;
118
+ }
119
+ /**
120
+ * The most bytes of text handed to a harness as one argument. The arguments and the environment
121
+ * of a process share about a megabyte on macOS, and a letter may be 200000 characters long.
122
+ */
123
+ export const MAX_ARGUMENT_BYTES = 120_000;
124
+ export function fitsArgument(text) {
125
+ return Buffer.byteLength(text, 'utf8') <= MAX_ARGUMENT_BYTES;
126
+ }
127
+ /**
128
+ * What a session gets in place of a letter too long for an argument: the letter's signature and
129
+ * how to read the rest, with the bridge's command line as the session can run it. The letter
130
+ * itself stays unread in the session's inbox.
131
+ */
132
+ export function tooLongNotice(letter, bridgeCommand = 'cogitator bridge', bridgeHome) {
133
+ const signature = letter.text.split('\n', 1)[0];
134
+ return (`${signature}\n` +
135
+ `This letter is ${letter.body.length} characters long, too long to hand over here. ` +
136
+ `Read it from the bridge: ${bridgeCommand} inbox --job ${letter.job}` +
137
+ (bridgeHome ? ` --home ${shellQuote(bridgeHome)}` : ''));
138
+ }
139
+ /** A value as one word of a shell command line. */
140
+ export function shellQuote(value) {
141
+ return /^[A-Za-z0-9_@%+=:,./-]+$/.test(value) ? value : `'${value.replaceAll("'", "'\\''")}'`;
142
+ }
143
+ /** Waits `ms`. The timer does not keep the process alive. */
144
+ export function pause(ms) {
145
+ return new Promise((resolve) => {
146
+ setTimeout(resolve, ms).unref();
147
+ });
148
+ }
149
+ //# sourceMappingURL=exec.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"exec.js","sourceRoot":"","sources":["../../src/adapters/exec.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAC3C,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,cAAc,EAAE,WAAW,EAAE,mBAAmB,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAoBpG,gEAAgE;AAChE,MAAM,OAAO,mBAAoB,SAAQ,KAAK;IACvB;IAArB,YAAqB,OAAe;QAClC,KAAK,CAAC,GAAG,OAAO,mCAAmC,CAAC,CAAC;QADlC,YAAO,GAAP,OAAO,CAAQ;QAElC,IAAI,CAAC,IAAI,GAAG,qBAAqB,CAAC;IACpC,CAAC;CACF;AAED,MAAM,0BAA0B,GAAG,MAAM,CAAC;AAE1C;;;GAGG;AACH,MAAM,QAAQ,GAAG,GAA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