@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/README.md CHANGED
@@ -6,7 +6,9 @@ The agent bridge: Claude Code, Codex and other agents hand each other jobs, ask
6
6
 
7
7
  Nobody waits. An agent hands a job over, gets its number at once and ends its turn. Whatever comes later, a question or the result, arrives as a letter. The bridge in the middle is a dispatcher, not a model: it keeps jobs and letters, finds who a letter is for, applies the limits and writes everything down. It never calls a model.
8
8
 
9
- The bridge reaches a session where it lives. A Claude Code session wakes for its mail through a hook of its own, a Codex thread through its message queue, and an agent the bridge hosts itself (any model of the Cogitator runtime, any agent of the Agent Client Protocol) gets a letter as its next turn. A harness without an adapter still takes part: its sessions read their inbox. The MCP tools agents call are the next step, until then a session calls the bridge with `cogitator bridge` from its shell.
9
+ The bridge reaches a session where it lives. A Claude Code session wakes for its mail through a hook of its own, a Codex thread through its message queue, and an agent the bridge hosts itself (any model of the Cogitator runtime, any agent of the Agent Client Protocol) gets a letter as its next turn. A harness without an adapter still takes part: its sessions read their inbox.
10
+
11
+ Agents call the bridge with tools of their own, served over MCP: `delegate`, `ask`, `answer`, `report` and the rest. A server of tools lives outside the sandbox of its session, so a Codex thread in a sandbox takes part like any other. `cogitator bridge install` sets Claude Code and Codex up for a project, and shows every change before it makes it.
10
12
 
11
13
  ```bash
12
14
  pnpm add @cogitator-ai/bridge better-sqlite3
@@ -26,18 +28,56 @@ cogitator bridge doctor # whether Claude Code and Codex can be reached,
26
28
 
27
29
  `cogitator daemon start --bridge` hosts it inside the assistant daemon instead. Its files live in `~/.cogitator/bridge` (`COGITATOR_BRIDGE_HOME` moves them): `bridge.db` and `bridge.sock`, both kept to their owner.
28
30
 
31
+ ## Set a project up
32
+
33
+ ```bash
34
+ cogitator bridge install # Claude Code and Codex, for you in this project
35
+ cogitator bridge install claude # one harness
36
+ cogitator bridge install --dry-run # list the changes, make none
37
+ cogitator bridge uninstall # take out what install put in, and nothing else
38
+ ```
39
+
40
+ `install` lists every change first and makes them after a yes (`--yes` skips the question):
41
+
42
+ | | Claude Code | Codex |
43
+ | ------------------- | ------------------------------------------------------------ | ---------------------------------- |
44
+ | The server of tools | `claude mcp add --scope local bridge` | `codex mcp add bridge` |
45
+ | Hooks | the project's `.claude/settings.local.json` | none needed |
46
+ | Tools run unasked | the rule `mcp__bridge` in the same file, unless `--no-allow` | Codex asks nothing for these tools |
47
+ | Notes for sessions | `CLAUDE.md` of the project, unless `--no-notes` | `AGENTS.md`, unless `--no-notes` |
48
+
49
+ What names a path of this machine goes where only you have it, never into a file the project shares. A linked git worktree is a checkout of its own: run `install` in each one whose sessions need the bridge. The notes say how the tools go together and that a letter of the bridge is not typed by you. By default they tell a session you opened to ask you before it carries out a job of another agent: `--take-jobs` lets it go ahead. `--user` sets every project of yours up instead of one. Codex keeps its servers for every project whichever way it is asked, so a per-project `uninstall` leaves its server and `uninstall codex --user` removes it. Settings that are not a JSON object are refused, never overwritten, and running `install` again changes only what is out of date. Sessions that are open get the tools when they are started again.
50
+
51
+ ### The tools
52
+
53
+ | Tool | What it does |
54
+ | ---------- | ------------------------------------------------------------------------------------------------ |
55
+ | `delegate` | Hands a job to `codex`, `claude` or an agent by name, and returns its number at once |
56
+ | `ask` | Asks the other agent of a job a question. The answer wakes the session |
57
+ | `answer` | Answers a question another agent asked |
58
+ | `report` | Reports the result of a job handed to this session, which ends the job. `failed` says it did not |
59
+ | `note` | Tells the other agent something it need not answer |
60
+ | `inbox` | Reads the letters that wait, when nothing woke the session |
61
+ | `job` | Shows one job: its state, and for a job of this session its latest letters |
62
+ | `jobs` | Lists the jobs this session handed over or carries out |
63
+ | `cancel` | Takes back a job this session handed over |
64
+ | `agents` | Lists the sessions the bridge knows in the project, and the agents it can start a session of |
65
+
66
+ No tool waits for another agent. The server tells every client the same in its `instructions`: after `delegate` say in one line what was handed over and end the turn, reply to a letter with the tools and never only in the chat, and treat a job of another agent as that agent's request, not the user's.
67
+
29
68
  ## Claude Code and Codex
30
69
 
31
- The dispatcher of `cogitator bridge serve` reaches both harnesses with the commands they document, and changes nothing in their settings.
70
+ The dispatcher of `cogitator bridge serve` reaches both harnesses with the commands they document. It changes nothing in their settings: `cogitator bridge install` does, for the sessions you open yourself, and a session the bridge starts carries what it needs.
32
71
 
33
72
  | | Claude Code | Codex |
34
73
  | ----------------------- | --------------------------------------------------------- | ------------------------------------------------------------- |
35
74
  | A letter reaches it by | a `Stop` hook of the session that waits at the bridge | `codex queue --resume` |
36
75
  | A session for a job is | `claude --bg`, a background session `claude attach` opens | `codex exec`, a thread `codex resume` opens |
37
76
  | It wakes by itself when | the session carries the hook | the thread is open in the Codex app, or the local daemon runs |
77
+ | The tools know it by | a hook that adds the session to every tool call | the thread Codex names in every tool call |
38
78
  | Before it can start | Claude Code must trust the folder | nothing |
39
79
 
40
- **Claude Code.** Nothing is pushed into a window from outside. After every turn a background hook of the session runs `cogitator bridge wait`, which waits at the dispatcher and, when a letter comes, exits with code 2 and the letter on stderr: that wakes the session with the letter as its next input (`asyncRewake` in Claude Code's hooks). Under the letter it adds one line saying how to answer through the bridge. While the hook waits the session is free, you can talk to it. A session the bridge starts carries the hook itself. For the sessions you open yourself, put it into the project's `.claude/settings.local.json`, `cogitator bridge doctor` prints the exact lines:
80
+ **Claude Code.** Nothing is pushed into a window from outside. After every turn a background hook of the session runs `cogitator bridge wait`, which waits at the dispatcher and, when a letter comes, exits with code 2 and the letter on stderr: that wakes the session with the letter as its next input (`asyncRewake` in Claude Code's hooks). Under the letter it adds one line saying how to answer through the bridge. While the hook waits the session is free, you can talk to it. A session the bridge starts carries the hook itself. For the sessions you open yourself, `cogitator bridge install` puts it into the project's `.claude/settings.local.json`:
41
81
 
42
82
  ```json
