@cogitator-ai/bridge 0.3.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 (75) hide show
  1. package/README.md +95 -9
  2. package/dist/adapter.d.ts +7 -0
  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/tools-server.d.ts +21 -0
  17. package/dist/adapters/tools-server.d.ts.map +1 -0
  18. package/dist/adapters/tools-server.js +19 -0
  19. package/dist/adapters/tools-server.js.map +1 -0
  20. package/dist/dispatcher.d.ts +2 -0
  21. package/dist/dispatcher.d.ts.map +1 -1
  22. package/dist/dispatcher.js +3 -0
  23. package/dist/dispatcher.js.map +1 -1
  24. package/dist/index.d.ts +8 -4
  25. package/dist/index.d.ts.map +1 -1
  26. package/dist/index.js +5 -3
  27. package/dist/index.js.map +1 -1
  28. package/dist/setup/claude.d.ts +53 -0
  29. package/dist/setup/claude.d.ts.map +1 -0
  30. package/dist/setup/claude.js +261 -0
  31. package/dist/setup/claude.js.map +1 -0
  32. package/dist/setup/codex.d.ts +22 -0
  33. package/dist/setup/codex.d.ts.map +1 -0
  34. package/dist/setup/codex.js +95 -0
  35. package/dist/setup/codex.js.map +1 -0
  36. package/dist/setup/files.d.ts +22 -0
  37. package/dist/setup/files.d.ts.map +1 -0
  38. package/dist/setup/files.js +86 -0
  39. package/dist/setup/files.js.map +1 -0
  40. package/dist/setup/index.d.ts +6 -0
  41. package/dist/setup/index.d.ts.map +1 -0
  42. package/dist/setup/index.js +3 -0
  43. package/dist/setup/index.js.map +1 -0
  44. package/dist/setup/setup.d.ts +52 -0
  45. package/dist/setup/setup.d.ts.map +1 -0
  46. package/dist/setup/setup.js +2 -0
  47. package/dist/setup/setup.js.map +1 -0
  48. package/dist/testing/fake-harnesses.d.ts +22 -2
  49. package/dist/testing/fake-harnesses.d.ts.map +1 -1
  50. package/dist/testing/fake-harnesses.js +16 -4
  51. package/dist/testing/fake-harnesses.js.map +1 -1
  52. package/dist/testing/index.d.ts +1 -1
  53. package/dist/testing/index.d.ts.map +1 -1
  54. package/dist/tools/caller.d.ts +39 -0
  55. package/dist/tools/caller.d.ts.map +1 -0
  56. package/dist/tools/caller.js +92 -0
  57. package/dist/tools/caller.js.map +1 -0
  58. package/dist/tools/guidance.d.ts +33 -0
  59. package/dist/tools/guidance.d.ts.map +1 -0
  60. package/dist/tools/guidance.js +92 -0
  61. package/dist/tools/guidance.js.map +1 -0
  62. package/dist/tools/index.d.ts +27 -0
  63. package/dist/tools/index.d.ts.map +1 -0
  64. package/dist/tools/index.js +24 -0
  65. package/dist/tools/index.js.map +1 -0
  66. package/dist/tools/tools.d.ts +38 -0
  67. package/dist/tools/tools.d.ts.map +1 -0
  68. package/dist/tools/tools.js +354 -0
  69. package/dist/tools/tools.js.map +1 -0
  70. package/fakes/claude.mjs +288 -23
  71. package/fakes/codex.mjs +199 -19
  72. package/fakes/lib.mjs +94 -16
  73. package/fakes/mcp.mjs +151 -0
  74. package/fakes/sandbox.mjs +84 -0
  75. package/package.json +13 -1
package/fakes/claude.mjs CHANGED
@@ -1,13 +1,19 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
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, `stop` and `rm`. The commands `__open` and
5
- * `__say` exist only here and play a person at an open window. The behaviour was measured on
6
- * Claude Code 2.1.292.
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.
7
13
  */
8
14
  import { randomUUID } from 'node:crypto';
