@cogitator-ai/bridge 0.5.0 → 0.6.1

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 (70) hide show
  1. package/README.md +19 -16
  2. package/dist/adapter.d.ts +33 -2
  3. package/dist/adapter.d.ts.map +1 -1
  4. package/dist/adapters/claude.d.ts +95 -2
  5. package/dist/adapters/claude.d.ts.map +1 -1
  6. package/dist/adapters/claude.js +207 -3
  7. package/dist/adapters/claude.js.map +1 -1
  8. package/dist/adapters/hosted.d.ts +3 -2
  9. package/dist/adapters/hosted.d.ts.map +1 -1
  10. package/dist/adapters/hosted.js +2 -1
  11. package/dist/adapters/hosted.js.map +1 -1
  12. package/dist/client.d.ts +11 -1
  13. package/dist/client.d.ts.map +1 -1
  14. package/dist/client.js +14 -0
  15. package/dist/client.js.map +1 -1
  16. package/dist/dispatcher.d.ts +33 -1
  17. package/dist/dispatcher.d.ts.map +1 -1
  18. package/dist/dispatcher.js +112 -4
  19. package/dist/dispatcher.js.map +1 -1
  20. package/dist/index.d.ts +7 -5
  21. package/dist/index.d.ts.map +1 -1
  22. package/dist/index.js +2 -1
  23. package/dist/index.js.map +1 -1
  24. package/dist/inputs.d.ts +24 -0
  25. package/dist/inputs.d.ts.map +1 -1
  26. package/dist/inputs.js +4 -0
  27. package/dist/inputs.js.map +1 -1
  28. package/dist/permit.d.ts +43 -0
  29. package/dist/permit.d.ts.map +1 -0
  30. package/dist/permit.js +118 -0
  31. package/dist/permit.js.map +1 -0
  32. package/dist/person-channel.d.ts.map +1 -1
  33. package/dist/person-channel.js +6 -0
  34. package/dist/person-channel.js.map +1 -1
  35. package/dist/person-inbox.d.ts +2 -1
  36. package/dist/person-inbox.d.ts.map +1 -1
  37. package/dist/person-inbox.js +10 -1
  38. package/dist/person-inbox.js.map +1 -1
  39. package/dist/person.d.ts +13 -0
  40. package/dist/person.d.ts.map +1 -1
  41. package/dist/person.js +1 -0
  42. package/dist/person.js.map +1 -1
  43. package/dist/protocol.d.ts +2 -0
  44. package/dist/protocol.d.ts.map +1 -1
  45. package/dist/protocol.js +2 -0
  46. package/dist/protocol.js.map +1 -1
  47. package/dist/server.d.ts.map +1 -1
  48. package/dist/server.js +2 -0
  49. package/dist/server.js.map +1 -1
  50. package/dist/setup/claude.d.ts +4 -2
  51. package/dist/setup/claude.d.ts.map +1 -1
  52. package/dist/setup/claude.js +9 -3
  53. package/dist/setup/claude.js.map +1 -1
  54. package/dist/testing/fake-harnesses.d.ts +15 -2
  55. package/dist/testing/fake-harnesses.d.ts.map +1 -1
  56. package/dist/testing/fake-harnesses.js +17 -2
  57. package/dist/testing/fake-harnesses.js.map +1 -1
  58. package/dist/tools/index.d.ts +1 -1
  59. package/dist/tools/index.js +1 -1
  60. package/dist/tools/tools.d.ts +1 -1
  61. package/dist/tools/tools.js +2 -2
  62. package/dist/tools/tools.js.map +1 -1
  63. package/dist/types.d.ts +6 -0
  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/fakes/claude.mjs +175 -8
  68. package/fakes/lib.mjs +58 -7
  69. package/fakes/mcp.mjs +6 -1
  70. package/package.json +4 -4
package/fakes/claude.mjs CHANGED
@@ -53,6 +53,7 @@ import { envPairs, toolServers } from './mcp.mjs';
53
53
  const SELF = fileURLToPath(import.meta.url);
