@cogitator-ai/bridge 0.3.0 → 0.5.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 (138) hide show
  1. package/README.md +154 -19
  2. package/dist/adapter.d.ts +9 -1
  3. package/dist/adapter.d.ts.map +1 -1
  4. package/dist/adapters/claude.d.ts +55 -0
  5. package/dist/adapters/claude.d.ts.map +1 -1
  6. package/dist/adapters/claude.js +195 -17
  7. package/dist/adapters/claude.js.map +1 -1
  8. package/dist/adapters/codex.d.ts +16 -3
  9. package/dist/adapters/codex.d.ts.map +1 -1
  10. package/dist/adapters/codex.js +58 -9
  11. package/dist/adapters/codex.js.map +1 -1
  12. package/dist/adapters/exec.d.ts +16 -3
  13. package/dist/adapters/exec.d.ts.map +1 -1
  14. package/dist/adapters/exec.js +22 -10
  15. package/dist/adapters/exec.js.map +1 -1
  16. package/dist/adapters/hosted.d.ts +36 -4
  17. package/dist/adapters/hosted.d.ts.map +1 -1
  18. package/dist/adapters/hosted.js +188 -9
  19. package/dist/adapters/hosted.js.map +1 -1
  20. package/dist/adapters/tools-server.d.ts +21 -0
  21. package/dist/adapters/tools-server.d.ts.map +1 -0
  22. package/dist/adapters/tools-server.js +19 -0
  23. package/dist/adapters/tools-server.js.map +1 -0
  24. package/dist/client.d.ts +16 -1
  25. package/dist/client.d.ts.map +1 -1
  26. package/dist/client.js +24 -1
  27. package/dist/client.js.map +1 -1
  28. package/dist/dispatcher.d.ts +115 -3
  29. package/dist/dispatcher.d.ts.map +1 -1
  30. package/dist/dispatcher.js +496 -23
  31. package/dist/dispatcher.js.map +1 -1
  32. package/dist/errors.d.ts +1 -1
  33. package/dist/errors.d.ts.map +1 -1
  34. package/dist/errors.js.map +1 -1
  35. package/dist/guards.d.ts +3 -2
  36. package/dist/guards.d.ts.map +1 -1
  37. package/dist/guards.js +4 -3
  38. package/dist/guards.js.map +1 -1
  39. package/dist/host.d.ts +9 -0
  40. package/dist/host.d.ts.map +1 -1
  41. package/dist/host.js +2 -0
  42. package/dist/host.js.map +1 -1
  43. package/dist/index.d.ts +19 -9
  44. package/dist/index.d.ts.map +1 -1
  45. package/dist/index.js +11 -6
  46. package/dist/index.js.map +1 -1
  47. package/dist/inputs.d.ts +76 -1
  48. package/dist/inputs.d.ts.map +1 -1
  49. package/dist/inputs.js +31 -1
  50. package/dist/inputs.js.map +1 -1
  51. package/dist/job-record.d.ts +1 -0
  52. package/dist/job-record.d.ts.map +1 -1
  53. package/dist/job-record.js +1 -0
  54. package/dist/job-record.js.map +1 -1
  55. package/dist/letters.d.ts.map +1 -1
  56. package/dist/letters.js +23 -1
  57. package/dist/letters.js.map +1 -1
  58. package/dist/person-channel.d.ts +45 -0
  59. package/dist/person-channel.d.ts.map +1 -0
  60. package/dist/person-channel.js +154 -0
  61. package/dist/person-channel.js.map +1 -0
  62. package/dist/person-inbox.d.ts +30 -0
  63. package/dist/person-inbox.d.ts.map +1 -0
  64. package/dist/person-inbox.js +60 -0
  65. package/dist/person-inbox.js.map +1 -0
  66. package/dist/person.d.ts +52 -0
  67. package/dist/person.d.ts.map +1 -0
  68. package/dist/person.js +30 -0
  69. package/dist/person.js.map +1 -0
  70. package/dist/protocol.d.ts +6 -1
  71. package/dist/protocol.d.ts.map +1 -1
  72. package/dist/protocol.js +5 -1
  73. package/dist/protocol.js.map +1 -1
  74. package/dist/rights/index.d.ts +36 -0
  75. package/dist/rights/index.d.ts.map +1 -0
  76. package/dist/rights/index.js +186 -0
  77. package/dist/rights/index.js.map +1 -0
  78. package/dist/server.d.ts.map +1 -1
  79. package/dist/server.js +9 -0
  80. package/dist/server.js.map +1 -1
  81. package/dist/setup/claude.d.ts +53 -0
  82. package/dist/setup/claude.d.ts.map +1 -0
  83. package/dist/setup/claude.js +261 -0
  84. package/dist/setup/claude.js.map +1 -0
  85. package/dist/setup/codex.d.ts +22 -0
  86. package/dist/setup/codex.d.ts.map +1 -0
  87. package/dist/setup/codex.js +95 -0
  88. package/dist/setup/codex.js.map +1 -0
  89. package/dist/setup/files.d.ts +22 -0
  90. package/dist/setup/files.d.ts.map +1 -0
  91. package/dist/setup/files.js +86 -0
  92. package/dist/setup/files.js.map +1 -0
  93. package/dist/setup/index.d.ts +6 -0
  94. package/dist/setup/index.d.ts.map +1 -0
  95. package/dist/setup/index.js +3 -0
  96. package/dist/setup/index.js.map +1 -0
  97. package/dist/setup/setup.d.ts +52 -0
  98. package/dist/setup/setup.d.ts.map +1 -0
  99. package/dist/setup/setup.js +2 -0
  100. package/dist/setup/setup.js.map +1 -0
  101. package/dist/store/sqlite.d.ts +6 -1
  102. package/dist/store/sqlite.d.ts.map +1 -1
  103. package/dist/store/sqlite.js +74 -18
  104. package/dist/store/sqlite.js.map +1 -1
  105. package/dist/store/store.d.ts +6 -2
  106. package/dist/store/store.d.ts.map +1 -1
  107. package/dist/testing/fake-harnesses.d.ts +22 -2
  108. package/dist/testing/fake-harnesses.d.ts.map +1 -1
  109. package/dist/testing/fake-harnesses.js +16 -4
  110. package/dist/testing/fake-harnesses.js.map +1 -1
  111. package/dist/testing/index.d.ts +1 -1
  112. package/dist/testing/index.d.ts.map +1 -1
  113. package/dist/tools/caller.d.ts +39 -0
  114. package/dist/tools/caller.d.ts.map +1 -0
  115. package/dist/tools/caller.js +92 -0
  116. package/dist/tools/caller.js.map +1 -0
  117. package/dist/tools/guidance.d.ts +33 -0
  118. package/dist/tools/guidance.d.ts.map +1 -0
  119. package/dist/tools/guidance.js +93 -0
  120. package/dist/tools/guidance.js.map +1 -0
  121. package/dist/tools/index.d.ts +27 -0
  122. package/dist/tools/index.d.ts.map +1 -0
  123. package/dist/tools/index.js +24 -0
  124. package/dist/tools/index.js.map +1 -0
  125. package/dist/tools/tools.d.ts +38 -0
  126. package/dist/tools/tools.d.ts.map +1 -0
  127. package/dist/tools/tools.js +377 -0
  128. package/dist/tools/tools.js.map +1 -0
  129. package/dist/types.d.ts +81 -1
  130. package/dist/types.d.ts.map +1 -1
  131. package/dist/types.js +29 -0
  132. package/dist/types.js.map +1 -1
  133. package/fakes/claude.mjs +288 -23
  134. package/fakes/codex.mjs +199 -19
  135. package/fakes/lib.mjs +94 -16
  136. package/fakes/mcp.mjs +151 -0
  137. package/fakes/sandbox.mjs +84 -0
  138. package/package.json +18 -1
