@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
@@ -0,0 +1,715 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * A stand-in for the Claude Code command line as far as the bridge adapters use it: background
4
+ * sessions, their listing, Stop hooks with rewake, `mcp`, `stop` and `rm`. The commands `__open`
5
+ * and `__say` exist only here and play a person at an open window. The behaviour was measured
6
+ * on Claude Code 2.1.292 and 2.1.325.
7
+ *
8
+ * MCP servers: a session has the servers of `--mcp-config` and of `mcp add` (local, project and
9
+ * user scope). A server is started once for the session, with the environment of the session
10
+ * and the id the session had then. Before a tool call the `PreToolUse` hooks whose matcher fits
11
+ * `mcp__<server>__<tool>` run, and one may replace the arguments (`updatedInput`). A background
12
+ * session calls only the tools its settings allow: nobody sits there to be asked.
13
+ */
14
+ import { randomUUID } from 'node:crypto';
15
+ import { existsSync, readFileSync, rmSync } from 'node:fs';
16
+ import { dirname, join, resolve } from 'node:path';
17
+ import { fileURLToPath } from 'node:url';
18
+ import {
19
+ CliError,
20
+ POLL_MS,
21
+ Unsupported,
22
+ abandonWork,
23
+ awaitJson,
24
+ boundLife,
25
+ enqueue,
26
+ flag,
27
+ isAlive,
28
+ isStateName,
29
+ isWithin,
30
+ listRecords,
31
+ listedIn,
32
+ option,
33
+ parseArgs,
34
+ patchJson,
35
+ performTurn,
36
+ print,
37
+ readJson,
38
+ recordTurn,
39
+ renderHelp,
40
+ repeated,
41
+ several,
42
+ runCli,
43
+ sleep,
44
+ spawnDetached,
45
+ startShell,
46
+ stateRoot,
47
+ takeNext,
48
+ terminate,
49
+ writeJson,
50
+ } from './lib.mjs';
51
+ import { envPairs, toolServers } from './mcp.mjs';
52
+
53
+ const SELF = fileURLToPath(import.meta.url);
54
+ const VERSION = '2.1.292';
55
+ const DEFAULT_HOOK_TIMEOUT_S = 600;
56
+ const NOT_TRUSTED =
57
+ 'Workspace not trusted. Run claude once in this folder and accept the trust prompt';
58
+
59
+ const OPEN_FLAGS = {
60
+ '--settings': option('settings'),
61
+ '--mcp-config': several('mcpConfig'),
62
+ '-n': option('name'),
63
+ '--name': option('name'),
64
+ };
65
+ const START_FLAGS = {
66
+ ...OPEN_FLAGS,
67
+ '--bg': flag('bg'),
68
+ '--background': flag('bg'),
69
+ '--permission-mode': option('permissionMode'),
70
+ '--model': option('model'),
71
+ '--append-system-prompt': option('appendSystemPrompt'),
72
+ '--add-dir': option('addDir'),
73
+ };
74
+ const AGENTS_FLAGS = {
75
+ '--json': flag('json'),
76
+ '--all': flag('all'),
77
+ '--cwd': option('cwd'),
78
+ '--help': flag('help'),
79
+ '-h': flag('help'),
80
+ };
81
+
82
+ const MCP_FLAGS = {
83
+ '-s': option('scope'),
84
+ '--scope': option('scope'),
85
+ '-e': repeated('env'),
86
+ '--env': repeated('env'),
87
+ };
88
+ const MCP_SCOPES = ['local', 'project', 'user'];
89
+ const HOOK_TIMEOUT_S = 60;
90
+
91
+ /** What FAKE_CLAUDE_MISSING can take away from the options that start a session */
92
+ const REMOVABLE_START_OPTIONS = [
93
+ ['bg', '--bg'],
94
+ ['settings', '--settings'],
95
+ ];
96
+
97
+ const HELP = [
98
+ 'Usage: claude [options] [command] [prompt]',
99
+ '',
100
+ 'Claude Code - starts an interactive session by default',
101
+ '',
102
+ 'Options:',
103
+ ['bg', ' --bg, --background Start the session in the background and return'],
104
+ ['settings', ' --settings <file-or-json> A settings JSON file or a JSON string to load'],
105
+ ' --mcp-config <configs...> Load MCP servers from JSON files or strings',
106
+ ' -n, --name <name> Set a display name for the session',
107
+ ' --permission-mode <mode> Permission mode to use for the session',
108
+ ' --model <model> Model for the session',
109
+ ' --append-system-prompt <text> Append text to the default system prompt',
110
+ ' --add-dir <dir> An additional folder to allow tool access to',
111
+ ' -v, --version Output the version number',
112
+ ' -h, --help Display help for command',
113
+ '',
114
+ 'Commands:',
115
+ ' agents [options] List sessions',
116
+ ' mcp Configure and manage MCP servers',
117
+ ' attach <id> Attach to a background session',
118
+ ' stop <id> Stop a session',
119
+ ' rm <id> Remove a session',
120
+ ];
121
+
122
+ const AGENTS_HELP = [
123
+ 'Usage: claude agents [options]',
124
+ '',
125
+ 'List sessions',
126
+ '',
127
+ 'Options:',
128
+ ['agents-json', ' --json Print the sessions as a JSON array'],
129
+ ' --all Include stopped sessions',
130
+ ' --cwd <path> Only sessions in this folder or below it',
131
+ ' -h, --help Display help for command',
132
+ ];
133
+
134
+ const missing = () => listedIn('FAKE_CLAUDE_MISSING');
135
+ const trustedFile = () => join(stateRoot('claude'), 'trusted.json');
136
+ const sessionsDir = () => join(stateRoot('claude'), 'sessions');
137
+ /** The file Claude Code keeps a person's configuration in, `.claude.json` */
138
+ const configFile = () =>
139
+ join(process.env.CLAUDE_CONFIG_DIR?.trim() || stateRoot('claude'), '.claude.json');
140
+
141
+ /** The state paths of a session. An id that could lead out of the sessions folder is refused */
142
+ function sessionFiles(sessionId) {
143
+ if (!isStateName(sessionId)) throw new Unsupported();
144
+ const base = join(sessionsDir(), sessionId);
145
+ return { record: `${base}.json`, transcript: `${base}.jsonl`, spool: `${base}.in` };
146
+ }
147
+
148
+ async function main(argv) {
149
+ const [command, ...rest] = argv;
150
+ switch (command) {
151
+ case '--version':
152
+ case '-v':
153
+ return print(`${process.env.FAKE_CLAUDE_VERSION || VERSION} (Claude Code)`);
154
+ case '--help':
155
+ case '-h':
156
+ return print(renderHelp(HELP, missing()));
157
+ case 'agents':
158
+ return agents(rest);
159
+ case 'mcp':
160
+ return mcp(rest);
161
+ case 'stop':
162
+ return stop(rest);
163
+ case 'rm':
164
+ return remove(rest);
165
+ case '__open':
166
+ return open(rest);
167
+ case '__say':
168
+ return say(rest);
169
+ case '__session':
170
+ return runSession(rest);
171
+ default:
172
+ return background(argv);
173
+ }
174
+ }
175
+
176
+ async function background(argv) {
177
+ const { values, positionals } = parseArgs(argv, START_FLAGS);
178
+ const [prompt] = positionals;
179
+ const brokenServers = mcpConfigProblem(values.mcpConfig);
180
+ const promptIsThere = positionals.length === 1 && prompt.trim() !== '';
181
+ const promptWasTaken = positionals.length === 0 && brokenServers !== undefined;
182
+ if (!values.bg || !(promptIsThere || promptWasTaken)) throw new Unsupported();
183
+ for (const [feature, name] of REMOVABLE_START_OPTIONS) {
184
+ if (missing().has(feature) && values[feature] !== undefined) {
185
+ throw new CliError(`error: unknown option '${name}'`);
186
+ }
187
+ }
188
+ if (process.env.FAKE_CLAUDE_BG_FAIL) throw new CliError(process.env.FAKE_CLAUDE_BG_FAIL);
189
+ if (!isTrusted(process.cwd())) throw new CliError(NOT_TRUSTED);
190
+ if (brokenServers !== undefined) {
191
+ const failed = failedSession(values.name, brokenServers);
192
+ return print(`backgrounded · ${failed.id} (idle — send a prompt to start)`);
193
+ }
194
+ const session = startSession({
195
+ kind: 'background',
196
+ name: values.name ?? defaultName(prompt),
197
+ settings: values.settings,
198
+ mcpConfig: values.mcpConfig,
199
+ permissionMode: values.permissionMode,
200
+ prompt,
201
+ });
202
+ await print(`backgrounded · ${session.id} · ${session.name}`);
203
+ }
204
+
205
+ async function open(argv) {
206
+ const { values, positionals } = parseArgs(argv, OPEN_FLAGS);
207
+ if (positionals.length > 0) throw new Unsupported();
208
+ const session = startSession({
209
+ kind: 'interactive',
210
+ name: values.name,
211
+ settings: values.settings,
212
+ mcpConfig: values.mcpConfig,
213
+ });
214
+ await print(session.sessionId);
215
+ }
216
+
217
+ function isTrusted(folder) {
218
+ return readJson(trustedFile(), []).some((trusted) => isWithin(folder, trusted));
219
+ }
220
+
221
+ function defaultName(prompt) {
222
+ return prompt.trim().split(/\s+/).slice(0, 3).join('-').toLowerCase();
223
+ }
224
+
225
+ /**
226
+ * Writes the record of a new session and starts its process. A background session begins busy
227
+ * with its prompt, an interactive one sits idle until somebody types.
228
+ */
229
+ function startSession({ kind, name, settings, mcpConfig, permissionMode, prompt }) {
230
+ checkSettings(settings);
231
+ const brokenServers = mcpConfigProblem(mcpConfig);
232
+ if (brokenServers !== undefined) throw new CliError(`Error: ${brokenServers}`);
233
+ const sessionId = randomUUID();
234
+ const files = sessionFiles(sessionId);
235
+ const inBackground = kind === 'background';
236
+ if (prompt !== undefined) enqueue(files.spool, { wokenBy: 'prompt', text: prompt });
237
+ const record = {
238
+ ...(inBackground && { id: shortId(sessionId) }),
239
+ sessionId,
240
+ name,
241
+ cwd: process.cwd(),
242
+ kind,
243
+ startedAt: Date.now(),
244
+ pid: spawnDetached(SELF, ['__session', sessionId]),
245
+ status: inBackground ? 'busy' : 'idle',
246
+ ...(inBackground && { state: 'working' }),
247
+ settings,
248
+ mcpConfig,
249
+ permissionMode,
250
+ };
251
+ writeJson(files.record, record);
252
+ return record;
253
+ }
254
+
255
+ /**
256
+ * The record of a background session that died before it began: `claude --bg` still says it
257
+ * started one and exits with 0, and `agents --json --all` shows the session as `failed`.
258
+ */
259
+ function failedSession(name, detail) {
260
+ const sessionId = randomUUID();
261
+ const record = {
262
+ id: shortId(sessionId),
263
+ sessionId,
264
+ name,
265
+ cwd: process.cwd(),
266
+ kind: 'background',
267
+ startedAt: Date.now(),
268
+ state: 'failed',
269
+ detail: `exit 1 before init — Error: ${detail}`,
270
+ };
271
+ writeJson(sessionFiles(sessionId).record, record);
272
+ return record;
273
+ }
274
+
275
+ /**
276
+ * What is wrong with the values of `--mcp-config`, if anything. The option takes every argument
277
+ * up to the next option, so a prompt right after it is read as one more file of servers.
278
+ */
279
+ function mcpConfigProblem(values = []) {
280
+ for (const value of values) {
281
+ const file = resolve(process.cwd(), value);
282
+ if (!value.trimStart().startsWith('{') && !existsSync(file)) {
283
+ return `Invalid MCP configuration: MCP config file not found: ${file}`;
284
+ }
285
+ try {
286
+ readSettingsOption(value, process.cwd());
287
+ } catch (error) {
288
+ return `Invalid MCP configuration: ${error.message}`;
289
+ }
290
+ }
291
+ return undefined;
292
+ }
293
+
294
+ const shortId = (sessionId) => sessionId.slice(0, 8);
295
+
296
+ /** The value of `--settings`: a JSON string, or the path of a JSON file */
297
+ function readSettingsOption(value, cwd) {
298
+ const json = value.trimStart().startsWith('{')
299
+ ? value
300
+ : readFileSync(resolve(cwd, value), 'utf8');
301
+ return JSON.parse(json);
302
+ }
303
+
304
+ function checkSettings(value) {
305
+ if (value === undefined) return;
306
+ try {
307
+ readSettingsOption(value, process.cwd());
308
+ } catch (error) {
309
+ throw new CliError(`Error: cannot load --settings: ${error.message}`);
310
+ }
311
+ }
312
+
313
+ /**
314
+ * What a session inherits from the command that started it. Claude Code does not promise a
315
+ * background session the environment of `claude --bg`: with FAKE_CLAUDE_BG_CLEAN_ENV set the
316
+ * fake keeps only what a service started on its own would have, so a test can prove that
317
+ * nothing depends on more.
318
+ */
319
+ function sessionBaseEnv() {
320
+ if (!process.env.FAKE_CLAUDE_BG_CLEAN_ENV) return process.env;
321
+ return Object.fromEntries(
322
+ Object.entries(process.env).filter(
323
+ ([name]) => ['PATH', 'HOME', 'TMPDIR'].includes(name) || name.startsWith('FAKE_')
324
+ )
325
+ );
326
+ }
327
+
328
+ /**
329
+ * The session process: takes the prompt, typed messages and hook wake-ups in the order they
330
+ * arrived, runs a turn for each and fires the Stop hooks after it.
331
+ */
332
+ async function runSession(argv) {
333
+ const [sessionId] = argv;
334
+ if (argv.length !== 1) throw new Unsupported();
335
+ const files = sessionFiles(sessionId);
336
+ const record = await awaitJson(files.record);
337
+ if (record === undefined) return;
338
+ const env = {
339
+ ...sessionBaseEnv(),
340
+ CLAUDE_CODE_SESSION_ID: sessionId,
341
+ CLAUDE_PROJECT_DIR: record.cwd,
342
+ };
343
+ const session = { record, files, env, hookPids: new Set() };
344
+ const servers = toolServers(sessionServers(record), {
345
+ cwd: record.cwd,
346
+ envOf: (config) => ({ ...env, ...config.env }),
347
+ clientInfo: { name: 'claude-code', title: 'Claude Code', version: VERSION },
348
+ });
349
+ boundLife(files.record, () => {
350
+ servers.close();
351
+ endSession(files.record);
352
+ });
353
+ for (;;) {
354
+ const message = await nextMessage(files.spool);
355
+ setActivity(session, 'busy');
356
+ const outcome = await performTurn({
357
+ input: message.text,
358
+ cwd: record.cwd,
359
+ env,
360
+ callTool: (server, tool, args) => callTool(session, servers, server, tool, args),
361
+ });
362
+ setActivity(session, 'idle');
363
+ recordTurn(files.transcript, outcome, message.wokenBy);
364
+ await fireStopHooks(session, outcome.answer, message.wokenBy === 'hook');
365
+ }
366
+ }
367
+
368
+ /**
369
+ * The MCP servers of a session: those of `mcp add` for every project (user scope), of the
370
+ * project's `.mcp.json` and of this person in the project (local scope), from the folder of the
371
+ * session up, and those of `--mcp-config` over them all.
372
+ */
373
+ function sessionServers(record) {
374
+ const config = readJson(configFile(), {});
375
+ const servers = { ...config.mcpServers };
376
+ const folders = [];
377
+ for (let dir = record.cwd; ; dir = dirname(dir)) {
378
+ folders.unshift(dir);
379
+ if (dirname(dir) === dir) break;
380
+ }
381
+ for (const dir of folders) {
382
+ Object.assign(servers, readJson(join(dir, '.mcp.json'), {}).mcpServers);
383
+ Object.assign(servers, config.projects?.[dir]?.mcpServers);
384
+ }
385
+ for (const value of record.mcpConfig ?? []) {
386
+ Object.assign(servers, readSettingsOption(value, record.cwd).mcpServers);
387
+ }
388
+ return servers;
389
+ }
390
+
391
+ /** The settings a session goes by: `--settings` and the two settings files of its project */
392
+ function settingsOf(record) {
393
+ const project = join(record.cwd, '.claude');
394
+ const sources = [
395
+ () => record.settings && readSettingsOption(record.settings, record.cwd),
396
+ () => readJson(join(project, 'settings.json')),
397
+ () => readJson(join(project, 'settings.local.json')),
398
+ ];
399
+ return sources.flatMap((read) => {
400
+ try {
401
+ const settings = read();
402
+ return settings ? [settings] : [];
403
+ } catch {
404
+ return [];
405
+ }
406
+ });
407
+ }
408
+
409
+ function isAllowed(record, toolName, serverName) {
410
+ const allowed = settingsOf(record).flatMap((settings) => settings.permissions?.allow ?? []);
411
+ const rules = [toolName, `mcp__${serverName}`, `mcp__${serverName}__*`];
412
+ return allowed.some((rule) => rules.includes(rule));
413
+ }
414
+
415
+ /**
416
+ * One tool call of a session: the permission of the session, the `PreToolUse` hooks that match
417
+ * the tool, then the call with the arguments the hooks left.
418
+ */
419
+ async function callTool(session, servers, serverName, toolName, args) {
420
+ const { record, files } = session;
421
+ const found = await servers.get(serverName);
422
+ if (!found) return { text: `No MCP server named "${serverName}"`, isError: true };
423
+ if (!found.tools.some(({ name }) => name === toolName)) {
424
+ return { text: `No such tool available: mcp__${serverName}__${toolName}`, isError: true };
425
+ }
426
+ const name = `mcp__${serverName}__${toolName}`;
427
+ if (record.kind === 'background' && !isAllowed(record, name, serverName)) {
428
+ return {
429
+ text: `Claude requested permissions to use ${name}, but you haven't granted it yet.`,
430
+ isError: true,
431
+ };
432
+ }
433
+ const toolUseId = `toolu_${randomUUID().replaceAll('-', '').slice(0, 24)}`;
434
+ let input = args;
435
+ for (const { matcher, hook } of toolHooks(record)) {
436
+ if (!new RegExp(`^(?:${matcher})$`).test(name)) continue;
437
+ const payload = JSON.stringify({
438
+ session_id: record.sessionId,
439
+ transcript_path: files.transcript,
440
+ cwd: record.cwd,
441
+ permission_mode: record.permissionMode ?? 'default',
442
+ hook_event_name: 'PreToolUse',
443
+ tool_name: name,
444
+ tool_input: input,
445
+ tool_use_id: toolUseId,
446
+ });
447
+ const result = await runHook(session, { timeout: HOOK_TIMEOUT_S, ...hook }, payload);
448
+ if (result.code === 2) return { text: result.stderr.trim(), isError: true };
449
+ if (result.code !== 0) continue;
450
+ try {
451
+ const updated = JSON.parse(result.stdout).hookSpecificOutput?.updatedInput;
452
+ if (updated && typeof updated === 'object') input = updated;
453
+ } catch {
454
+ continue;
455
+ }
456
+ }
457
+ const answer = await found.server.call(toolName, input, {
458
+ 'claudecode/toolUseId': toolUseId,
459
+ progressToken: 1,
460
+ });
461
+ return input === args ? answer : { ...answer, sent: input };
462
+ }
463
+
464
+ /** The command hooks of the PreToolUse event, each with the matcher of its group */
465
+ function toolHooks(record) {
466
+ return settingsOf(record).flatMap((settings) => {
467
+ const groups = settings.hooks?.PreToolUse;
468
+ if (!Array.isArray(groups)) return [];
469
+ return groups.flatMap((group) =>
470
+ (Array.isArray(group?.hooks) ? group.hooks : [])
471
+ .filter((hook) => hook?.type === 'command' && typeof hook.command === 'string')
472
+ .map((hook) => ({
473
+ matcher: typeof group.matcher === 'string' ? group.matcher : '.*',
474
+ hook,
475
+ }))
476
+ );
477
+ });
478
+ }
479
+
480
+ /**
481
+ * `mcp add`, `get` and `remove`. Local scope is kept under the folder of the command in the
482
+ * configuration file, user scope at its top, project scope in the `.mcp.json` of the folder.
483
+ */
484
+ async function mcp(argv) {
485
+ const [action, ...rest] = argv;
486
+ const { values, positionals } = parseArgs(rest, MCP_FLAGS);
487
+ const [name, command, ...args] = positionals;
488
+ const cwd = process.cwd();
489
+ if (name === undefined || (values.scope !== undefined && !MCP_SCOPES.includes(values.scope))) {
490
+ throw new Unsupported();
491
+ }
492
+ const places = {
493
+ local: {
494
+ file: configFile(),
495
+ read: (config) => config.projects?.[cwd]?.mcpServers,
496
+ write: (config, servers) => ({
497
+ ...config,
498
+ projects: { ...config.projects, [cwd]: { ...config.projects?.[cwd], mcpServers: servers } },
499
+ }),
500
+ },
501
+ project: {
502
+ file: join(cwd, '.mcp.json'),
503
+ read: (config) => config.mcpServers,
504
+ write: (config, servers) => ({ ...config, mcpServers: servers }),
505
+ },
506
+ user: {
507
+ file: configFile(),
508
+ read: (config) => config.mcpServers,
509
+ write: (config, servers) => ({ ...config, mcpServers: servers }),
510
+ },
511
+ };
512
+ const serversIn = (scope) => places[scope].read(readJson(places[scope].file, {})) ?? {};
513
+ const save = (scope, servers) => {
514
+ const { file, write } = places[scope];
515
+ writeJson(file, write(readJson(file, {}), servers));
516
+ };
517
+
518
+ if (action === 'add') {
519
+ const scope = values.scope ?? 'local';
520
+ const env = envPairs(values.env ?? []);
521
+ if (command === undefined || env === undefined) throw new Unsupported();
522
+ const servers = serversIn(scope);
523
+ if (Object.hasOwn(servers, name)) {
524
+ throw new CliError(`MCP server ${name} already exists in ${scope} config`);
525
+ }
526
+ save(scope, { ...servers, [name]: { type: 'stdio', command, args, env } });
527
+ return print(
528
+ `Added stdio MCP server ${name} with command: ${[command, ...args].join(' ')} to ${scope} config`
529
+ );
530
+ }
531
+ if (positionals.length !== 1) throw new Unsupported();
532
+ const scopes = values.scope ? [values.scope] : MCP_SCOPES;
533
+ const scope = scopes.find((candidate) => Object.hasOwn(serversIn(candidate), name));
534
+ if (action === 'get') {
535
+ if (!scope) throw new CliError(`No MCP server named "${name}".`);
536
+ const server = serversIn(scope)[name];
537
+ return print(
538
+ `${name}:\n Scope: ${scope}\n Type: stdio\n Command: ${server.command}\n Args: ${(server.args ?? []).join(' ')}`
539
+ );
540
+ }
541
+ if (action !== 'remove') throw new Unsupported();
542
+ if (!scope) {
543
+ throw new CliError(
544
+ values.scope
545
+ ? `No MCP server named "${name}" in ${values.scope} scope`
546
+ : `No MCP server named "${name}"`
547
+ );
548
+ }
549
+ const { [name]: _removed, ...kept } = serversIn(scope);
550
+ save(scope, kept);
551
+ return print(`Removed MCP server ${name} from ${scope} config`);
552
+ }
553
+
554
+ async function nextMessage(spool) {
555
+ for (;;) {
556
+ const message = takeNext(spool);
557
+ if (message !== undefined) return message;
558
+ await sleep(POLL_MS);
559
+ }
560
+ }
561
+
562
+ function setActivity({ record, files }, status) {
563
+ const state = status === 'busy' ? 'working' : 'done';
564
+ patchJson(files.record, record.kind === 'background' ? { status, state } : { status });
565
+ }
566
+
567
+ function endSession(recordFile) {
568
+ abandonWork();
569
+ patchJson(recordFile, {
570
+ pid: undefined,
571
+ status: undefined,
572
+ hookPids: undefined,
573
+ state: 'stopped',
574
+ });
575
+ process.exit(0);
576
+ }
577
+
578
+ /**
579
+ * Runs the Stop hooks of a session that just went idle. The session waits for a plain hook,
580
+ * a hook with `asyncRewake` or `async` is left running, also across later turns.
581
+ */
582
+ async function fireStopHooks(session, answer, wokenByHook) {
583
+ const { record, files } = session;
584
+ const payload = JSON.stringify({
585
+ session_id: record.sessionId,
586
+ transcript_path: files.transcript,
587
+ cwd: record.cwd,
588
+ permission_mode: record.permissionMode ?? 'default',
589
+ hook_event_name: 'Stop',
590
+ stop_hook_active: wokenByHook,
591
+ last_assistant_message: answer,
592
+ });
593
+ for (const hook of stopHooks(record)) {
594
+ const ended = runHook(session, hook, payload);
595
+ if (hook.asyncRewake === true) void ended.then((result) => wake(files, rewakeText(result)));
596
+ else if (hook.async !== true) wake(files, blockingText(await ended));
597
+ }
598
+ }
599
+
600
+ /** The command hooks of the Stop event from `--settings` and the two project settings files */
601
+ function stopHooks(record) {
602
+ return settingsOf(record).flatMap((settings) => commandHooks(settings));
603
+ }
604
+
605
+ function commandHooks(settings) {
606
+ const groups = settings?.hooks?.Stop;
607
+ if (!Array.isArray(groups)) return [];
608
+ return groups
609
+ .flatMap((group) => (Array.isArray(group?.hooks) ? group.hooks : []))
610
+ .filter((hook) => hook?.type === 'command' && typeof hook.command === 'string');
611
+ }
612
+
613
+ function runHook(session, hook, payload) {
614
+ const timeoutS = typeof hook.timeout === 'number' ? hook.timeout : DEFAULT_HOOK_TIMEOUT_S;
615
+ const shell = startShell(hook.command, {
616
+ cwd: session.record.cwd,
617
+ env: session.env,
618
+ input: payload,
619
+ timeoutMs: timeoutS * 1000,
620
+ killSignal: 'SIGTERM',
621
+ });
622
+ if (shell.pid === undefined) return shell.done;
623
+ trackHook(session, (pids) => pids.add(shell.pid));
624
+ return shell.done.finally(() => trackHook(session, (pids) => pids.delete(shell.pid)));
625
+ }
626
+
627
+ /** Keeps the pids of the running hooks in the record, for whoever has to clean up after a crash */
628
+ function trackHook(session, change) {
629
+ change(session.hookPids);
630
+ patchJson(session.files.record, { hookPids: [...session.hookPids] });
631
+ }
632
+
633
+ const asksForTurn = ({ code, timedOut }) => code === 2 && !timedOut;
634
+
635
+ function blockingText(result) {
636
+ return (asksForTurn(result) && result.stderr.trim()) || undefined;
637
+ }
638
+
639
+ function rewakeText(result) {
640
+ return asksForTurn(result) ? result.stderr.trim() || result.stdout.trim() : undefined;
641
+ }
642
+
643
+ function wake(files, text) {
644
+ if (text !== undefined) enqueue(files.spool, { wokenBy: 'hook', text });
645
+ }
646
+
647
+ /** A record as it stands now: a session whose process is gone counts as stopped, unless it never began */
648
+ function current(record) {
649
+ if (record.state === 'failed') return record;
650
+ if (record.pid !== undefined && isAlive(record.pid)) return record;
651
+ return { ...record, pid: undefined, status: undefined, hookPids: undefined, state: 'stopped' };
652
+ }
653
+
654
+ function listSessions() {
655
+ return listRecords(sessionsDir())
656
+ .map(current)
657
+ .sort((a, b) => a.startedAt - b.startedAt);
658
+ }
659
+
660
+ /** Finds a session by its session id or short id, or else the newest one with that name */
661
+ function findSession(argv) {
662
+ const [ref] = argv;
663
+ if (argv.length !== 1) throw new Unsupported();
664
+ const newestFirst = listSessions().reverse();
665
+ const found =
666
+ newestFirst.find(({ sessionId }) => sessionId === ref || shortId(sessionId) === ref) ??
667
+ newestFirst.find(({ name }) => name === ref);
668
+ if (found === undefined) throw new CliError(`No session found for '${ref}'`);
669
+ return found;
670
+ }
671
+
672
+ async function agents(argv) {
673
+ const { values, positionals } = parseArgs(argv, AGENTS_FLAGS);
674
+ if (values.help) return print(renderHelp(AGENTS_HELP, missing()));
675
+ if (values.json && missing().has('agents-json'))
676
+ throw new CliError("error: unknown option '--json'");
677
+ if (!values.json || positionals.length > 0) throw new Unsupported();
678
+ const sessions = listSessions()
679
+ .filter(({ pid }) => values.all || pid !== undefined)
680
+ .filter(({ cwd }) => values.cwd === undefined || isWithin(cwd, values.cwd));
681
+ await print(JSON.stringify(sessions.map(listed), null, 2));
682
+ }
683
+
684
+ /** What `agents --json` shows of a session: `id` and `state` are there for background ones only */
685
+ function listed({ id, sessionId, name, cwd, kind, startedAt, pid, status, state }) {
686
+ const shown = { id, sessionId, name, cwd, kind, startedAt, pid, status };
687
+ return kind === 'background' ? { ...shown, state } : shown;
688
+ }
689
+
690
+ async function stopSession({ pid }) {
691
+ if (pid !== undefined) await terminate(pid);
692
+ }
693
+
694
+ async function stop(argv) {
695
+ await stopSession(findSession(argv));
696
+ }
697
+
698
+ async function remove(argv) {
699
+ const session = findSession(argv);
700
+ await stopSession(session);
701
+ const files = sessionFiles(session.sessionId);
702
+ rmSync(files.record, { force: true });
703
+ rmSync(files.transcript, { force: true });
704
+ rmSync(files.spool, { recursive: true, force: true });
705
+ }
706
+
707
+ async function say(argv) {
708
+ const [ref, text] = argv;
709
+ if (argv.length !== 2) throw new Unsupported();
710
+ const session = findSession([ref]);
711
+ if (session.pid === undefined) throw new CliError(`Session '${ref}' is not running`);
712
+ enqueue(sessionFiles(session.sessionId).spool, { wokenBy: 'user', text });
713
+ }
714
+
715
+ await runCli('claude', main);