9
- import { readFileSync, rmSync } from 'node:fs';
10
- import { join, resolve } from 'node:path';
15
+ import { existsSync, readFileSync, rmSync } from 'node:fs';
16
+ import { dirname, join, resolve } from 'node:path';
11
17
  import { fileURLToPath } from 'node:url';
12
18
  import {
13
19
  CliError,
@@ -31,6 +37,8 @@ import {
31
37
  readJson,
32
38
  recordTurn,
33
39
  renderHelp,
40
+ repeated,
41
+ several,
34
42
  runCli,
35
43
  sleep,
36
44
  spawnDetached,
@@ -40,6 +48,7 @@ import {
40
48
  terminate,
41
49
  writeJson,
42
50
  } from './lib.mjs';
51
+ import { envPairs, toolServers } from './mcp.mjs';
43
52
 
44
53
  const SELF = fileURLToPath(import.meta.url);
45
54
  const VERSION = '2.1.292';
@@ -49,6 +58,7 @@ const NOT_TRUSTED =
49
58
 
50
59
  const OPEN_FLAGS = {
51
60
  '--settings': option('settings'),
61
+ '--mcp-config': several('mcpConfig'),
52
62
  '-n': option('name'),
53
63
  '--name': option('name'),
54
64
  };
@@ -69,6 +79,15 @@ const AGENTS_FLAGS = {
69
79
  '-h': flag('help'),
70
80
  };
71
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
+
72
91
  /** What FAKE_CLAUDE_MISSING can take away from the options that start a session */
73
92
  const REMOVABLE_START_OPTIONS = [
74
93
  ['bg', '--bg'],
@@ -83,6 +102,7 @@ const HELP = [
83
102
  'Options:',
84
103
  ['bg', ' --bg, --background Start the session in the background and return'],
85
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',
86
106
  ' -n, --name <name> Set a display name for the session',
87
107
  ' --permission-mode <mode> Permission mode to use for the session',
88
108
  ' --model <model> Model for the session',
@@ -93,6 +113,7 @@ const HELP = [
93
113
  '',
94
114
  'Commands:',
95
115
  ' agents [options] List sessions',
116
+ ' mcp Configure and manage MCP servers',
96
117
  ' attach <id> Attach to a background session',
97
118
  ' stop <id> Stop a session',
98
119
  ' rm <id> Remove a session',
@@ -113,6 +134,9 @@ const AGENTS_HELP = [
113
134
  const missing = () => listedIn('FAKE_CLAUDE_MISSING');
114
135
  const trustedFile = () => join(stateRoot('claude'), 'trusted.json');
115
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');
116
140
 
117
141
  /** The state paths of a session. An id that could lead out of the sessions folder is refused */
118
142
  function sessionFiles(sessionId) {
@@ -132,6 +156,8 @@ async function main(argv) {
132
156
  return print(renderHelp(HELP, missing()));
133
157
  case 'agents':
134
158
  return agents(rest);
159
+ case 'mcp':
160
+ return mcp(rest);
135
161
  case 'stop':
136
162
  return stop(rest);
137
163
  case 'rm':
@@ -150,7 +176,10 @@ async function main(argv) {
150
176
  async function background(argv) {
151
177
  const { values, positionals } = parseArgs(argv, START_FLAGS);
152
178
  const [prompt] = positionals;
153
- if (!values.bg || positionals.length !== 1 || prompt.trim() === '') throw new Unsupported();
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();
154
183
  for (const [feature, name] of REMOVABLE_START_OPTIONS) {
155
184
  if (missing().has(feature) && values[feature] !== undefined) {
156
185
  throw new CliError(`error: unknown option '${name}'`);
@@ -158,10 +187,15 @@ async function background(argv) {
158
187
  }
159
188
  if (process.env.FAKE_CLAUDE_BG_FAIL) throw new CliError(process.env.FAKE_CLAUDE_BG_FAIL);
160
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
+ }
161
194
  const session = startSession({
162
195
  kind: 'background',
163
196
  name: values.name ?? defaultName(prompt),
164
197
  settings: values.settings,
198
+ mcpConfig: values.mcpConfig,
165
199
  permissionMode: values.permissionMode,
166
200
  prompt,
167
201
  });
@@ -175,6 +209,7 @@ async function open(argv) {
175
209
  kind: 'interactive',
176
210
  name: values.name,
177
211
  settings: values.settings,
212
+ mcpConfig: values.mcpConfig,
178
213
  });
179
214
  await print(session.sessionId);
180
215
  }
@@ -191,8 +226,10 @@ function defaultName(prompt) {
191
226
  * Writes the record of a new session and starts its process. A background session begins busy
192
227
  * with its prompt, an interactive one sits idle until somebody types.
193
228
  */
194
- function startSession({ kind, name, settings, permissionMode, prompt }) {
229
+ function startSession({ kind, name, settings, mcpConfig, permissionMode, prompt }) {
195
230
  checkSettings(settings);
231
+ const brokenServers = mcpConfigProblem(mcpConfig);
232
+ if (brokenServers !== undefined) throw new CliError(`Error: ${brokenServers}`);
196
233
  const sessionId = randomUUID();
197
234
  const files = sessionFiles(sessionId);
198
235
  const inBackground = kind === 'background';
@@ -208,12 +245,52 @@ function startSession({ kind, name, settings, permissionMode, prompt }) {
208
245
  status: inBackground ? 'busy' : 'idle',
209
246
  ...(inBackground && { state: 'working' }),
210
247
  settings,
248
+ mcpConfig,
211
249
  permissionMode,
212
250
  };
213
251
  writeJson(files.record, record);
214
252
  return record;
215
253
  }
216
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
+
217
294
  const shortId = (sessionId) => sessionId.slice(0, 8);
218
295
 
219
296
  /** The value of `--settings`: a JSON string, or the path of a JSON file */
@@ -264,17 +341,216 @@ async function runSession(argv) {
264
341
  CLAUDE_PROJECT_DIR: record.cwd,
265
342
  };
266
343
  const session = { record, files, env, hookPids: new Set() };
267
- boundLife(files.record, () => endSession(files.record));
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
+ });
268
353
  for (;;) {
269
354
  const message = await nextMessage(files.spool);
270
355
  setActivity(session, 'busy');
271
- const outcome = await performTurn({ input: message.text, cwd: record.cwd, env });
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
+ });
272
362
  setActivity(session, 'idle');
273
363
  recordTurn(files.transcript, outcome, message.wokenBy);
274
364
  await fireStopHooks(session, outcome.answer, message.wokenBy === 'hook');
275
365
  }
276
366
  }
277
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
+
278
554
  async function nextMessage(spool) {
279
555
  for (;;) {
280
556
  const message = takeNext(spool);
@@ -323,19 +599,7 @@ async function fireStopHooks(session, answer, wokenByHook) {
323
599
 
324
600
  /** The command hooks of the Stop event from `--settings` and the two project settings files */
325
601
  function stopHooks(record) {
326
- const project = join(record.cwd, '.claude');
327
- const sources = [
328
- () => record.settings && readSettingsOption(record.settings, record.cwd),
329
- () => readJson(join(project, 'settings.json')),
330
- () => readJson(join(project, 'settings.local.json')),
331
- ];
332
- return sources.flatMap((read) => {
333
- try {
334
- return commandHooks(read());
335
- } catch {
336
- return [];
337
- }
338
- });
602
+ return settingsOf(record).flatMap((settings) => commandHooks(settings));
339
603
  }
340
604
 
341
605
  function commandHooks(settings) {
@@ -380,8 +644,9 @@ function wake(files, text) {
380
644
  if (text !== undefined) enqueue(files.spool, { wokenBy: 'hook', text });
381
645
  }
382
646
 
383
- /** A record as it stands now: a session whose process is gone counts as stopped */
647
+ /** A record as it stands now: a session whose process is gone counts as stopped, unless it never began */
384
648
  function current(record) {
649
+ if (record.state === 'failed') return record;
385
650
  if (record.pid !== undefined && isAlive(record.pid)) return record;
386
651
  return { ...record, pid: undefined, status: undefined, hookPids: undefined, state: 'stopped' };
387
652
  }