package/fakes/codex.mjs CHANGED
@@ -1,9 +1,16 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
3
  * A stand-in for the Codex command line as far as the bridge adapters use it: `exec` with JSON
4
- * events, `queue`, the app-server daemon and `delete`. The commands `__open` and `__app` exist
5
- * only here and play the desktop app with its threads. The behaviour was measured on codex-cli
6
- * 0.167.0-alpha.4.1.
4
+ * events, `queue`, the app-server daemon, `mcp` and `delete`. The commands `__open` and `__app`
5
+ * exist only here and play the desktop app with its threads. The behaviour was measured on
6
+ * codex-cli 0.167.0-alpha.4.1.
7
+ *
8
+ * MCP servers: a thread has the servers of `mcp add` and of `-c mcp_servers.<name>.*`. A server
9
+ * is started outside the sandbox of the thread, with next to nothing of the environment and no
10
+ * thread id in it: Codex names the thread in `_meta` of every tool call. A thread of `exec`
11
+ * cannot ask anybody for an approval, so it calls only tools that say they destroy nothing and
12
+ * stay in a closed world. The commands of a sandboxed thread reach no socket and write nowhere
13
+ * outside their folder.
7
14
  */
8
15
  import { randomUUID } from 'node:crypto';
9
16
  import { rmSync, statSync } from 'node:fs';