43
83
  {
@@ -47,7 +87,7 @@ The dispatcher of `cogitator bridge serve` reaches both harnesses with the comma
47
87
  "hooks": [
48
88
  {
49
89
  "type": "command",
50
- "command": "cogitator bridge wait --hook claude-code --timeout 43140",
90
+ "command": "cogitator bridge wait --hook claude-code --timeout 43140 --tools",
51
91
  "timeout": 43200,
52
92
  "async": true,
53
93
  "asyncRewake": true
@@ -59,11 +99,15 @@ The dispatcher of `cogitator bridge serve` reaches both harnesses with the comma
59
99
  }
60
100
  ```
61
101
 
62
- A dispatcher that keeps its files somewhere else (`--home`, `COGITATOR_BRIDGE_HOME`) puts that folder into the hook, so its sessions call it and not the default one. A session without the hook still gets its letters, when it asks: `cogitator bridge inbox`. The hook waits 12 hours at most, then the session reads its mail at its next turn. A session a person opened decides for itself what to do with a job another agent hands it: every letter says it was not typed by the user, and such a session may ask its person before it acts. A session the bridge started for a job takes the job as its task. Claude Code starts a background session only in a folder it trusts: the bridge checks that first and fails the job with what to do (open the folder in Claude Code once and accept its prompt).
102
+ A dispatcher that keeps its files somewhere else (`--home`, `COGITATOR_BRIDGE_HOME`) puts that folder into the hook and into the command of the server of tools, so its sessions call it and not the default one. A session without the hook still gets its letters, when it asks: the `inbox` tool, or `cogitator bridge inbox`.
63
103
 
64
- **Codex.** A letter goes into the message queue of the thread. A thread open in the Codex app takes it within seconds. A thread that is open nowhere, such as one the bridge started, wakes only when Codex's local daemon runs (`codex app-server daemon start`). The bridge never starts that daemon for you: without it the letter stays in the queue until the thread is opened. Codex does not tell the two cases apart, so the journal notes every letter queued while no daemon runs. A thread the bridge starts runs in the `workspace-write` sandbox, and what it prints goes to a file of its own in `~/.cogitator/bridge/sessions`, which the bridge never removes. From that sandbox the thread cannot reach the bridge with shell commands, so the bridge takes the final answer of its first turn as the report, and a turn that fails as a failed job. A thread that has to ask questions on the way needs a wider sandbox until the MCP tools arrive: `cogitator bridge serve --codex-sandbox danger-full-access`, or the `sandbox` option of `codexAdapter`. That sandbox holds nothing back, so name it only on a machine where you would let the thread do anything.
104
+ Claude Code starts a server of tools once and keeps it across `/clear`, so the session a server was started for is not always the one that calls. A second hook, on the bridge's tools only (`PreToolUse`, `cogitator bridge caller`), adds the session to the arguments of every call, and the tools go by that. Without it they go by the session the server was started for, which `cogitator bridge doctor` warns about. The hook waits 12 hours at most, then the session reads its mail at its next turn. A session a person opened decides for itself what to do with a job another agent hands it: every letter says it was not typed by the user, and such a session may ask its person before it acts. A session the bridge started for a job takes the job as its task. Claude Code starts a background session only in a folder it trusts: the bridge checks that first and fails the job with what to do (open the folder in Claude Code once and accept its prompt).
65
105
 
66
- **From inside a session.** Until the bridge has tools of its own, an agent calls it from its shell. The session is known by what its harness put into the environment.
106
+ **Codex.** A letter goes into the message queue of the thread. A thread open in the Codex app takes it within seconds. A thread that is open nowhere, such as one the bridge started, wakes only when Codex's local daemon runs (`codex app-server daemon start`). The bridge never starts that daemon for you: without it the letter stays in the queue until the thread is opened. Codex does not tell the two cases apart, so the journal notes every letter queued while no daemon runs. A thread the bridge starts runs in the `workspace-write` sandbox, and what it prints goes to a file of its own in `~/.cogitator/bridge/sessions`, which the bridge never removes.
107
+
108
+ The sandbox keeps the shell commands of a thread from the bridge's socket (`connect EPERM`), and Codex gives a server of tools none of the thread's environment. The tools need neither: Codex runs their server outside the sandbox and names the thread in every call, so a thread asks, answers and reports from any sandbox. The tools say they destroy nothing and stay on this machine, which is why Codex runs them without an approval, in `codex exec` too. A thread the bridge starts gets the tools whatever Codex has set up, and when its turn ends without a report the bridge takes its final answer as one, and a turn that fails as a failed job. `cogitator bridge serve --codex-sandbox <mode>` and the `sandbox` option of `codexAdapter` choose what the thread itself may do: `danger-full-access` holds nothing back, so name it only on a machine where you would let the thread do anything.
109
+
110
+ **From a shell.** A session without the tools, and you at a terminal inside one, call the bridge with its command line. The session is known by what its harness put into the environment. A sandbox that keeps commands from sockets keeps this from the bridge too: that is what the tools are for.
67
111
 
68
112
  ```bash
69
113
  cogitator bridge delegate codex "Write the tests for the rate limiter" --check "pnpm test"
@@ -249,6 +293,47 @@ A session of a provider stays in the folder it was opened for: a later job for a
249
293
 
250
294
  `open` returns a session: anything with a `turn(text, { job })` whose `result` resolves with the agent's answer, so a session of your own is a few lines. Hosted sessions live in the host's process and end with it.
251
295
 
296
+ ## The tools in your own process
297
+
298
+ `cogitator bridge mcp` is a few lines over `@cogitator-ai/bridge/tools`, which needs `@cogitator-ai/core`:
299
+
300
+ ```typescript
301
+ import { MCPServer } from '@cogitator-ai/mcp';
302
+ import { bridgePaths } from '@cogitator-ai/bridge';
303
+ import { BRIDGE_INSTRUCTIONS, bridgeTools } from '@cogitator-ai/bridge/tools';
304
+
305
+ const server = new MCPServer({
306
+ name: 'cogitator-bridge',
307
+ version: '1.0.0',
308
+ transport: 'stdio',
309
+ instructions: BRIDGE_INSTRUCTIONS,
310
+ });
311
+ server.registerTools(bridgeTools({ socketPath: bridgePaths().socket }));
312
+ await server.start();
313
+ ```
314
+
315
+ Every call reaches the dispatcher on a connection of its own, so the server may start before the dispatcher and lives through its restarts. Who calls is read from each call, not once (`callerOfToolCall`): the hint a hook of the harness added to the arguments, else the thread Codex names in `_meta`, else the environment of the server.
316
+
317
+ `claudeSetup()` and `codexSetup()` are what `cogitator bridge install` runs. `install()` and `uninstall()` return steps, each with a title, the command it runs or the lines a file gains, and an `apply()`: nothing changes until a step is applied, and a harness that is set up has no steps.
318
+
319
+ ```typescript
320
+ import { claudeSetup } from '@cogitator-ai/bridge';
321
+
322
+ const setup = claudeSetup({
323
+ toolsServer: { command: 'cogitator', args: ['bridge', 'mcp'] },
324
+ });
325
+ const steps = await setup.install({
326
+ project: process.cwd(),
327
+ scope: 'project',
328
+ notes: true,
329
+ takeJobs: false,
330
+ allowTools: true,
331
+ });
332
+ for (const step of steps) console.log(step.title, step.lines);
333
+ ```
334
+
335
+ Pass `toolsServer` to `claudeCodeAdapter()` and `codexAdapter()` too, and the sessions they start get the tools: Claude Code with `--mcp-config`, the hook that names the session and the rule for the tools, Codex as overrides of its configuration.
336
+
252
337
  ## Adapters
253
338
 
254
339
  An adapter tells the bridge how to reach the sessions of one harness. `claudeCodeAdapter()`, `codexAdapter()` and `hostedAdapter()` are the ones above. `cogitator bridge serve` runs the first two as they come. To choose the permission mode of Claude Code sessions or the sandbox of Codex threads, or to add hosted agents, host the dispatcher in a process of your own:
@@ -293,6 +378,7 @@ const host = await hostBridge({ adapters: [adapter] });
293
378
  | `deliver` | Hands a letter to a session. Leave it out when the sessions wait for their mail themselves, as Claude Code's do |
294
379
  | `createSession` | Starts a session for a job, and may hand it the first letter while it does |
295
380
  | `identify` | Tells which session a process belongs to, from its environment or from what the harness wrote to its hook |
381
+ | `toolCallHook` | Answers the hook a harness runs before a bridge tool call, so the call carries the session that makes it |
296
382
  | `liveSessions` | Lists the sessions that run, so the bridge knows a closed one from a quiet one |
297
383
  | `health` | What `cogitator bridge doctor` shows: versions, the commands the bridge needs, each with what to do about it |
298
384
  | `attach` | Gets the calls the adapter's own sessions make, such as to report |
@@ -300,7 +386,7 @@ const host = await hostBridge({ adapters: [adapter] });
300
386
 
301
387
  `deliver` may return `{ note }`: something a person should know about the delivery, kept in the journal.
302
388
 
303
- `@cogitator-ai/bridge/testing` has what the adapters of this package are tested with. `adapterConformanceCases(target)` is the adapter contract as cases to run against your adapter and its harness. `installFakeHarnesses()` puts stand-ins of the `claude` and `codex` commands on a `PATH`: they keep background sessions, fire hooks, hold queues and run a scripted turn, so code that drives the real command lines is tested without them.
389
+ `@cogitator-ai/bridge/testing` has what the adapters of this package are tested with. `adapterConformanceCases(target)` is the adapter contract as cases to run against your adapter and its harness. `installFakeHarnesses()` puts stand-ins of the `claude` and `codex` commands on a `PATH`: they keep background sessions, fire hooks, hold queues and run a scripted turn, so code that drives the real command lines is tested without them. They run MCP servers the way the real ones were measured to (`claude mcp`, `codex mcp`, the environment a server gets, what a tool call carries, the tools a session nobody sits at may call), and keep the commands of a sandboxed Codex thread from sockets and from writing outside its folder, so a test shows what works from a sandbox.
304
390
 
305
391
  ```typescript
306
392
  import { adapterConformanceCases } from '@cogitator-ai/bridge/testing';
@@ -312,7 +398,7 @@ for (const conformance of adapterConformanceCases(target)) {
312
398
 
313
399
  ## Trust
314
400
 
315
- The bridge is a tool of one person on one machine. The socket and the database are created for their owner only, a folder or a database that belongs to another user is refused, and every process of that user can connect: read any job and letter, and call as a session by naming its id. A job is done inside the project it is handed over in, or the worktree its caller works in. A session the bridge starts has the rights its harness gives it: a Claude Code session the permission mode you configure (`claudeCodeAdapter({ permissionMode })`), a Codex thread the `workspace-write` sandbox unless you choose another (`codexAdapter({ sandbox })`). A letter is text from another agent, never an order from you: every letter says so in its first line. Do not point `COGITATOR_BRIDGE_HOME` at a folder other users can write to. On Windows the dispatcher listens on a named pipe that other users of the same machine can reach, so run it only on a machine you do not share. The Claude Code and Codex adapters run on macOS and Linux.
401
+ The bridge is a tool of one person on one machine. The socket and the database are created for their owner only, a folder or a database that belongs to another user is refused, and every process of that user can connect: read any job and letter, and call as a session by naming its id. A job is done inside the project it is handed over in, or the worktree its caller works in. A session the bridge starts has the rights its harness gives it: a Claude Code session the permission mode you configure (`claudeCodeAdapter({ permissionMode })`), a Codex thread the `workspace-write` sandbox unless you choose another (`codexAdapter({ sandbox })`). A letter is text from another agent, never an order from you: every letter says so in its first line, and whether a session you opened takes a job without asking you is yours to say at `cogitator bridge install` (`--take-jobs`). A tool call names its session the way a connection to the socket does, and is believed the same way. Do not point `COGITATOR_BRIDGE_HOME` at a folder other users can write to. On Windows the dispatcher listens on a named pipe that other users of the same machine can reach, so run it only on a machine you do not share. The Claude Code and Codex adapters run on macOS and Linux.
316
402
 
317
403
  ## Errors
318
404
 
package/dist/adapter.d.ts CHANGED
@@ -107,6 +107,13 @@ export interface BridgeAdapter {
107
107
  * the variables of the harnesses the bridge knows
108
108
  */
109
109
  identify?(context: IdentifyContext): CallerIdentity | undefined;
110
+ /**
111
+ * What a hook of the harness answers before a call of a bridge tool, so the call carries the
112
+ * session that makes it: the harness then hands the tool the arguments with the hint in them
113
+ * (`TOOL_CALL_HINT_KEY`). Undefined when the hook's input names no session, and the call goes
114
+ * on as it was. For a harness whose server of tools outlives its sessions
115
+ */
116
+ toolCallHook?(context: IdentifyContext): string | undefined;
110
117
  /**
111
118
  * The sessions of the harness running on this machine, when the harness can list them. The
112
119
  * bridge keeps a listed session in its address book however long it is silent, and takes one
@@ -1 +1 @@
1
- {"version":3,"file":"adapter.d.ts","sourceRoot":"","sources":["../src/adapter.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,cAAc,EACd,eAAe,EACf,UAAU,EACV,eAAe,EACf,gBAAgB,EACjB,MAAM,aAAa,CAAC;AACrB,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AACrD,OAAO,KAAK,EAC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O,CAAC,eAAe,GAAG,IAAI,CAAC,CAAC;IACpE,oFAAoF;IACpF,aAAa,CAAC,CAAC,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,cAAc,CAAC,CAAC;IACjE;;;;OAIG;IACH,QAAQ,CAAC,CAAC,OAAO,EAAE,eAAe,GAAG,cAAc,GAAG,SAAS,CAAC;IAChE;;;;;OAKG;IACH,YAAY,CAAC,CAAC,OAAO,EAAE,eAAe,GAAG,MAAM,GAAG,SAAS,CAAC;IAC5D;;;;OAIG;IACH,YAAY,CAAC,IAAI,OAAO,CAAC,WAAW,EAAE,CAAC,CAAC;IACxC,oGAAoG;IACpG,MAAM,CAAC,CAAC,OAAO,EAAE,aAAa,GAAG,OAAO,CAAC,WAAW,EAAE,CAAC,CAAC;IACxD,gGAAgG;IAChG,MAAM,CAAC,CAAC,MAAM,EAAE,WAAW,GAAG,IAAI,CAAC;IACnC,oEAAoE;IACpE,KAAK,CAAC,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CACzB"}
@@ -1,4 +1,5 @@
1
1
  import type { BridgeAdapter } from '../adapter.js';
2
+ import { type ToolsServerCommand } from './tools-server.js';
2
3
  /** How letters reach a Claude Code session: a hook of the session waits for them. */
3
4
  export declare const CLAUDE_DELIVERY = "hook";
4
5
  /** How long a waiter of a Claude Code session waits before Claude Code ends it, 12 hours. */
@@ -12,6 +13,8 @@ export interface ClaudeWaitHookOptions {
12
13
  agentName?: string;
13
14
  /** The folder of the bridge's files, when it is not the default one */
14
15
  bridgeHome?: string;
16
+ /** Whether the session has the bridge's tools: the waiter then says to answer with them */
17
+ tools?: boolean;
15
18
  }
16
19
  export interface ClaudeHookSettings {
17
20
  hooks: {
@@ -38,6 +41,52 @@ export declare function claudeWaitCommand(options?: ClaudeWaitHookOptions): stri
38
41
  export declare function claudeWaitHook(options?: ClaudeWaitHookOptions): ClaudeHookSettings;
39
42
  /** Whether Claude Code settings hold a hook that waits at the bridge. */
40
43
  export declare function hasClaudeWaitHook(settings: unknown): boolean;
44
+ /** How a Claude Code session names the tools of the bridge's server, and what rules match them by. */
45
+ export declare const CLAUDE_TOOLS_PREFIX = "mcp__bridge";
46
+ /** The permission rule that lets a session call the bridge's tools without a prompt. */
47
+ export declare const CLAUDE_TOOLS_PERMISSION = "mcp__bridge";
48
+ export interface ClaudeToolsHookOptions {
49
+ /** How the bridge's command line is run, `cogitator bridge` by default */
50
+ bridgeCommand?: string;
51
+ }
52
+ export interface ClaudeToolsHookSettings {
53
+ hooks: {
54
+ PreToolUse: {
55
+ matcher: string;
56
+ hooks: {
57
+ type: 'command';
58
+ command: string;
59
+ timeout: number;
60
+ }[];
61
+ }[];
62
+ };
63
+ }
64
+ /** The command a hook of a Claude Code session runs before a call of a bridge tool. */
65
+ export declare function claudeCallerCommand(options?: ClaudeToolsHookOptions): string;
66
+ /**
67
+ * The settings that tell the bridge's tools which Claude Code session calls them: a `PreToolUse`
68
+ * hook on the tools of the bridge's server that adds the session to the arguments of the call.
69
+ * Claude Code starts the server once and keeps it across `/clear`, so the session the server was
70
+ * started for is not always the one that calls. Without the hook the tools go by that first
71
+ * session.
72
+ */
73
+ export declare function claudeToolsHook(options?: ClaudeToolsHookOptions): ClaudeToolsHookSettings;
74
+ /** Whether Claude Code settings hold the hook that names the session of a bridge tool call. */
75
+ export declare function hasClaudeToolsHook(settings: unknown): boolean;
76
+ /**
77
+ * What the hook of `claudeToolsHook` answers Claude Code with: the arguments of the call with
78
+ * the session that makes it added (`hookSpecificOutput.updatedInput`). Undefined when the input
79
+ * is not that of a `PreToolUse` hook, and the call goes on as the model wrote it.
80
+ *
81
+ * @param hookInput what Claude Code wrote to the hook's stdin
82
+ */
83
+ export declare function claudeToolCallHook(hookInput: string): string | undefined;
84
+ /**
85
+ * Where Claude Code has the bridge's server of tools for the sessions of a folder: `local`
86
+ * (this person, this project), `project` (the project's `.mcp.json`) or `user` (this person,
87
+ * every project). Undefined when it has it nowhere.
88
+ */
89
+ export declare function claudeToolsScope(folder: string, configPath?: string): 'local' | 'project' | 'user' | undefined;
41
90
  export type ClaudeTrust = 'trusted' | 'untrusted' | 'unknown';
42
91
  /**
43
92
  * Whether Claude Code trusts a folder, read from where it records that a person accepted its
@@ -76,6 +125,12 @@ export interface ClaudeCodeAdapterOptions {
76
125
  userSettingsPath?: string;
77
126
  /** How long a started session may take to show up among the running ones, 30 s by default */
78
127
  sessionListedMs?: number;
128
+ /**
129
+ * How a session starts the bridge's server of tools. With it the sessions the adapter starts
130
+ * get the tools, the hook that tells the tools which session calls, and the permission to call
131
+ * them. Without it they use the bridge's command line
132
+ */
133
+ toolsServer?: ToolsServerCommand;
79
134
  }
80
135
  /**
81
136
  * Reaches Claude Code sessions in their own windows. A session started for a job runs in the
@@ -1 +1 @@
1
- {"version":3,"file":"claude.d.ts","sourceRoot":"","sources":["../../src/adapters/claude.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EACV,aAAa,EAOd,MAAM,eAAe,CAAC;AAcvB,qFAAqF;AACrF,eAAO,MAAM,eAAe,SAAS,CAAC;AAEtC,6FAA6F;AAC7F,eAAO,MAAM,sBAAsB,QAAY,CAAC;AAKhD,MAAM,WAAW,qBAAqB;IACpC,0EAA0E;IAC1E,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,oDAAoD;IACpD,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,sEAAsE;IACtE,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,uEAAuE;IACvE,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;AAED,MAAM,WAAW,kBAAkB;IACjC,KAAK,EAAE;QACL,IAAI,EAAE;YACJ,KAAK,EAAE;gBACL,IAAI,EAAE,SAAS,CAAC;gBAChB,OAAO,EAAE,MAAM,CAAC;gBAChB,OAAO,EAAE,MAAM,CAAC;gBAChB,KAAK,EAAE,IAAI,CAAC;gBACZ,WAAW,EAAE,IAAI,CAAC;aACnB,EAAE,CAAC;SACL,EAAE,CAAC;KACL,CAAC;CACH;AAED,uFAAuF;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;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB;;;OAGG;IACH,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,6FAA6F;IAC7F,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB;;;;OAIG;IACH,WAAW,CAAC,EAAE,kBAAkB,CAAC;CAClC;AAyBD;;;;;;;;GAQG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,GAAE,wBAA6B,GAAG,aAAa,CAsSvF"}
@@ -2,9 +2,11 @@ import { readFileSync } from 'node:fs';
2
2
  import { homedir } from 'node:os';
3
3
  import { dirname, join, resolve } from 'node:path';
4
4
  import { z } from 'zod';
5
- import { findProjectRoot } from '../paths.js';
5
+ import { canonicalPath, findProjectRoot } from '../paths.js';
6
+ import { TOOL_CALL_HINT_KEY } from '../tools/caller.js';
6
7
  import { HARNESSES } from '../types.js';
7
8
  import { CommandMissingError, failureOf, fitsArgument, pause, runCommand, sessionEnv, shellQuote, tooLongNotice, } from './exec.js';
9
+ import { BRIDGE_TOOLS_SERVER, toolsServerEnv } from './tools-server.js';
8
10
  /** How letters reach a Claude Code session: a hook of the session waits for them. */
9
11
  export const CLAUDE_DELIVERY = 'hook';
10
12
  /** How long a waiter of a Claude Code session waits before Claude Code ends it, 12 hours. */
@@ -22,6 +24,7 @@ export function claudeWaitCommand(options = {}) {
22
24
  `--timeout ${waitS}`,
23
25
  ...(options.agentName ? [`--agent ${shellQuote(options.agentName)}`] : []),
24
26
  ...(options.bridgeHome ? [`--home ${shellQuote(options.bridgeHome)}`] : []),
27
+ ...(options.tools ? ['--tools'] : []),
25
28
  ].join(' ');
26
29
  }
27
30
  /**
@@ -57,19 +60,94 @@ export function hasClaudeWaitHook(settings) {
57
60
  return false;
58
61
  return (parsed.data.hooks?.Stop ?? []).some((group) => (group.hooks ?? []).some((hook) => hook.asyncRewake === true && /\bbridge\s+wait\b/.test(hook.command ?? '')));
59
62
  }
60
- const SettingsSchema = z.object({
63
+ const HookGroupsSchema = z
64
+ .array(z.object({
61
65
  hooks: z
62
- .object({
63
- Stop: z
64
- .array(z.object({
65
- hooks: z
66
- .array(z.object({ command: z.string().optional(), asyncRewake: z.boolean().optional() }))
67
- .optional(),
68
- }))
69
- .optional(),
70
- })
66
+ .array(z.object({ command: z.string().optional(), asyncRewake: z.boolean().optional() }))
71
67
  .optional(),
68
+ }))
69
+ .optional();
70
+ const SettingsSchema = z.object({
71
+ hooks: z.object({ Stop: HookGroupsSchema, PreToolUse: HookGroupsSchema }).optional(),
72
+ });
73
+ /** How a Claude Code session names the tools of the bridge's server, and what rules match them by. */
74
+ export const CLAUDE_TOOLS_PREFIX = `mcp__${BRIDGE_TOOLS_SERVER}`;
75
+ /** The permission rule that lets a session call the bridge's tools without a prompt. */
76
+ export const CLAUDE_TOOLS_PERMISSION = CLAUDE_TOOLS_PREFIX;
77
+ /** Seconds the hook that names the session of a tool call may take. */
78
+ const CALLER_HOOK_TIMEOUT_S = 15;
79
+ /** The command a hook of a Claude Code session runs before a call of a bridge tool. */
80
+ export function claudeCallerCommand(options = {}) {
81
+ return `${options.bridgeCommand ?? 'cogitator bridge'} caller --hook ${HARNESSES.claudeCode}`;
82
+ }
83
+ /**
84
+ * The settings that tell the bridge's tools which Claude Code session calls them: a `PreToolUse`
85
+ * hook on the tools of the bridge's server that adds the session to the arguments of the call.
86
+ * Claude Code starts the server once and keeps it across `/clear`, so the session the server was
87
+ * started for is not always the one that calls. Without the hook the tools go by that first
88
+ * session.
89
+ */
90
+ export function claudeToolsHook(options = {}) {
91
+ return {
92
+ hooks: {
93
+ PreToolUse: [
94
+ {
95
+ matcher: `${CLAUDE_TOOLS_PREFIX}__.*`,
96
+ hooks: [
97
+ {
98
+ type: 'command',
99
+ command: claudeCallerCommand(options),
100
+ timeout: CALLER_HOOK_TIMEOUT_S,
101
+ },
102
+ ],
103
+ },
104
+ ],
105
+ },
106
+ };
107
+ }
108
+ /** Whether Claude Code settings hold the hook that names the session of a bridge tool call. */
109
+ export function hasClaudeToolsHook(settings) {
110
+ const parsed = SettingsSchema.safeParse(settings);
111
+ if (!parsed.success)
112
+ return false;
113
+ return (parsed.data.hooks?.PreToolUse ?? []).some((group) => (group.hooks ?? []).some((hook) => /\bbridge\s+caller\b/.test(hook.command ?? '')));
114
+ }
115
+ const ToolHookInputSchema = z.object({
116
+ session_id: z.string().min(1),
117
+ cwd: z.string().min(1).optional(),
118
+ tool_input: z.record(z.string(), z.unknown()),
72
119
  });
120
+ /**
121
+ * What the hook of `claudeToolsHook` answers Claude Code with: the arguments of the call with
122
+ * the session that makes it added (`hookSpecificOutput.updatedInput`). Undefined when the input
123
+ * is not that of a `PreToolUse` hook, and the call goes on as the model wrote it.
124
+ *
125
+ * @param hookInput what Claude Code wrote to the hook's stdin
126
+ */
127
+ export function claudeToolCallHook(hookInput) {
128
+ let input;
129
+ try {
130
+ input = JSON.parse(hookInput);
131
+ }
132
+ catch {
133
+ return undefined;
134
+ }
135
+ const parsed = ToolHookInputSchema.safeParse(input);
136
+ if (!parsed.success)
137
+ return undefined;
138
+ const { session_id: session, cwd, tool_input: args } = parsed.data;
139
+ const hint = {
140
+ harness: HARNESSES.claudeCode,
141
+ session,
142
+ ...(cwd && { cwd: resolve(cwd) }),
143
+ };
144
+ return JSON.stringify({
145
+ hookSpecificOutput: {
146
+ hookEventName: 'PreToolUse',
147
+ updatedInput: { ...args, [TOOL_CALL_HINT_KEY]: hint },
148
+ },
149
+ });
150
+ }
73
151
  const HookInputSchema = z.object({
74
152
  session_id: z.string().min(1),
75
153
  cwd: z.string().min(1).optional(),
@@ -81,12 +159,52 @@ const ListedSessionSchema = z.object({
81
159
  name: z.string().optional(),
82
160
  pid: z.number().optional(),
83
161
  status: z.string().optional(),
162
+ state: z.string().optional(),
84
163
  });
164
+ const ServersSchema = z.record(z.string(), z.unknown()).optional();
85
165
  const TrustConfigSchema = z.object({
86
166
  projects: z
87
- .record(z.string(), z.object({ hasTrustDialogAccepted: z.boolean().optional() }))
167
+ .record(z.string(), z.object({ hasTrustDialogAccepted: z.boolean().optional(), mcpServers: ServersSchema }))
88
168
  .optional(),
169
+ mcpServers: ServersSchema,
89
170
  });
171
+ const ProjectServersSchema = z.object({ mcpServers: ServersSchema });
172
+ /**
173
+ * Where Claude Code has the bridge's server of tools for the sessions of a folder: `local`
174
+ * (this person, this project), `project` (the project's `.mcp.json`) or `user` (this person,
175
+ * every project). Undefined when it has it nowhere.
176
+ */
177
+ export function claudeToolsScope(folder, configPath = join(homedir(), '.claude.json')) {
178
+ const config = TrustConfigSchema.safeParse(readJson(configPath));
179
+ const projects = config.success ? (config.data.projects ?? {}) : {};
180
+ const folders = spellingsOf(folder).flatMap((start) => {
181
+ const up = [];
182
+ for (let current = start;; current = dirname(current)) {
183
+ up.push(current);
184
+ if (dirname(current) === current)
185
+ return up;
186
+ }
187
+ });
188
+ if (folders.some((dir) => projects[dir]?.mcpServers?.[BRIDGE_TOOLS_SERVER] !== undefined)) {
189
+ return 'local';
190
+ }
191
+ const shared = folders.some((dir) => {
192
+ const file = ProjectServersSchema.safeParse(readJson(join(dir, '.mcp.json')));
193
+ return file.success && file.data.mcpServers?.[BRIDGE_TOOLS_SERVER] !== undefined;
194
+ });
195
+ if (shared)
196
+ return 'project';
197
+ return config.success && config.data.mcpServers?.[BRIDGE_TOOLS_SERVER] !== undefined
198
+ ? 'user'
199
+ : undefined;
200
+ }
201
+ /**
202
+ * The ways a folder may be written in what Claude Code keeps: by its real path, which is how
203
+ * Claude Code names a project, and as it was given.
204
+ */
205
+ function spellingsOf(folder) {
206
+ return [...new Set([canonicalPath(folder), resolve(folder)])];
207
+ }
90
208
  /**
91
209
  * Whether Claude Code trusts a folder, read from where it records that a person accepted its
92
210
  * trust prompt (`projects[<folder>].hasTrustDialogAccepted` in `~/.claude.json`). Trust of a
@@ -111,8 +229,12 @@ export function claudeTrust(folder, configPath = join(homedir(), '.claude.json')
111
229
  return 'untrusted';
112
230
  }
113
231
  }
232
+ /** What sets a project up for the sessions a person opens in it. */
233
+ const INSTALL = 'cogitator bridge install claude';
114
234
  const DEFAULT_SESSION_LISTED_MS = 30_000;
115
235
  const LISTING_INTERVAL_MS = 300;
236
+ /** How `claude agents --json` marks a background session that died before it began */
237
+ const FAILED_STATE = 'failed';
116
238
  const SHORT_ID = /backgrounded\s*[·:-]?\s*([0-9a-f]{6,})\b/i;
117
239
  function untrusted(folder) {
118
240
  return new Error(`Claude Code does not trust ${folder} yet. Open the folder in Claude Code once and accept its trust prompt, then hand the job over again`);
@@ -159,6 +281,9 @@ export function claudeCodeAdapter(options = {}) {
159
281
  const deadline = Date.now() + (options.sessionListedMs ?? DEFAULT_SESSION_LISTED_MS);
160
282
  for (;;) {
161
283
  const session = (await listed()).find((candidate) => candidate.id === shortId);
284
+ if (session?.state === FAILED_STATE) {
285
+ throw new Error(`Claude Code started the background session ${shortId}, and it failed before its first turn`);
286
+ }
162
287
  if (session?.sessionId) {
163
288
  return { sessionId: session.sessionId };
164
289
  }
@@ -168,13 +293,38 @@ export function claudeCodeAdapter(options = {}) {
168
293
  await pause(LISTING_INTERVAL_MS);
169
294
  }
170
295
  }
296
+ /**
297
+ * `--mcp-config` takes every argument up to the next option, so it stands before `--settings`
298
+ * and never right before the first letter, which it would read as one more file of servers.
299
+ */
171
300
  async function createSession(request) {
172
301
  if (claudeTrust(request.cwd, configPath) === 'untrusted')
173
302
  throw untrusted(request.cwd);
174
303
  const whole = fitsArgument(request.firstLetter.text);
175
- const settings = claudeWaitHook({ ...hook, agentName: request.agentName });
304
+ const tools = options.toolsServer;
305
+ const waits = claudeWaitHook({ ...hook, agentName: request.agentName, tools: !!tools });
306
+ const settings = tools
307
+ ? {
308
+ hooks: { ...waits.hooks, ...claudeToolsHook(hook).hooks },
309
+ permissions: { allow: [CLAUDE_TOOLS_PERMISSION] },
310
+ }
311
+ : waits;
312
+ const servers = tools && {
313
+ mcpServers: {
314
+ [BRIDGE_TOOLS_SERVER]: {
315
+ command: tools.command,
316
+ args: [...tools.args],
317
+ env: toolsServerEnv({
318
+ harness: HARNESSES.claudeCode,
319
+ agentName: request.agentName,
320
+ ...(request.sessionName && { sessionName: request.sessionName }),
321
+ }),
322
+ },
323
+ },
324
+ };
176
325
  const result = await runCommand(command, [
177
326
  '--bg',
327
+ ...(servers ? ['--mcp-config', JSON.stringify(servers)] : []),
178
328
  '--settings',
179
329
  JSON.stringify(settings),
180
330
  ...(request.sessionName ? ['--name', request.sessionName] : []),
@@ -182,7 +332,11 @@ export function claudeCodeAdapter(options = {}) {
182
332
  ...(options.sessionArgs ?? []),
183
333
  whole
184
334
  ? request.firstLetter.text
185
- : tooLongNotice(request.firstLetter, options.bridgeCommand, bridgeHome),
335
+ : tooLongNotice(request.firstLetter, {
336
+ ...(options.bridgeCommand !== undefined && { bridgeCommand: options.bridgeCommand }),
337
+ ...(bridgeHome !== undefined && { bridgeHome }),
338
+ tools: !!tools,
339
+ }),
186
340
  ], {
187
341
  cwd: request.cwd,
188
342
  env: sessionEnv(env, {
@@ -340,12 +494,35 @@ export function claudeCodeAdapter(options = {}) {
340
494
  detail: armed
341
495
  ? `sessions opened in this folder wait for their mail (${armed})`
342
496
  : 'sessions a person opens in this folder do not wake for mail, they read it when asked. Sessions the bridge starts carry the hook themselves',
343
- ...(!armed && {
344
- fix: `Merge into ${places[0]}: ${JSON.stringify(claudeWaitHook(hook))}`,
345
- }),
497
+ ...(!armed && { fix: INSTALL }),
498
+ });
499
+ const scope = claudeToolsScope(context.cwd, configPath);
500
+ checks.push({
501
+ id: 'tools',
502
+ title: 'Bridge tools',
503
+ status: scope ? 'ok' : 'warn',
504
+ detail: scope
505
+ ? `sessions opened in this folder have the bridge's tools (${scope} config)`
506
+ : 'sessions a person opens in this folder have no bridge tools, they use its command line. Sessions the bridge starts get the tools themselves',
507
+ ...(!scope && { fix: INSTALL }),
346
508
  });
509
+ if (scope) {
510
+ const named = places.find((place) => hasClaudeToolsHook(readJson(place)));
511
+ checks.push({
512
+ id: 'caller',
513
+ title: 'Session of a tool call',
514
+ status: named ? 'ok' : 'warn',
515
+ detail: named
516
+ ? `a hook tells the tools which session calls them (${named})`
517
+ : 'the tools go by the session their server was started for: after /clear they act as the session before it',
518
+ ...(!named && { fix: INSTALL }),
519
+ });
520
+ }
347
521
  return checks;
348
522
  }
523
+ function toolCallHook(context) {
524
+ return context.hookInput === undefined ? undefined : claudeToolCallHook(context.hookInput);
525
+ }
349
526
  return {
350
527
  harness: HARNESSES.claudeCode,
351
528
  delivery: CLAUDE_DELIVERY,
@@ -353,6 +530,7 @@ export function claudeCodeAdapter(options = {}) {
353
530
  createSession,
354
531
  liveSessions,
355
532
  identify,
533
+ toolCallHook,
356
534
  health,
357
535
  };
358
536
  }