54
54
  const VERSION = '2.1.292';
55
55
  const DEFAULT_HOOK_TIMEOUT_S = 600;
56
+ const DEFAULT_NOTICE_MS = 100;
56
57
  const NOT_TRUSTED =
57
58
  'Workspace not trusted. Run claude once in this folder and accept the trust prompt';
58
59
 
@@ -142,7 +143,12 @@ const configFile = () =>
142
143
  function sessionFiles(sessionId) {
143
144
  if (!isStateName(sessionId)) throw new Unsupported();
144
145
  const base = join(sessionsDir(), sessionId);
145
- return { record: `${base}.json`, transcript: `${base}.jsonl`, spool: `${base}.in` };
146
+ return {
147
+ record: `${base}.json`,
148
+ transcript: `${base}.jsonl`,
149
+ spool: `${base}.in`,
150
+ answer: `${base}.answer`,
151
+ };
146
152
  }
147
153
 
148
154
  async function main(argv) {
@@ -166,6 +172,8 @@ async function main(argv) {
166
172
  return open(rest);
167
173
  case '__say':
168
174
  return say(rest);
175
+ case '__answer':
176
+ return answerPrompt(rest);
169
177
  case '__session':
170
178
  return runSession(rest);
171
179
  default:
@@ -358,6 +366,7 @@ async function runSession(argv) {
358
366
  cwd: record.cwd,
359
367
  env,
360
368
  callTool: (server, tool, args) => callTool(session, servers, server, tool, args),
369
+ askLeave: ({ tool, input }) => leaveFor(session, tool, input),
361
370
  });
362
371
  setActivity(session, 'idle');
363
372
  recordTurn(files.transcript, outcome, message.wokenBy);
@@ -461,22 +470,158 @@ async function callTool(session, servers, serverName, toolName, args) {
461
470
  return input === args ? answer : { ...answer, sent: input };
462
471
  }
463
472
 
464
- /** The command hooks of the PreToolUse event, each with the matcher of its group */
465
- function toolHooks(record) {
473
+ /**
474
+ * Whether a permission rule covers a call: the name of the tool alone, or the tool with a
475
+ * pattern for its command or file. `Bash(git push *)` and `Bash(git push:*)` cover what starts
476
+ * with the words, `Bash(git status)` that command only.
477
+ */
478
+ function ruleCovers(rule, toolName, input) {
479
+ if (rule === toolName) return true;
480
+ const match = /^([\w-]+)\((.*)\)$/.exec(rule);
481
+ if (!match || match[1] !== toolName) return false;
482
+ const [, , pattern] = match;
483
+ const subject = String(input.command ?? input.file_path ?? '');
484
+ if (pattern.endsWith(':*')) return subject.startsWith(pattern.slice(0, -2));
485
+ if (pattern.endsWith(' *')) {
486
+ return subject === pattern.slice(0, -2) || subject.startsWith(pattern.slice(0, -1));
487
+ }
488
+ return subject === pattern;
489
+ }
490
+
491
+ /**
492
+ * Gets leave for a call of one of the session's own tools, the way Claude Code decides: the
493
+ * mode (`acceptEdits` takes an edit inside the folder of the session), the deny and allow rules,
494
+ * the `PermissionRequest` hooks that match the tool, and when none of them settles it, the
495
+ * dialog a person answers with `__answer`, however long that takes. From the moment the call
496
+ * needs leave the session is listed as blocked on a permission prompt, also while a hook still
497
+ * decides, and when nothing has decided after `FAKE_CLAUDE_NOTIFY_MS` its `Notification` hooks
498
+ * are told (Claude Code takes about six seconds).
499
+ */
500
+ async function leaveFor(session, toolName, input) {
501
+ const { record, files } = session;
502
+ const mode = record.permissionMode ?? 'default';
503
+ const refused = (message) => ({ allowed: false, message });
504
+ const rules = (list) =>
505
+ settingsOf(record).flatMap((settings) => settings.permissions?.[list] ?? []);
506
+ const covered = (list) => rules(list).some((rule) => ruleCovers(rule, toolName, input));
507
+ if (covered('deny')) return refused(`Permission to use ${toolName} has been denied.`);
508
+ if (mode === 'bypassPermissions' || covered('allow')) return { allowed: true };
509
+ const edited = toolName === 'Edit' && typeof input.file_path === 'string' && input.file_path;
510
+ if (mode === 'acceptEdits' && edited && isWithin(edited, record.cwd)) {
511
+ return { allowed: true };
512
+ }
513
+
514
+ const payload = {
515
+ session_id: record.sessionId,
516
+ transcript_path: files.transcript,
517
+ cwd: record.cwd,
518
+ permission_mode: mode,
519
+ tool_name: toolName,
520
+ tool_input: input,
521
+ };
522
+ rmSync(files.answer, { force: true });
523
+ patchJson(files.record, {
524
+ status: 'waiting',
525
+ waitingFor: 'permission prompt',
526
+ ...(record.kind === 'background' && { state: 'blocked' }),
527
+ });
528
+ const notice = setTimeout(() => tellOfPrompt(session), noticeDelayMs());
529
+ const settled = (leave) => {
530
+ clearTimeout(notice);
531
+ patchJson(files.record, {
532
+ status: 'busy',
533
+ waitingFor: undefined,
534
+ dialog: undefined,
535
+ ...(record.kind === 'background' && { state: 'working' }),
536
+ });
537
+ return leave;
538
+ };
539
+
540
+ let allowedByHook = false;
541
+ for (const { matcher, hook } of eventHooks(record, 'PermissionRequest')) {
542
+ if (!new RegExp(`^(?:${matcher})$`).test(toolName)) continue;
543
+ const result = await runHook(
544
+ session,
545
+ hook,
546
+ JSON.stringify({ ...payload, hook_event_name: 'PermissionRequest' })
547
+ );
548
+ if (result.code !== 0) continue;
549
+ let decision;
550
+ try {
551
+ decision = JSON.parse(result.stdout).hookSpecificOutput?.decision;
552
+ } catch {
553
+ continue;
554
+ }
555
+ if (decision?.behavior === 'deny') {
556
+ return settled(
557
+ refused(String(decision.message ?? `Permission to use ${toolName} has been denied.`))
558
+ );
559
+ }
560
+ if (decision?.behavior === 'allow') allowedByHook = true;
561
+ }
562
+ if (allowedByHook) return settled({ allowed: true });
563
+ if (mode === 'dontAsk') {
564
+ return settled(refused(`Permission to use ${toolName} has been denied.`));
565
+ }
566
+
567
+ patchJson(files.record, { dialog: true });
568
+ let answer;
569
+ while ((answer = readJson(files.answer)) === undefined) await sleep(POLL_MS);
570
+ rmSync(files.answer, { force: true });
571
+ return settled(
572
+ answer.allow === true
573
+ ? { allowed: true }
574
+ : refused(`The user doesn't want to proceed with this tool use.`)
575
+ );
576
+ }
577
+
578
+ function noticeDelayMs() {
579
+ const value = Number(process.env.FAKE_CLAUDE_NOTIFY_MS);
580
+ return Number.isFinite(value) && value >= 0 ? value : DEFAULT_NOTICE_MS;
581
+ }
582
+
583
+ /** Tells the `Notification` hooks for permission prompts that the session waits for leave */
584
+ function tellOfPrompt(session) {
585
+ const { record, files } = session;
586
+ for (const { matcher, hook } of eventHooks(record, 'Notification')) {
587
+ if (matcher !== '.*' && !new RegExp(`^(?:${matcher})$`).test('permission_prompt')) continue;
588
+ void runHook(
589
+ session,
590
+ hook,
591
+ JSON.stringify({
592
+ session_id: record.sessionId,
593
+ transcript_path: files.transcript,
594
+ cwd: record.cwd,
595
+ hook_event_name: 'Notification',
596
+ message: 'Claude needs your permission',
597
+ title: 'Permission needed',
598
+ notification_type: 'permission_prompt',
599
+ })
600
+ );
601
+ }
602
+ }
603
+
604
+ /** The command hooks of an event, each with the matcher of its group */
605
+ function eventHooks(record, event) {
466
606
  return settingsOf(record).flatMap((settings) => {
467
- const groups = settings.hooks?.PreToolUse;
607
+ const groups = settings.hooks?.[event];
468
608
  if (!Array.isArray(groups)) return [];
469
609
  return groups.flatMap((group) =>
470
610
  (Array.isArray(group?.hooks) ? group.hooks : [])
471
611
  .filter((hook) => hook?.type === 'command' && typeof hook.command === 'string')
472
612
  .map((hook) => ({
473
- matcher: typeof group.matcher === 'string' ? group.matcher : '.*',
613
+ matcher: typeof group.matcher === 'string' && group.matcher !== '' ? group.matcher : '.*',
474
614
  hook,
475
615
  }))
476
616
  );
477
617
  });
478
618
  }
479
619
 
620
+ /** The command hooks of the PreToolUse event, each with the matcher of its group */
621
+ function toolHooks(record) {
622
+ return eventHooks(record, 'PreToolUse');
623
+ }
624
+
480
625
  /**
481
626
  * `mcp add`, `get` and `remove`. Local scope is kept under the folder of the command in the
482
627
  * configuration file, user scope at its top, project scope in the `.mcp.json` of the folder.
@@ -569,6 +714,8 @@ function endSession(recordFile) {
569
714
  patchJson(recordFile, {
570
715
  pid: undefined,
571
716
  status: undefined,
717
+ waitingFor: undefined,
718
+ dialog: undefined,
572
719
  hookPids: undefined,
573
720
  state: 'stopped',
574
721
  });
@@ -648,7 +795,15 @@ function wake(files, text) {
648
795
  function current(record) {
649
796
  if (record.state === 'failed') return record;
650
797
  if (record.pid !== undefined && isAlive(record.pid)) return record;
651
- return { ...record, pid: undefined, status: undefined, hookPids: undefined, state: 'stopped' };
798
+ return {
799
+ ...record,
800
+ pid: undefined,
801
+ status: undefined,
802
+ waitingFor: undefined,
803
+ dialog: undefined,
804
+ hookPids: undefined,
805
+ state: 'stopped',
806
+ };
652
807
  }
653
808
 
654
809
  function listSessions() {
@@ -682,8 +837,8 @@ async function agents(argv) {
682
837
  }
683
838
 
684
839
  /** 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 };
840
+ function listed({ id, sessionId, name, cwd, kind, startedAt, pid, status, state, waitingFor }) {
841
+ const shown = { id, sessionId, name, cwd, kind, startedAt, pid, status, waitingFor };
687
842
  return kind === 'background' ? { ...shown, state } : shown;
688
843
  }
689
844
 
@@ -702,6 +857,18 @@ async function remove(argv) {
702
857
  rmSync(files.record, { force: true });
703
858
  rmSync(files.transcript, { force: true });
704
859
  rmSync(files.spool, { recursive: true, force: true });
860
+ rmSync(files.answer, { force: true });
861
+ }
862
+
863
+ /** `__answer <session> allow|deny`: a person answers the permission dialog a session shows */
864
+ async function answerPrompt(argv) {
865
+ const [ref, word] = argv;
866
+ if (argv.length !== 2 || (word !== 'allow' && word !== 'deny')) throw new Unsupported();
867
+ const session = findSession([ref]);
868
+ if (session.dialog !== true) {
869
+ throw new CliError(`Session '${ref}' shows no permission dialog`);
870
+ }
871
+ writeJson(sessionFiles(session.sessionId).answer, { allow: word === 'allow' });
705
872
  }
706
873
 
707
874
  async function say(argv) {
package/fakes/lib.mjs CHANGED
@@ -467,7 +467,13 @@ export function abandonWork() {
467
467
  for (const file of [...heldLocks]) unlock(file);
468
468
  }
469
469
 
470
- /** @typedef {{ command: string, code: number | null, stdout: string, stderr: string }} CommandRun */
470
+ /**
471
+ * A command of a turn. `denied` marks one that never ran because leave for it was refused, with
472
+ * the refusal in `stderr`
473
+ * @typedef {{ command: string, code: number | null, stdout: string, stderr: string, denied?: boolean }} CommandRun
474
+ */
475
+
476
+ /** @typedef {(call: { tool: string, input: Record<string, unknown> }) => Promise<{ allowed: boolean, message?: string }>} LeaveAsker */
471
477
 
472
478
  /**
473
479
  * A tool call of a turn: `args` as the model wrote them, `sent` as they reached the server when
@@ -482,11 +488,11 @@ export function abandonWork() {
482
488
  /**
483
489
  * The directives of an input, in the order of its lines. A line counts after its leading
484
490
  * whitespace is trimmed, a quoted line (`> run: ...`) is not a directive.
485
- * @returns {{ kind: 'run' | 'sleep' | 'say' | 'tool', value: string }[]}
491
+ * @returns {{ kind: 'run' | 'bash' | 'edit' | 'sleep' | 'say' | 'tool', value: string }[]}
486
492
  */
487
493
  function directives(input) {
488
494
  return input.split(/\r?\n/).flatMap((line) => {
489
- const match = /^(run|sleep|say|tool): (.+)$/.exec(line.trimStart());
495
+ const match = /^(run|bash|edit|sleep|say|tool): (.+)$/.exec(line.trimStart());
490
496
  if (!match) return [];
491
497
  const [, kind, text] = match;
492
498
  const value = text.trim();
@@ -527,23 +533,68 @@ async function runTool(value, callTool) {
527
533
  }
528
534
 
529
535
  /**
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`.
536
+ * A `bash:` directive: a command the session's own shell tool runs, which the session needs
537
+ * leave for the way its harness decides. A refused one does not run.
538
+ * @param {string} command
539
+ * @param {LeaveAsker | undefined} askLeave
540
+ * @returns {Promise<CommandRun>}
541
+ */
542
+ async function runWithLeave(command, cwd, env, askLeave) {
543
+ const leave = askLeave ? await askLeave({ tool: 'Bash', input: { command } }) : { allowed: true };
544
+ if (leave.allowed) return runCommand(command, cwd, env);
545
+ return { command, code: null, stdout: '', stderr: leave.message ?? 'denied', denied: true };
546
+ }
547
+
548
+ /**
549
+ * An `edit:` directive: a file the session's own edit tool changes, by adding a line to it,
550
+ * which the session needs leave for the way its harness decides. It is in the turn as a command
551
+ * `edit <path>`, refused or done. A harness that imitates no edit tool of its own fails it.
552
+ * @param {string} path as the model wrote it, relative to the folder of the session or absolute
553
+ * @param {LeaveAsker | undefined} askLeave
554
+ * @returns {Promise<CommandRun>}
555
+ */
556
+ async function editWithLeave(path, cwd, askLeave) {
557
+ const file = resolve(cwd, path);
558
+ const command = `edit ${path}`;
559
+ if (!askLeave) {
560
+ return { command, code: 1, stdout: '', stderr: 'this stand-in has no edit tool of its own' };
561
+ }
562
+ const leave = await askLeave({ tool: 'Edit', input: { file_path: file } });
563
+ if (!leave.allowed) {
564
+ return { command, code: null, stdout: '', stderr: leave.message ?? 'denied', denied: true };
565
+ }
566
+ try {
567
+ mkdirSync(dirname(file), { recursive: true });
568
+ appendFileSync(file, 'edited\n');
569
+ return { command, code: 0, stdout: '', stderr: '' };
570
+ } catch (error) {
571
+ return { command, code: 1, stdout: '', stderr: error.message };
572
+ }
573
+ }
574
+
575
+ /**
576
+ * The scripted model: runs every `run: <command>` line with `sh -c`, asks leave for and then
577
+ * runs every `bash: <command>` line, asks leave for and then changes the file of every
578
+ * `edit: <path>` line, calls the tool of every `tool: <server>.<tool> {json}` line and waits
579
+ * out every `sleep: <ms>` line, one after another, and answers with the last `say: <text>`
580
+ * line, or `ok`.
533
581
  * @param {object} turn
534
582
  * @param {string} turn.input
535
583
  * @param {string} turn.cwd where the commands run
536
584
  * @param {NodeJS.ProcessEnv} turn.env what the commands see
537
585
  * @param {ToolCaller} [turn.callTool] how the session calls a tool of one of its MCP servers
586
+ * @param {LeaveAsker} [turn.askLeave] how the session gets leave for a call of its own tools
538
587
  * @returns {Promise<TurnOutcome>}
539
588
  */
540
- export async function performTurn({ input, cwd, env, callTool }) {
589
+ export async function performTurn({ input, cwd, env, callTool, askLeave }) {
541
590
  const at = new Date().toISOString();
542
591
  const ran = [];
543
592
  const tools = [];
544
593
  let answer = 'ok';
545
594
  for (const { kind, value } of directives(input)) {
546
595
  if (kind === 'run') ran.push(await runCommand(value, cwd, env));
596
+ else if (kind === 'bash') ran.push(await runWithLeave(value, cwd, env, askLeave));
597
+ else if (kind === 'edit') ran.push(await editWithLeave(value, cwd, askLeave));
547
598
  else if (kind === 'tool') tools.push(await runTool(value, callTool));
548
599
  else if (kind === 'sleep') await sleep(Number(value));
549
600
  else answer = value;
package/fakes/mcp.mjs CHANGED
@@ -5,7 +5,12 @@
5
5
  import { spawn } from 'node:child_process';
6
6
  import { createInterface } from 'node:readline';
7
7
 
8
- const REQUEST_TIMEOUT_MS = 15_000;
8
+ /**
9
+ * A server of tools is a process that starts for the request: on a busy CI runner its first
10
+ * answer took over fifteen seconds while it still loaded the whole runtime, so a request waits
11
+ * a minute
12
+ */
13
+ const REQUEST_TIMEOUT_MS = 60_000;
9
14
  const PROTOCOL_VERSION = '2025-06-18';
10
15
 
11
16
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cogitator-ai/bridge",
3
- "version": "0.5.0",
3
+ "version": "0.6.1",
4
4
  "description": "Agent bridge for Cogitator: Claude Code, Codex and other agents hand each other jobs, ask questions and report back, each in its own window (experimental)",
5
5
  "keywords": [
6
6
  "cogitator",
@@ -52,8 +52,8 @@
52
52
  "zod": "^4.6.6"
53
53
  },
54
54
  "devDependencies": {
55
- "@cogitator-ai/core": "0.78.1",
56
- "@cogitator-ai/mcp": "19.11.0",
55
+ "@cogitator-ai/core": "0.79.0",
56
+ "@cogitator-ai/mcp": "19.12.0",
57
57
  "@types/better-sqlite3": "^9.6.0",
58
58
  "@types/node": "^22.20.4",
59
59
  "better-sqlite3": "^13.0.3",
@@ -61,7 +61,7 @@
61
61
  "vitest": "^5.0.3"
62
62
  },
63
63
  "peerDependencies": {
64
- "@cogitator-ai/core": ">=0.78.1",
64
+ "@cogitator-ai/core": ">=0.79.0",
65
65
  "better-sqlite3": "^11.0.0 || ^12.0.0 || ^13.0.0"
66
66
  },
67
67
  "peerDependenciesMeta": {