@@ -34,7 +41,9 @@ import {
34
41
  readJson,
35
42
  recordTurn,
36
43
  renderHelp,
44
+ repeated,
37
45
  runCli,
46
+ sandboxedEnv,
38
47
  sleep,
39
48
  spawnDetached,
40
49
  stateRoot,
@@ -44,6 +53,7 @@ import {
44
53
  unlock,
45
54
  writeJson,
46
55
  } from './lib.mjs';
56
+ import { envPairs, toolServers } from './mcp.mjs';
47
57
 
48
58
  const SELF = fileURLToPath(import.meta.url);
49
59
  const VERSION = '0.167.0-alpha.4.1';
@@ -67,9 +77,14 @@ const EXEC_FLAGS = {
67
77
  '--skip-git-repo-check': flag('skipGitRepoCheck'),
68
78
  '-m': option('model'),
69
79
  '--model': option('model'),
70
- '-c': option('config'),
71
- '--config': option('config'),
80
+ '-c': repeated('config'),
81
+ '--config': repeated('config'),
72
82
  };
83
+ const MCP_ADD_FLAGS = { '--env': repeated('env') };
84
+ const MCP_JSON_FLAGS = { '--json': flag('json') };
85
+ /** What a server of tools gets of the environment of Codex: Codex gives it next to nothing */
86
+ const SERVER_ENV = ['PATH', 'HOME', 'TMPDIR', 'USER', 'LOGNAME', 'SHELL', 'LANG'];
87
+ const NEEDS_APPROVAL = 'MCP tool call requires approval, but approval policy is never';
73
88
  const QUEUE_FLAGS = {
74
89
  ...HELP_FLAGS,
75
90
  ...FOLDER_FLAGS,
@@ -77,7 +92,11 @@ const QUEUE_FLAGS = {
77
92
  '--message': option('message'),
78
93
  '--resume': flag('resume'),
79
94
  };
80
- const OPEN_FLAGS = { ...FOLDER_FLAGS, '--owner': option('owner') };
95
+ const OPEN_FLAGS = {
96
+ ...FOLDER_FLAGS,
97
+ '--owner': option('owner'),
98
+ '--sandbox': option('sandbox'),
99
+ };
81
100
  const DELETE_FLAGS = { '--force': flag('force') };
82
101
 
83
102
  const HELP = [
@@ -90,6 +109,7 @@ const HELP = [
90
109
  ' exec Run Codex non-interactively',
91
110
  ['queue', ' queue Queue a message for a thread'],
92
111
  ' app-server Run the app server or its daemon',
112
+ ' mcp Manage external MCP servers for Codex',
93
113
  ' delete Delete a thread',
94
114
  '',
95
115
  'Options:',
@@ -130,6 +150,7 @@ const missing = () => listedIn('FAKE_CODEX_MISSING');
130
150
  const version = () => process.env.FAKE_CODEX_VERSION || VERSION;
131
151
  const threadsDir = () => join(stateRoot('codex'), 'threads');
132
152
  const ownerFile = (kind) => join(stateRoot('codex'), `${kind}.json`);
153
+ const configFile = () => join(stateRoot('codex'), 'config.json');
133
154
 
134
155
  function threadFiles(threadId) {
135
156
  const base = join(threadsDir(), threadId);
@@ -157,6 +178,8 @@ async function main(argv) {
157
178
  return queue(rest);
158
179
  case 'app-server':
159
180
  return appServer(rest);
181
+ case 'mcp':
182
+ return mcp(rest);
160
183
  case 'delete':
161
184
  return remove(rest);
162
185
  case '__open':
@@ -180,10 +203,50 @@ async function exec(argv) {
180
203
  const { resumed, promptArgument } = execTarget(positionals);
181
204
  const cwd = resumed ? undefined : workFolder(values.cd);
182
205
  const prompt = await promptText(promptArgument);
183
- const thread = resumed ?? createThread({ cwd, sandbox: values.sandbox, owner: 'none' });
206
+ const thread =
207
+ resumed ??
208
+ createThread({
209
+ cwd,
210
+ sandbox: values.sandbox ?? 'read-only',
211
+ owner: 'none',
212
+ servers: { ...configuredServers(), ...overriddenServers(values.config ?? []) },
213
+ });
184
214
  await foregroundTurn(thread, prompt, values.json === true);
185
215
  }
186
216
 
217
+ /** The MCP servers of the configuration, as `mcp add` left them */
218
+ function configuredServers() {
219
+ return readJson(configFile(), {}).mcp_servers ?? {};
220
+ }
221
+
222
+ /**
223
+ * The MCP servers `-c mcp_servers.<name>.<field>=<value>` describes. The values are TOML: a
224
+ * string, an array of strings, or for `env` an inline table of strings.
225
+ * @param {string[]} overrides
226
+ */
227
+ function overriddenServers(overrides) {
228
+ const servers = {};
229
+ for (const override of overrides) {
230
+ const match = /^mcp_servers\.([\w-]+)\.(command|args|env)=(.*)$/s.exec(override);
231
+ if (!match) continue;
232
+ const [, name, field, value] = match;
233
+ servers[name] = { ...servers[name], [field]: tomlValue(field, value) };
234
+ }
235
+ return Object.fromEntries(
236
+ Object.entries(servers).filter(([, server]) => typeof server.command === 'string')
237
+ );
238
+ }
239
+
240
+ function tomlValue(field, value) {
241
+ try {
242
+ if (field !== 'env') return JSON.parse(value);
243
+ const pairs = [...value.matchAll(/([\w-]+)\s*=\s*("(?:[^"\\]|\\.)*")/g)];
244
+ return Object.fromEntries(pairs.map(([, key, text]) => [key, JSON.parse(text)]));
245
+ } catch {
246
+ throw new CliError(`Error: invalid override value: ${value}`);
247
+ }
248
+ }
249
+
187
250
  /** Tells `exec <prompt>` from `exec resume <threadId> <prompt>` */
188
251
  function execTarget(positionals) {
189
252
  const [first, ...rest] = positionals;
@@ -211,8 +274,8 @@ async function promptText(argument) {
211
274
  return prompt;
212
275
  }
213
276
 
214
- function createThread({ cwd, sandbox, owner }) {
215
- const thread = { threadId: randomUUID(), cwd, sandbox, owner, createdAt: Date.now() };
277
+ function createThread({ cwd, sandbox, owner, servers }) {
278
+ const thread = { threadId: randomUUID(), cwd, sandbox, owner, servers, createdAt: Date.now() };
216
279
  writeJson(threadFiles(thread.threadId).record, thread);
217
280
  return thread;
218
281
  }
@@ -254,24 +317,142 @@ async function printEvents(...events) {
254
317
 
255
318
  /** One turn of a thread. The caller holds the lock of the thread */
256
319
  async function threadTurn(thread, input, wokenBy) {
257
- const env = {
258
- ...process.env,
259
- CODEX_THREAD_ID: thread.threadId,
260
- ...(thread.sandbox !== undefined && { FAKE_CODEX_SANDBOX: thread.sandbox }),
261
- };
262
- const outcome = await performTurn({ input, cwd: thread.cwd, env });
263
- recordTurn(threadFiles(thread.threadId).transcript, outcome, wokenBy);
264
- return outcome.answer;
320
+ const env = sandboxedEnv(
321
+ {
322
+ ...process.env,
323
+ CODEX_THREAD_ID: thread.threadId,
324
+ ...(thread.sandbox !== undefined && { FAKE_CODEX_SANDBOX: thread.sandbox }),
325
+ },
326
+ thread.sandbox,
327
+ thread.cwd
328
+ );
329
+ const servers = toolServers(thread.servers ?? {}, {
330
+ cwd: thread.cwd,
331
+ envOf: (config) => ({
332
+ ...Object.fromEntries(
333
+ SERVER_ENV.flatMap((name) =>
334
+ process.env[name] === undefined ? [] : [[name, process.env[name]]]
335
+ )
336
+ ),
337
+ ...config.env,
338
+ }),
339
+ clientInfo: { name: 'codex-mcp-client', title: 'Codex', version: version() },
340
+ });
341
+ const turnId = randomUUID();
342
+ try {
343
+ const outcome = await performTurn({
344
+ input,
345
+ cwd: thread.cwd,
346
+ env,
347
+ callTool: (server, tool, args) => callTool(thread, servers, turnId, server, tool, args),
348
+ });
349
+ recordTurn(threadFiles(thread.threadId).transcript, outcome, wokenBy);
350
+ return outcome.answer;
351
+ } finally {
352
+ servers.close();
353
+ }
354
+ }
355
+
356
+ /** Whether a tool says it changes nothing, or destroys nothing and stays in a closed world */
357
+ function isHarmless(annotations) {
358
+ return (
359
+ annotations?.readOnlyHint === true ||
360
+ (annotations?.destructiveHint === false && annotations?.openWorldHint === false)
361
+ );
362
+ }
363
+
364
+ /**
365
+ * One tool call of a thread. A thread nobody sits at (`exec`) is refused a tool it would have
366
+ * to ask about. The thread is named in `_meta`, the only place a server learns it from.
367
+ */
368
+ async function callTool(thread, servers, turnId, serverName, toolName, args) {
369
+ const found = await servers.get(serverName);
370
+ if (!found) return { text: `unknown MCP server '${serverName}'`, isError: true };
371
+ const tool = found.tools.find(({ name }) => name === toolName);
372
+ if (!tool) return { text: `unknown tool '${toolName}' of '${serverName}'`, isError: true };
373
+ if (thread.owner === 'none' && !isHarmless(tool.annotations)) {
374
+ return { text: NEEDS_APPROVAL, isError: true };
375
+ }
376
+ const { threadId } = thread;
377
+ return found.server.call(toolName, args, {
378
+ callId: `exec-${randomUUID()}`,
379
+ 'x-codex-turn-metadata': {
380
+ session_id: threadId,
381
+ thread_id: threadId,
382
+ turn_id: turnId,
383
+ sandbox_mode: thread.sandbox ?? 'danger-full-access',
384
+ codex_version: version(),
385
+ },
386
+ threadId,
387
+ sessionId: threadId,
388
+ progressToken: 1,
389
+ });
265
390
  }
266
391
 
267
392
  async function open(argv) {
268
393
  const { values, positionals } = parseArgs(argv, OPEN_FLAGS);
269
394
  const owner = values.owner ?? 'app';
270
395
  if (positionals.length > 0 || !THREAD_OWNERS.includes(owner)) throw new Unsupported();
271
- const thread = createThread({ cwd: workFolder(values.cd), owner });
396
+ const thread = createThread({
397
+ cwd: workFolder(values.cd),
398
+ sandbox: values.sandbox,
399
+ owner,
400
+ servers: configuredServers(),
401
+ });
272
402
  await print(thread.threadId);
273
403
  }
274
404
 
405
+ /** `mcp add`, `get`, `list` and `remove`: the servers every new thread gets */
406
+ async function mcp(argv) {
407
+ const [action, ...rest] = argv;
408
+ const servers = configuredServers();
409
+ const save = () => writeJson(configFile(), { mcp_servers: servers });
410
+ const shown = (name) => ({
411
+ name,
412
+ enabled: true,
413
+ disabled_reason: null,
414
+ transport: {
415
+ type: 'stdio',
416
+ command: servers[name].command,
417
+ args: servers[name].args ?? [],
418
+ env: servers[name].env ?? null,
419
+ env_vars: [],
420
+ cwd: null,
421
+ },
422
+ });
423
+ if (action === 'add') {
424
+ const { values, positionals } = parseArgs(rest, MCP_ADD_FLAGS);
425
+ const [name, command, ...args] = positionals;
426
+ const env = envPairs(values.env ?? []);
427
+ if (name === undefined || command === undefined || env === undefined) throw new Unsupported();
428
+ servers[name] = { command, args, ...(Object.keys(env).length > 0 && { env }) };
429
+ save();
430
+ return print(`Added global MCP server '${name}'.`);
431
+ }
432
+ const { values, positionals } = parseArgs(rest, MCP_JSON_FLAGS);
433
+ const [name] = positionals;
434
+ if (action === 'list' && positionals.length === 0) {
435
+ const all = Object.keys(servers).map(shown);
436
+ return print(values.json ? JSON.stringify(all, null, 2) : all.map((s) => s.name).join('\n'));
437
+ }
438
+ if (positionals.length !== 1) throw new Unsupported();
439
+ const known = Object.hasOwn(servers, name);
440
+ if (action === 'get') {
441
+ if (!known) throw new CliError(`Error: No MCP server named '${name}' found.`);
442
+ const { transport } = shown(name);
443
+ return print(
444
+ values.json
445
+ ? JSON.stringify(shown(name), null, 2)
446
+ : `${name}\n enabled: true\n transport: stdio\n command: ${transport.command}\n args: ${transport.args.join(' ')}`
447
+ );
448
+ }
449
+ if (action !== 'remove') throw new Unsupported();
450
+ if (!known) return print(`No MCP server named '${name}' found.`);
451
+ delete servers[name];
452
+ save();
453
+ return print(`Removed global MCP server '${name}'.`);
454
+ }
455
+
275
456
  async function queue(argv) {
276
457
  if (missing().has('queue')) throw new CliError("error: unrecognized subcommand 'queue'", 2);
277
458
  const { values, positionals } = parseArgs(argv, QUEUE_FLAGS);
@@ -297,7 +478,6 @@ function isOwnerAlive(kind) {
297
478
  return pid !== undefined && isAlive(pid);
298
479
  }
299
480
 
300
-
301
481
  async function appServer(argv) {
302
482
  const [group, ...rest] = argv;
303
483
  if (group !== 'daemon') throw new Unsupported();
package/fakes/lib.mjs CHANGED
@@ -92,7 +92,7 @@ export function print(text) {
92
92
  return new Promise((done) => process.stdout.write(`${text}\n`, () => done()));
93
93
  }
94
94
 
95
- /** @typedef {{ key: string, takesValue: boolean }} Flag */
95
+ /** @typedef {{ key: string, takesValue: boolean, repeats?: boolean, greedy?: boolean }} Flag */
96
96
 
97
97
  /** @param {string} key @returns {Flag} */
98
98
  export const flag = (key) => ({ key, takesValue: false });
@@ -100,13 +100,27 @@ export const flag = (key) => ({ key, takesValue: false });
100
100
  /** @param {string} key @returns {Flag} */
101
101
  export const option = (key) => ({ key, takesValue: true });
102
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
+
103
115
  /**
104
116
  * Splits arguments into option values and positionals. An option that takes a value consumes
105
117
  * 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}.
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}.
107
121
  * @param {string[]} argv
108
122
  * @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[] }}
123
+ * @returns {{ values: Record<string, string | string[] | true>, positionals: string[] }}
110
124
  */
111
125
  export function parseArgs(argv, flags) {
112
126
  const values = {};
@@ -116,7 +130,15 @@ export function parseArgs(argv, flags) {
116
130
  const arg = rest.shift();
117
131
  if (arg === '--') positionals.push(...rest.splice(0));
118
132
  else if (arg === '-' || !arg.startsWith('-')) positionals.push(arg);
119
- else Object.assign(values, readOption(arg, rest, flags));
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
+ }
120
142
  }
121
143
  return { values, positionals };
122
144
  }
@@ -126,14 +148,14 @@ function readOption(arg, rest, flags) {
126
148
  const name = cut === -1 ? arg : arg.slice(0, cut);
127
149
  const inline = cut === -1 ? undefined : arg.slice(cut + 1);
128
150
  if (!Object.hasOwn(flags, name)) throw new Unsupported();
129
- const { key, takesValue } = flags[name];
151
+ const { key, takesValue, repeats, greedy } = flags[name];
130
152
  if (!takesValue) {
131
153
  if (inline !== undefined) throw new Unsupported();
132
- return { [key]: true };
154
+ return { key, value: true };
133
155
  }
134
156
  const value = inline ?? rest.shift();
135
157
  if (value === undefined) throw new Unsupported();
136
- return { [key]: value };
158
+ return { key, value, repeats, greedy };
137
159
  }
138
160
 
139
161
  /**
@@ -447,16 +469,24 @@ export function abandonWork() {
447
469
 
448
470
  /** @typedef {{ command: string, code: number | null, stdout: string, stderr: string }} CommandRun */
449
471
 
450
- /** @typedef {{ at: string, input: string, ran: CommandRun[], answer: string }} TurnOutcome */
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 */
451
481
 
452
482
  /**
453
483
  * The directives of an input, in the order of its lines. A line counts after its leading
454
484
  * whitespace is trimmed, a quoted line (`> run: ...`) is not a directive.
455
- * @returns {{ kind: 'run' | 'sleep' | 'say', value: string }[]}
485
+ * @returns {{ kind: 'run' | 'sleep' | 'say' | 'tool', value: string }[]}
456
486
  */
457
487
  function directives(input) {
458
488
  return input.split(/\r?\n/).flatMap((line) => {
459
- const match = /^(run|sleep|say): (.+)$/.exec(line.trimStart());
489
+ const match = /^(run|sleep|say|tool): (.+)$/.exec(line.trimStart());
460
490
  if (!match) return [];
461
491
  const [, kind, text] = match;
462
492
  const value = text.trim();
@@ -471,24 +501,72 @@ async function runCommand(command, cwd, env) {
471
501
  }
472
502
 
473
503
  /**
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`.
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`.
476
533
  * @param {object} turn
477
534
  * @param {string} turn.input
478
535
  * @param {string} turn.cwd where the commands run
479
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
480
538
  * @returns {Promise<TurnOutcome>}
481
539
  */
482
- export async function performTurn({ input, cwd, env }) {
540
+ export async function performTurn({ input, cwd, env, callTool }) {
483
541
  const at = new Date().toISOString();
484
542
  const ran = [];
543
+ const tools = [];
485
544
  let answer = 'ok';
486
545
  for (const { kind, value } of directives(input)) {
487
546
  if (kind === 'run') ran.push(await runCommand(value, cwd, env));
547
+ else if (kind === 'tool') tools.push(await runTool(value, callTool));
488
548
  else if (kind === 'sleep') await sleep(Number(value));
489
549
  else answer = value;
490
550
  }
491
- return { at, input, ran, answer };
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
+ };
492
570
  }
493
571
 
494
572
  function countLines(file) {
@@ -501,7 +579,7 @@ function countLines(file) {
501
579
  * @param {TurnOutcome} outcome
502
580
  * @param {'prompt' | 'user' | 'hook' | 'queue' | 'exec'} wokenBy what started the turn
503
581
  */
504
- export function recordTurn(transcript, { at, input, ran, answer }, wokenBy) {
505
- const turn = { turn: countLines(transcript) + 1, at, input, ran, answer, wokenBy };
582
+ export function recordTurn(transcript, { at, input, ran, tools, answer }, wokenBy) {
583
+ const turn = { turn: countLines(transcript) + 1, at, input, ran, tools, answer, wokenBy };
506
584
  appendFileSync(transcript, `${JSON.stringify(turn)}\n`);
507
585
  }
package/fakes/mcp.mjs ADDED
@@ -0,0 +1,151 @@
1
+ /**
2
+ * The MCP client of the fake harnesses: starts the stdio servers a session is configured with
3
+ * and calls their tools the way the real harnesses do, as far as the bridge depends on it.
4
+ */
5
+ import { spawn } from 'node:child_process';
6
+ import { createInterface } from 'node:readline';
7
+
8
+ const REQUEST_TIMEOUT_MS = 15_000;
9
+ const PROTOCOL_VERSION = '2025-06-18';
10
+
11
+ /**
12
+ * @typedef {object} ServerConfig
13
+ * @property {string} command
14
+ * @property {string[]} [args]
15
+ * @property {Record<string, string>} [env]
16
+ */
17
+
18
+ /** @typedef {{ name: string, annotations?: Record<string, unknown> }} ListedTool */
19
+
20
+ /** @typedef {{ text: string, isError: boolean }} ToolAnswer */
21
+
22
+ /**
23
+ * One running server. Its stderr is dropped: a server writes its diagnostics there.
24
+ * @param {ServerConfig} config
25
+ * @param {object} options
26
+ * @param {string} options.cwd
27
+ * @param {NodeJS.ProcessEnv} options.env the whole environment of the server process
28
+ * @param {{ name: string, title?: string, version: string }} options.clientInfo
29
+ */
30
+ function startServer(config, { cwd, env, clientInfo }) {
31
+ const child = spawn(config.command, config.args ?? [], {
32
+ cwd,
33
+ env,
34
+ stdio: ['pipe', 'pipe', 'ignore'],
35
+ });
36
+ const waiting = new Map();
37
+ let nextId = 0;
38
+ let failure;
39
+ const fail = (error) => {
40
+ failure ??= error;
41
+ for (const { reject, timer } of waiting.values()) {
42
+ clearTimeout(timer);
43
+ reject(failure);
44
+ }
45
+ waiting.clear();
46
+ };
47
+ child.on('error', (error) => fail(new Error(`MCP server failed to start: ${error.message}`)));
48
+ child.on('exit', () => fail(new Error('MCP server exited')));
49
+ child.stdin.on('error', () => undefined);
50
+ createInterface({ input: child.stdout }).on('line', (line) => {
51
+ let message;
52
+ try {
53
+ message = JSON.parse(line);
54
+ } catch {
55
+ return;
56
+ }
57
+ const call = waiting.get(message.id);
58
+ if (!call || message.method !== undefined) return;
59
+ waiting.delete(message.id);
60
+ clearTimeout(call.timer);
61
+ if (message.error) call.reject(new Error(message.error.message ?? 'MCP error'));
62
+ else call.resolve(message.result);
63
+ });
64
+
65
+ const write = (message) => child.stdin.write(`${JSON.stringify(message)}\n`);
66
+ const request = (method, params) =>
67
+ new Promise((resolve, reject) => {
68
+ if (failure) return reject(failure);
69
+ const id = (nextId += 1);
70
+ const timer = setTimeout(() => {
71
+ waiting.delete(id);
72
+ reject(new Error(`MCP server did not answer ${method}`));
73
+ }, REQUEST_TIMEOUT_MS);
74
+ waiting.set(id, { resolve, reject, timer });
75
+ write({ jsonrpc: '2.0', id, method, ...(params !== undefined && { params }) });
76
+ });
77
+
78
+ const ready = (async () => {
79
+ const hello = await request('initialize', {
80
+ protocolVersion: PROTOCOL_VERSION,
81
+ capabilities: {},
82
+ clientInfo,
83
+ });
84
+ write({ jsonrpc: '2.0', method: 'notifications/initialized' });
85
+ const { tools } = await request('tools/list', {});
86
+ return { instructions: hello.instructions, tools };
87
+ })();
88
+ ready.catch(() => undefined);
89
+
90
+ return {
91
+ ready,
92
+ /**
93
+ * @param {string} tool
94
+ * @param {Record<string, unknown>} args
95
+ * @param {Record<string, unknown>} meta
96
+ * @returns {Promise<ToolAnswer>}
97
+ */
98
+ async call(tool, args, meta) {
99
+ const result = await request('tools/call', { name: tool, arguments: args, _meta: meta });
100
+ const text = (result.content ?? [])
101
+ .filter((part) => part.type === 'text')
102
+ .map((part) => part.text)
103
+ .join('\n');
104
+ return { text, isError: result.isError === true };
105
+ },
106
+ close() {
107
+ child.stdin.end();
108
+ child.kill('SIGTERM');
109
+ },
110
+ };
111
+ }
112
+
113
+ /**
114
+ * The servers of one session, each started when a tool of it is first called.
115
+ * @param {Record<string, ServerConfig>} configs by the name the session knows the server by
116
+ * @param {object} options
117
+ * @param {string} options.cwd
118
+ * @param {(config: ServerConfig) => NodeJS.ProcessEnv} options.envOf
119
+ * @param {{ name: string, title?: string, version: string }} options.clientInfo
120
+ */
121
+ export function toolServers(configs, { cwd, envOf, clientInfo }) {
122
+ const running = new Map();
123
+ return {
124
+ names: () => Object.keys(configs),
125
+ /** @returns {Promise<{ server: ReturnType<typeof startServer>, tools: ListedTool[], instructions?: string } | undefined>} */
126
+ async get(name) {
127
+ if (!Object.hasOwn(configs, name)) return undefined;
128
+ if (!running.has(name)) {
129
+ const config = configs[name];
130
+ running.set(name, startServer(config, { cwd, env: envOf(config), clientInfo }));
131
+ }
132
+ const server = running.get(name);
133
+ return { server, ...(await server.ready) };
134
+ },
135
+ close() {
136
+ for (const server of running.values()) server.close();
137
+ running.clear();
138
+ },
139
+ };
140
+ }
141
+
142
+ /** `K=V` pairs of a command line as an object. A pair without `=` is refused with undefined */
143
+ export function envPairs(pairs) {
144
+ const env = {};
145
+ for (const pair of pairs) {
146
+ const cut = pair.indexOf('=');
147
+ if (cut <= 0) return undefined;
148
+ env[pair.slice(0, cut)] = pair.slice(cut + 1);
149
+ }
150
+ return env;
151
+ }