diff --git a/CHANGELOG.md b/CHANGELOG.md index fc2912a37..4f0ac7f57 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Fixed + +- `@agent-relay/events-shim`: a fresh Claude Code session set up with `setup --claude` is woken by webhook posts again, with nothing to tell it. Since 18.9.0 only a session that had called a `webhooks` MCP tool listened, so a new session never woke. Now the most recently started Claude Code session takes the inbox over at its start (not a `claude -p` run or a compaction), and the older session's listener stops before it takes another post. Calling a `webhooks` tool also takes the inbox over, and when the owning session has closed, the next session's hook takes it. Posts still go to one session only, and no hook listener takes posts while the inbox has a working relay wake link. +- `@agent-relay/events-shim`: `watch_webhooks` now says which Agent Relay agent a relay wake link wakes (`linked_agent`, `linked_at`) and tells the agent to compare that name with its own. Before, every session with the inbox's MCP server read `wake: linked` and was told "each post is injected into this session", so a session could claim a link that targets another agent. `link_relay_wake` takes the linking session's `agent` name and says when it moves the link away from another agent (`replaced_agent`). Links that events-shim makes for Codex and other CLIs woken through the core record the agent's name. The page feed reports it as `agent.wake_agent`. Hosts that persist `WakeTarget.agent` show the name; others report the link without one. +- `@agent-relay/events-shim setup`: each agent CLI keeps the inbox it was set up with (`inboxes` in `~/.config/agent-relay/webhooks.json`), so one machine can give Claude Code and Codex separate inboxes that wake each independently. Before, the last setup's inbox replaced every CLI's. One inbox wakes one session: setup now refuses to add a second waking CLI to an inbox another CLI already uses, or to an inbox linked to another agent, and points to making a separate inbox. `--share-inbox` adds the CLI anyway. When several CLIs share an inbox, setup says which session gets the posts and how that changes. + ## [18.10.0] - 2026-11-17 ### Added diff --git a/packages/events-shim/README.md b/packages/events-shim/README.md index bcb676636..63234d9b4 100644 --- a/packages/events-shim/README.md +++ b/packages/events-shim/README.md @@ -12,15 +12,25 @@ It adds the inbox's MCP server to every supported agent CLI on the machine, or o `--claude`, `--codex`, `--copilot`, `--cursor`, `--droid`, `--amp`, `--opencode`, `--muse`, `--gemini`, `--grok`, `--devin` (or `--cli claude,codex`). Each tool gets it its own way (`claude`/`codex`/`copilot`/`droid`/`amp`/`gemini`/`grok`/`devin`/`muse mcp add` at user scope; Cursor's `~/.cursor/mcp.json`, opencode's config file), re-running replaces it, and Claude Code and Codex also get -the `agent-relay-webhooks` skill. The inbox is saved to `~/.config/agent-relay/webhooks.json` (0600). Then tell the +the `agent-relay-webhooks` skill. The inbox is saved to `~/.config/agent-relay/webhooks.json` (0600), per CLI. Then tell the agent "watch for webhooks". Each post wakes it: +**One inbox wakes one session, not one per agent.** To wake Claude Code and Codex (or any two agents) independently, +make one inbox per agent and run `setup` once per agent with its own MCP URL (`setup '' --claude`, then +`setup '' --codex`). Each CLI keeps the inbox it was set up with. Setup refuses to add a second waking CLI to +an inbox another CLI already uses, or to an inbox linked to another agent's session, unless you pass `--share-inbox`. +When CLIs share an inbox, setup says which session gets the posts: a relay wake link (Codex and the other CLIs woken +through the core) takes every post while it works, and otherwise the hook listeners do. + - **Claude Code, with or without Agent Relay: nothing to do.** `setup --claude` also installs SessionStart and Stop hooks (`async`, `asyncRewake`) in `~/.claude/settings.json` that run `events-shim listen --hook`. It waits for the next post and exits 2 with it, which wakes the idle session with the post; each turn's Stop hook re-arms it. One - listener per session, and none for a closed session. The hooks run in every Claude Code session, but only a - session that used the `webhooks` MCP (its transcript shows a `watch_webhooks`, `link_relay_wake`, - `wait_for_webhook`, `get_webhook_events`, `ack_webhook_events` or `release_webhook_events` call) listens. While the inbox has a working relay wake link + listener per session, and none for a closed session. The hooks run in every Claude Code session, but the inbox + wakes one: the most recently started session takes it over at its start (not a `claude -p` run or a compaction), + and the older session's listener stops before it takes another post. A session that calls a `webhooks` MCP tool + (`watch_webhooks`, `link_relay_wake`, `wait_for_webhook`, `get_webhook_events`, `ack_webhook_events` or + `release_webhook_events`) takes it over too, so telling an older session "watch for webhooks" moves the posts to + it. When the owning session closes, the next session to start or finish a turn takes over. While the inbox has a working relay wake link (`link_relay_wake`), no hook listener takes posts: the link delivers each one to the session that made it. `npx @agent-relay/events-shim uninstall --claude` removes the hooks. - **Codex, with or without Agent Relay Desktop: nothing to do.** `setup --codex` installs a SessionStart hook in @@ -93,8 +103,8 @@ event arrives as a post naming the changed file (deduplicated per path and revis | Tool | What it does | | ------------------------ | ----------------------------------------------------------------------------------- | -| `watch_webhooks` | Start here: webhook URLs, wake state, waiting posts and next steps | -| `link_relay_wake` | Link the session's relay webhook (checked with a test post first) | +| `watch_webhooks` | Start here: webhook URLs, wake state and the agent a link wakes, waiting posts | +| `link_relay_wake` | Link the session's relay webhook (checked first); pass `agent`, your relay name | | `unlink_relay_wake` | Stop forwarding | | `get_webhook_events` | Unread posts (marks them read), or one post by id | | `wait_for_webhook` | Block until a post arrives (≤ 50 s), then return it (marks it read, or leases it) | @@ -124,6 +134,16 @@ it is handed to the session (or printed), and release it when the session let go leases (no `claim_token` in the result, see Hosting) they keep the older behaviour: the posts are already read, and a stop hook that let go keeps the post on disk for the next turn's hook. +### Which session a link wakes + +Every session that has the inbox's MCP server reads the same wake state, so `watch_webhooks` names the Agent Relay +agent a working link wakes (`linked_agent`, with `linked_at`) and tells the agent to compare it with its own name +before saying the inbox is linked to it. `link_relay_wake` records its `agent` argument (events-shim's own links for +Codex and the other CLIs woken through the core always pass it) and answers `replaced_agent` when it moves the link +away from another session. A link made without a name is reported as `linked_agent: null`, and the agent is told to +assume it wakes another session unless it made the link itself. Hosts keep the name in `WakeTarget.agent`. The page +feed shows it as `agent.wake_agent`. + ## Webhook URLs `/h/` accepts anyone holding the URL. `/github`, `/stripe`, `/linear` and `/bearer` suffixes diff --git a/packages/events-shim/src/cli.test.ts b/packages/events-shim/src/cli.test.ts index fa41c9674..15ce9f044 100644 --- a/packages/events-shim/src/cli.test.ts +++ b/packages/events-shim/src/cli.test.ts @@ -91,6 +91,29 @@ function claudeHook(session: string, extra: Record = {}, optedI return JSON.stringify({ session_id: session, transcript_path: transcript, ...extra }); } +/** Records \`session\` (its \`claude\` process \`pid\`) as the Claude Code session that owns the inbox's posts. */ +function claudeOwnedBy(home: string, mcpUrl: string, session: string, pid: number): void { + const dir = join(home, '.config', 'agent-relay'); + mkdirSync(dir, { recursive: true }); + const digest = createHash('sha256').update(mcpUrl).digest('hex').slice(0, 16); + writeFileSync(join(dir, `claude-owner-${digest}.json`), JSON.stringify({ session, pid })); +} + +function claudeOwnerOf(home: string, mcpUrl: string): string | null { + const digest = createHash('sha256').update(mcpUrl).digest('hex').slice(0, 16); + try { + return ( + JSON.parse( + readFileSync(join(home, '.config', 'agent-relay', `claude-owner-${digest}.json`), 'utf8') + ) as { + session: string; + } + ).session; + } catch { + return null; + } +} + /** A real inbox served in-process, and a CLI environment pointed at a temp HOME. */ async function setupWorld( options: { @@ -378,7 +401,14 @@ describe('events-shim CLI', () => { 'webhooks', w.created.mcp_url, ]); - expect(w.out.join('\n')).toContain('Each post wakes it by itself; there is nothing to tell it.'); + expect(w.out.join('\n')).toContain( + 'each post wakes the most recently started Claude Code session by itself, with nothing to tell it' + ); + expect(w.out.join('\n')).toContain( + 'Claude Code: MCP server "webhooks" added, skill installed; its most recently started session is woken by every post' + ); + // One CLI on the inbox: nothing about sharing it. + expect(w.out.join('\n')).not.toContain('One inbox wakes one session'); }); it('setup says when Agent Relay is running, and when no agent CLI is installed', async () => { @@ -609,7 +639,7 @@ describe('events-shim CLI', () => { expect(await runCli(['setup', w.created.mcp_url, '--cursor'], w.io)).toBe(0); expect(modeOf(cursor)).toBe(0o600); const fresh = join(w.home, '.config', 'opencode', 'opencode.json'); - expect(await runCli(['setup', w.created.mcp_url, '--opencode'], w.io)).toBe(0); + expect(await runCli(['setup', w.created.mcp_url, '--opencode', '--share-inbox'], w.io)).toBe(0); expect(modeOf(fresh)).toBe(0o600); // Exists but unreadable: left alone, with the manual step. @@ -794,7 +824,7 @@ describe('events-shim CLI', () => { expect(w.mints).toHaveLength(1); expect(w.downloads).toHaveLength(1); // Setting up another CLI on the same inbox keeps the Codex workspace. - expect(await runCli(['setup', w.created.mcp_url, '--claude'], w.io)).toBe(0); + expect(await runCli(['setup', w.created.mcp_url, '--claude', '--share-inbox'], w.io)).toBe(0); expect(JSON.parse(readFileSync(configPath(w.io), 'utf8')).workspaceKey).toBe('rk_live_temp1'); // The core adds its own Codex hooks; uninstall removes them and stops the core it started. @@ -864,8 +894,8 @@ describe('events-shim CLI', () => { 'Devin: MCP server "webhooks" added; its newest open session is woken by every post' ); - // Adding Muse later keeps the others. - expect(await runCli(['setup', w.created.mcp_url, '--muse'], w.io)).toBe(0); + // Adding Muse later (to the same inbox, so asked for) keeps the others. + expect(await runCli(['setup', w.created.mcp_url, '--muse', '--share-inbox'], w.io)).toBe(0); expect(JSON.parse(readFileSync(configPath(w.io), 'utf8')).wakeKinds).toEqual([ 'codex', 'devin', @@ -1014,10 +1044,14 @@ describe('events-shim CLI', () => { () => { byId('dv_d').live = false; }, - // The inbox changes: the same open session is linked again for it. + // The inbox changes (setup again with another one): the same open session is linked again for it. () => { const saved = JSON.parse(readFileSync(configPath(w.io), 'utf8')); - writeFileSync(configPath(w.io), JSON.stringify({ ...saved, mcpUrl: `${saved.mcpUrl}/` })); + const next = saved.mcpUrl.replace(/esm_[A-Za-z0-9_-]{43}/, `esm_${'n'.repeat(43)}`); + writeFileSync( + configPath(w.io), + JSON.stringify({ ...saved, mcpUrl: next, inboxes: { opencode: next, devin: next } }) + ); }, ]; w.io.sleep = vi.fn(async () => { @@ -1156,10 +1190,13 @@ describe('events-shim CLI', () => { ['agents.webhook.create', { name: 'codex-01a1' }], ['agents.webhook.create', { name: 'codex-01a1' }], ]); + // The link names the session's agent, so the inbox can tell every session which one it wakes. expect(linked).toEqual({ url: 'https://cast.agentrelay.com/v1/hooks/wh2', secret: 'wh_live_0123456789abcdef', + agent: 'codex-01a1', }); + expect((await inboxTool(w, 'watch_webhooks')).linked_agent).toBe('codex-01a1'); expect(w.logs.at(-1)).toContain('linked codex-01a1'); // The inbox call fails after the webhook was made: it is still recorded as ours, so a retry replaces it. const fetchOk = w.io.fetchImpl; @@ -1228,24 +1265,76 @@ describe('events-shim CLI', () => { expect(woke).toContain('untrusted data'); }); - it('listen --hook listens only in a session that opted in to the inbox, and remembers it', async () => { - const w = await fileWorld({ stdin: claudeHook('other-1', {}, false) }); - await runCli(['setup', w.created.mcp_url], w.io); - await w.post({ for: 'the session that asked' }); - // Every Claude Code session runs the hook, but this one never used the webhooks MCP: it takes nothing. + it('listen --hook: a fresh session wakes with nothing said to it; a session that does not own the inbox takes nothing', async () => { + const w = await fileWorld({ stdin: claudeHook('other-1', { hook_event_name: 'Stop' }, false) }); + await runCli(['setup', w.created.mcp_url, '--claude'], w.io); + // A newer session (its Claude Code still open) owns the inbox: every other session's hook runs too, but takes nothing. + claudeOwnedBy(w.home, w.created.mcp_url, 'newer-1', 777); + await w.post({ for: 'the newest session' }); expect(await runCli(['listen', '--hook'], w.io)).toBe(0); expect(w.err).toEqual([]); - expect((await inboxTool(w, 'watch_webhooks')).waiting).toBe(1); // still there for the session that asked - const optedIn = await fileWorld({ stdin: claudeHook('mine-1') }); - await runCli(['setup', optedIn.created.mcp_url], optedIn.io); - await optedIn.post({ for: 'me' }); - expect(await runCli(['listen', '--hook'], optedIn.io)).toBe(2); - expect(optedIn.err.join('\n')).toContain('{"for":"me"}'); - const dir = join(optedIn.home, '.config', 'agent-relay'); - expect(readdirSync(dir).some((file) => file.startsWith('optin-'))).toBe(true); + expect((await inboxTool(w, 'watch_webhooks')).waiting).toBe(1); // still there for the owner + + // A brand-new session that never used the webhooks MCP takes the inbox over by starting, and is woken. + w.io.readStdin = async () => + claudeHook('fresh-1', { hook_event_name: 'SessionStart', source: 'startup' }, false); + expect(await runCli(['listen', '--hook'], w.io)).toBe(2); + expect(w.err.join('\n')).toContain('{"for":"the newest session"}'); + expect(claudeOwnerOf(w.home, w.created.mcp_url)).toBe('fresh-1'); + }); + + it('listen --hook: a newer session takes the inbox over and the older listener stops before taking a post', async () => { + const w = await fileWorld(); + await runCli(['setup', w.created.mcp_url, '--claude'], w.io); + // Two Claude Code sessions, each with its own hook process (pids 4242 and 5002) and output. + for (const pid of [4242, 5002]) w.listeners.add(pid); + const errs: Record = { first: [], second: [] }; + const tick = () => new Promise((resolve) => setTimeout(resolve, 10)); + const session = (name: 'first' | 'second', pid: number): CliIo => ({ + ...w.io, + pid, + stderr: (line) => errs[name]!.push(line), + readStdin: async () => + claudeHook(`${name}-1`, { hook_event_name: 'SessionStart', source: 'startup' }, false), + sleep: tick, + }); + const first = runCli(['listen', '--hook'], session('first', 4242)); + await new Promise((resolve) => setTimeout(resolve, 100)); + expect(claudeOwnerOf(w.home, w.created.mcp_url)).toBe('first-1'); + const second = runCli(['listen', '--hook'], session('second', 5002)); + // The older listener notices the takeover and leaves without a post. + expect(await first).toBe(0); + expect(claudeOwnerOf(w.home, w.created.mcp_url)).toBe('second-1'); + await w.post({ for: 'the newer session' }); + expect(await second).toBe(2); + expect(errs.second!.join('\n')).toContain('{"for":"the newer session"}'); + expect(errs.first).toEqual([]); + }, 15_000); + + it("listen --hook: a closed owner's inbox goes to the next session's hook; claude -p and compaction take nothing over", async () => { + const w = await fileWorld({ stdin: claudeHook('next-1', { hook_event_name: 'Stop' }, false) }); + await runCli(['setup', w.created.mcp_url, '--claude'], w.io); + claudeOwnedBy(w.home, w.created.mcp_url, 'gone-1', 999); // its Claude Code has exited + await w.post({ for: 'whoever is left' }); + expect(await runCli(['listen', '--hook'], w.io)).toBe(2); + expect(claudeOwnerOf(w.home, w.created.mcp_url)).toBe('next-1'); + + // A non-interactive \`claude -p\` run starting, or a session compacting, does not take it from next-1. + await w.post({ for: 'next-1 still' }); + const processArgs = w.io.processArgs; + w.io.processArgs = (pid) => (pid === 777 ? 'claude -p summarize this' : processArgs(pid)); + w.io.readStdin = async () => + claudeHook('print-1', { hook_event_name: 'SessionStart', source: 'startup' }, false); + expect(await runCli(['listen', '--hook'], w.io)).toBe(0); + w.io.processArgs = processArgs; + w.io.readStdin = async () => + claudeHook('compact-1', { hook_event_name: 'SessionStart', source: 'compact' }, false); + expect(await runCli(['listen', '--hook'], w.io)).toBe(0); + expect(claudeOwnerOf(w.home, w.created.mcp_url)).toBe('next-1'); + expect((await inboxTool(w, 'watch_webhooks')).waiting).toBe(1); }); - it('listen --hook finds an opt-in past the first chunk of a long transcript, reading each part once', async () => { + it('listen --hook: a webhooks tool call takes the inbox over, found past the first chunk of a long transcript, reading each part once', async () => { const dir = mkdtempSync(join(tmpdir(), 'events-shim-transcript-')); const transcript = join(dir, 'long-1.jsonl'); const turn = (n: number) => @@ -1261,6 +1350,7 @@ describe('events-shim CLI', () => { return readTextChunk(path, offset, 100); }; await runCli(['setup', w.created.mcp_url], w.io); + claudeOwnedBy(w.home, w.created.mcp_url, 'newer-1', 777); // another session owns the inbox await w.post({ for: 'the long session' }); expect(await runCli(['listen', '--hook'], w.io)).toBe(0); // no webhooks call yet const scanned = Math.max(...reads); @@ -1276,8 +1366,10 @@ describe('events-shim CLI', () => { })}\n` ); reads.length = 0; + // The call takes the inbox over for this session. expect(await runCli(['listen', '--hook'], w.io)).toBe(2); expect(w.err.join('\n')).toContain('{"for":"the long session"}'); + expect(claudeOwnerOf(w.home, w.created.mcp_url)).toBe('long-1'); expect(Math.min(...reads)).toBeGreaterThanOrEqual(scanned - 100); }); @@ -1303,7 +1395,7 @@ describe('events-shim CLI', () => { expect(readTextChunk(file, 1, 4)).toEqual({ text: '😀', end: 5 }); }); - it('listen --hook finds an opt-in right after a chunk boundary inside a character', async () => { + it('listen --hook finds a webhooks tool call right after a chunk boundary inside a character', async () => { const dir = mkdtempSync(join(tmpdir(), 'events-shim-transcript-')); const transcript = join(dir, 'split-1.jsonl'); const call = JSON.stringify({ @@ -1326,7 +1418,7 @@ describe('events-shim CLI', () => { expect(w.err.join('\n')).toContain('{"for":"split"}'); }); - it('listen --hook: a webhooks tool name inside another call is not an opt-in', async () => { + it('listen --hook: a webhooks tool name inside another call does not take the inbox over', async () => { const dir = mkdtempSync(join(tmpdir(), 'events-shim-transcript-')); const transcript = join(dir, 'other-2.jsonl'); writeFileSync( @@ -1348,6 +1440,7 @@ describe('events-shim CLI', () => { stdin: JSON.stringify({ session_id: 'other-2', transcript_path: transcript }), }); await runCli(['setup', w.created.mcp_url], w.io); + claudeOwnedBy(w.home, w.created.mcp_url, 'newer-1', 777); await w.post({ for: 'someone else' }); expect(await runCli(['listen', '--hook'], w.io)).toBe(0); expect((await inboxTool(w, 'watch_webhooks')).waiting).toBe(1); @@ -1371,6 +1464,24 @@ describe('events-shim CLI', () => { expect((await inboxTool(w, 'watch_webhooks')).waiting).toBe(1); }); + it('listen --hook takes nothing when its session closes while it asks whether the inbox leases', async () => { + const w = await fileWorld({ stdin: claudeHook('closing-2') }); + await runCli(['setup', w.created.mcp_url], w.io); + await w.post({ for: 'a live session' }); + const fetchImpl = w.io.fetchImpl; + w.io.fetchImpl = async (input, init) => { + const response = await fetchImpl(input, init); + if (typeof init?.body === 'string' && init.body.includes('"tools/list"')) { + w.io.pidAlive = (pid) => pid === 4242; // Claude (777) exits meanwhile + } + return response; + }; + expect(await runCli(['listen', '--hook'], w.io)).toBe(0); + expect(w.err).toEqual([]); + w.io.fetchImpl = fetchImpl; + expect((await inboxTool(w, 'watch_webhooks')).waiting).toBe(1); + }); + it('listen --hook stands down while the inbox forwards posts through a relay wake link', async () => { const w = await fileWorld({ stdin: claudeHook('abc-123') }); await runCli(['setup', w.created.mcp_url], w.io); @@ -1425,6 +1536,176 @@ describe('events-shim CLI', () => { expect(() => readFileSync(lockFile, 'utf8')).toThrow(); // released on exit }); + for (const leases of [true, false]) { + it(`listen --hook hands a post claimed just as another session took over to the new owner (${leases ? 'inbox with leases' : 'inbox without leases'})`, async () => { + const w = await fileWorld({ + noLeases: !leases, + stdin: claudeHook('old-1', { hook_event_name: 'SessionStart', source: 'startup' }, false), + }); + await runCli(['setup', w.created.mcp_url, '--claude'], w.io); + await w.post({ for: 'the new owner' }); + const fetchImpl = w.io.fetchImpl; + w.io.fetchImpl = async (input, init) => { + const response = await fetchImpl(input, init); + // A newer session starts while the wait is returning the post. + if (typeof init?.body === 'string' && init.body.includes('"wait_for_webhook"')) + claudeOwnedBy(w.home, w.created.mcp_url, 'new-1', 777); + return response; + }; + expect(await runCli(['listen', '--hook'], w.io)).toBe(0); + expect(w.err).toEqual([]); // the old session is not woken with it + w.io.fetchImpl = fetchImpl; + w.io.readStdin = async () => claudeHook('new-1', { hook_event_name: 'Stop' }, false); + expect(await runCli(['listen', '--hook'], w.io)).toBe(2); + expect(w.err.join('\n')).toContain('{"for":"the new owner"}'); + }); + } + + it('listen --hook takes a post a release before canonical inbox URLs kept under the trailing-slash name', async () => { + const w = await fileWorld({ + stdin: claudeHook('up-1', { hook_event_name: 'SessionStart', source: 'startup' }, false), + }); + await runCli(['setup', w.created.mcp_url, '--claude'], w.io); + const digest = createHash('sha256').update(`${w.created.mcp_url}/`).digest('hex').slice(0, 16); + writeFileSync(join(w.home, '.config', 'agent-relay', `held-${digest}.txt`), 'kept by an older release'); + expect(await runCli(['listen', '--hook'], w.io)).toBe(2); + expect(w.err.join('\n')).toContain('kept by an older release'); + }); + + it('listen --hook: a claude -p run never takes a vacant inbox by itself', async () => { + const w = await fileWorld({ stdin: claudeHook('print-2', { hook_event_name: 'Stop' }, false) }); + await runCli(['setup', w.created.mcp_url, '--claude'], w.io); + await w.post({ for: 'an interactive session' }); + const processArgs = w.io.processArgs; + w.io.processArgs = (pid) => (pid === 777 ? 'claude --print run the report' : processArgs(pid)); + expect(await runCli(['listen', '--hook'], w.io)).toBe(0); // no owner yet, still not taken + expect(claudeOwnerOf(w.home, w.created.mcp_url)).toBeNull(); + expect((await inboxTool(w, 'watch_webhooks')).waiting).toBe(1); + }); + + it("a config saved before per-CLI inboxes keeps a turn-end CLI's hook on its inbox too", async () => { + const w = await fileWorld(); + const old = 'https://shim.test/api/v1/events-shim/t/esm_' + 'b'.repeat(43) + '/mcp'; + mkdirSync(dirname(configPath(w.io)), { recursive: true }); + writeFileSync(configPath(w.io), JSON.stringify({ mcpUrl: old })); + mkdirSync(join(w.home, '.copilot', 'hooks'), { recursive: true }); + writeFileSync( + join(w.home, '.copilot', 'hooks', 'agent-relay-webhooks.json'), + JSON.stringify({ hooks: { agentStop: [{ type: 'command', bash: stopHookCommand('copilot') }] } }) + ); + expect(await runCli(['setup', w.created.mcp_url, '--claude'], w.io)).toBe(0); + expect(JSON.parse(readFileSync(configPath(w.io), 'utf8')).inboxes).toEqual({ + copilot: old, + claude: w.created.mcp_url, + }); + }); + + it('setup refuses to add a second waking CLI to an inbox another one uses, unless asked, and then says which session wins', async () => { + const w = await fileWorld({ core: true }); + expect(await runCli(['setup', w.created.mcp_url, '--claude'], w.io)).toBe(0); + const saved = readFileSync(configPath(w.io), 'utf8'); + expect(await runCli(['setup', w.created.mcp_url, '--codex'], w.io)).toBe(2); + const refused = w.err.join('\n'); + expect(refused).toContain( + 'This inbox already wakes Claude Code. One inbox wakes one session, not one per agent' + ); + expect(refused).toContain( + 'make another at https://agentrelay.com/mcp-events-shim and run setup with its MCP URL --codex' + ); + expect(refused).toContain('--share-inbox'); + expect(readFileSync(configPath(w.io), 'utf8')).toBe(saved); // nothing changed + expect(w.runs.some((run) => run[0] === 'codex')).toBe(false); + + // Asked for: set up, and setup says plainly which session gets the posts. + w.out.length = 0; + expect(await runCli(['setup', w.created.mcp_url, '--codex', '--share-inbox'], w.io)).toBe(0); + const said = w.out.join('\n'); + expect(said).toContain( + 'One inbox wakes one session, not one per agent. Claude Code, Codex share this inbox, so:' + ); + expect(said).toContain('Once a Codex session is open, the inbox is linked to the newest one'); + expect(said).toContain('While that link works, Claude Code sessions get none.'); + expect(said).toContain('give each its own inbox'); + // Re-running the same setup is not adding anything: no refusal. + expect(await runCli(['setup', w.created.mcp_url, '--claude', '--codex'], w.io)).toBe(0); + }); + + it('setup of several CLIs on one inbox says one session wins; an inbox linked to another agent is refused by name', async () => { + const w = await fileWorld({ core: true }); + expect(await runCli(['setup', w.created.mcp_url, '--claude', '--codex'], w.io)).toBe(0); + expect(w.out.join('\n')).toContain('One inbox wakes one session, not one per agent'); + + const other = await fileWorld(); + await inboxTool(other, 'link_relay_wake', { + url: 'https://cast.agentrelay.com/v1/hooks/h1', + secret: 'wh_live_0123456789abcdef', + agent: 'codex-elsewhere', + }); + expect(await runCli(['setup', other.created.mcp_url, '--claude'], other.io)).toBe(2); + expect(other.err.join('\n')).toContain( + 'This inbox already wakes the Agent Relay agent "codex-elsewhere"' + ); + expect(await runCli(['setup', other.created.mcp_url, '--claude', '--share-inbox'], other.io)).toBe(0); + expect(other.out.join('\n')).toContain( + 'The inbox is linked to the Agent Relay agent "codex-elsewhere" now: it gets every post, and Claude Code sessions get none' + ); + }); + + it('each agent CLI keeps its own inbox: Claude Code wakes on one, Codex is linked to the other', async () => { + const w = await fileWorld({ + core: true, + stdin: claudeHook('claude-1', { hook_event_name: 'SessionStart', source: 'startup' }, false), + }); + // A second inbox on the same host, for Codex. + const second = (await (await w.shimFetch(`${BASE}/shims`, { method: 'POST' })).json()) as { + mcp_url: string; + webhook_url: string; + }; + expect(await runCli(['setup', w.created.mcp_url, '--claude'], w.io)).toBe(0); + expect(await runCli(['setup', second.mcp_url, '--codex'], w.io)).toBe(0); // its own inbox: no refusal + const config = JSON.parse(readFileSync(configPath(w.io), 'utf8')); + expect(config.inboxes).toEqual({ claude: w.created.mcp_url, codex: second.mcp_url }); + expect(w.out.join('\n')).not.toContain('One inbox wakes one session'); + + // Codex's session is linked to its own inbox, by name. + w.core.hooks = 1; + w.core.agents.push({ name: 'codex-abc', target: { kind: 'codex', id: 'thread-abc' } }); + expect(await runCli(['link', '--kind', 'codex', '--session', 'thread-abc'], w.io)).toBe(0); + expect(await inboxTool({ ...w, created: second as typeof w.created }, 'watch_webhooks')).toMatchObject({ + wake: 'linked', + linked_agent: 'codex-abc', + }); + // Claude Code's inbox is not linked, so a fresh Claude Code session is woken by its posts. + expect((await inboxTool(w, 'watch_webhooks')).wake).toBe('none'); + await w.post({ for: 'claude' }); + expect(await runCli(['listen', '--hook'], w.io)).toBe(2); + expect(w.err.join('\n')).toContain('{"for":"claude"}'); + }); + + it('the same inbox written with or without a trailing slash is one inbox to setup', async () => { + const w = await fileWorld({ core: true }); + expect(await runCli(['setup', w.created.mcp_url, '--claude'], w.io)).toBe(0); + // The slash form reaches the same inbox: adding Codex there is still refused without --share-inbox. + expect(await runCli(['setup', `${w.created.mcp_url}/`, '--codex'], w.io)).toBe(2); + expect(w.err.join('\n')).toContain('This inbox already wakes Claude Code'); + expect(await runCli(['setup', `${w.created.mcp_url}/`, '--claude'], w.io)).toBe(0); + expect(JSON.parse(readFileSync(configPath(w.io), 'utf8')).inboxes).toEqual({ claude: w.created.mcp_url }); + }); + + it('a config saved before per-CLI inboxes keeps the CLIs it set up on their inbox when another inbox is set up', async () => { + const w = await fileWorld({ core: true }); + const old = 'https://shim.test/api/v1/events-shim/t/esm_' + 'a'.repeat(43) + '/mcp'; + mkdirSync(dirname(configPath(w.io)), { recursive: true }); + writeFileSync(configPath(w.io), JSON.stringify({ mcpUrl: old, wakeKinds: ['codex'] })); + expect(await runCli(['setup', w.created.mcp_url, '--claude'], w.io)).toBe(0); + const config = JSON.parse(readFileSync(configPath(w.io), 'utf8')); + expect(config).toMatchObject({ + mcpUrl: w.created.mcp_url, + wakeKinds: ['codex'], + inboxes: { codex: old, claude: w.created.mcp_url }, + }); + }); + it('a duplicate post says it was not delivered again', async () => { const w = await setupWorld(); const send = () => diff --git a/packages/events-shim/src/cli.ts b/packages/events-shim/src/cli.ts index 8b1bebfb1..9d3640ad5 100644 --- a/packages/events-shim/src/cli.ts +++ b/packages/events-shim/src/cli.ts @@ -101,7 +101,13 @@ export interface CliIo { } interface Config { + /** The inbox setup was last run with: \`listen\`, \`forward\` and any CLI without its own entry use it. */ mcpUrl: string; + /** + * The inbox each agent CLI was set up with, by CLI id (\`claude\`, \`codex\`, …). One inbox wakes + * one session, so each agent can have its own: its hooks and links use its entry. + */ + inboxes?: Record; /** The Agent Relay workspace key the standalone core runs with, when no signed-in core is running. */ workspaceKey?: string; /** When a temporary workspace expires (ISO), if it is one. */ @@ -115,9 +121,11 @@ interface Config { } const USAGE = `Usage: - npx @agent-relay/events-shim setup [--claude] [--codex] [--copilot] [--cursor] [--droid] [--amp] [--opencode] [--muse] [--gemini] [--grok] [--devin] + npx @agent-relay/events-shim setup [--claude] [--codex] [--copilot] [--cursor] [--droid] [--amp] [--opencode] [--muse] [--gemini] [--grok] [--devin] [--share-inbox] Add the inbox's MCP server to those agent CLIs (default: every one - installed here) and install the webhooks skill + installed here) and install the webhooks skill. One inbox wakes one + session: give each agent its own inbox (--share-inbox adds a CLI to + an inbox another one already uses) npx @agent-relay/events-shim uninstall [--claude] [--codex] … Remove the MCP server, wake hooks and skill again npx @agent-relay/events-shim listen Wait for the next webhook post, print it and exit @@ -139,10 +147,25 @@ export function configPath(io: CliIo): string { return join(base, 'agent-relay', 'webhooks.json'); } +/** + * One inbox's MCP URL in one form: \`…/mcp/\` and \`…/mcp\` reach the same inbox, so they must compare + * (and hash, for its locks and owner record) the same. + */ +function canonicalInbox(url: string): string { + return url.replace(/\/mcp\/$/, '/mcp'); +} + function readConfig(io: CliIo): Config | null { try { const parsed = JSON.parse(readFileSync(configPath(io), 'utf8')) as Config; - return typeof parsed.mcpUrl === 'string' && parsed.mcpUrl ? parsed : null; + if (typeof parsed.mcpUrl !== 'string' || !parsed.mcpUrl) return null; + parsed.mcpUrl = canonicalInbox(parsed.mcpUrl); + if (parsed.inboxes && typeof parsed.inboxes === 'object') { + parsed.inboxes = Object.fromEntries( + Object.entries(parsed.inboxes).map(([id, url]) => [id, canonicalInbox(String(url))]) + ); + } + return parsed; } catch { return null; } @@ -157,9 +180,25 @@ function writePrivate(path: string, contents: string): void { renameSync(temporary, path); } -/** The inbox's MCP URL from `--mcp-url`, `AGENT_RELAY_WEBHOOKS_MCP_URL`, or the saved config. */ -function mcpUrlFor(io: CliIo, flags: Record): string | null { - return flags['mcp-url'] || io.env.AGENT_RELAY_WEBHOOKS_MCP_URL || readConfig(io)?.mcpUrl || null; +/** The inbox an agent CLI was set up with: its own entry, else the last one setup saved. */ +function inboxOf(config: Config, cli?: string): string { + return (cli && config.inboxes?.[cli]) || config.mcpUrl; +} + +/** The agent CLI whose sessions the core lists as \`kind\` (\`codex\`, \`grok-open\`, …). */ +function cliOfKind(kind: string): string { + return AGENT_CLIS.find((cli) => cli.coreKind === kind)?.id ?? kind; +} + +/** + * The inbox's MCP URL from \`--mcp-url\`, \`AGENT_RELAY_WEBHOOKS_MCP_URL\`, or the saved config (the + * inbox \`cli\` was set up with, when given). + */ +function mcpUrlFor(io: CliIo, flags: Record, cli?: string): string | null { + const given = flags['mcp-url'] || io.env.AGENT_RELAY_WEBHOOKS_MCP_URL; + if (given) return canonicalInbox(given); + const config = readConfig(io); + return config ? inboxOf(config, cli) : null; } function checkMcpUrl(raw: string): string | null { @@ -167,12 +206,34 @@ function checkMcpUrl(raw: string): string | null { const url = new URL(raw); if (url.protocol !== 'https:' && url.hostname !== 'localhost' && url.hostname !== '127.0.0.1') return null; - return /\/t\/esm_[A-Za-z0-9_-]{43}\/mcp\/?$/.test(url.pathname) ? url.toString() : null; + return /\/t\/esm_[A-Za-z0-9_-]{43}\/mcp\/?$/.test(url.pathname) ? canonicalInbox(url.toString()) : null; } catch { return null; } } +/** Whether the inbox leases \`wait_for_webhook\` claims (it lists \`release_webhook_events\`); false when unknown. */ +async function inboxLeases(io: CliIo, mcpUrl: string): Promise { + try { + const response = await io.fetchImpl(mcpUrl, { + method: 'POST', + headers: { + 'content-type': 'application/json', + accept: 'application/json, text/event-stream', + 'mcp-protocol-version': '2025-06-18', + }, + body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list', params: {} }), + signal: AbortSignal.timeout(15_000), + }); + const text = await response.text(); + const data = text.split('\n').find((line) => line.startsWith('data:')); + const parsed = JSON.parse(data ? data.slice(5) : text) as { result?: { tools?: { name?: string }[] } }; + return (parsed.result?.tools ?? []).some((tool) => tool.name === 'release_webhook_events'); + } catch { + return false; + } +} + /** Calls one tool on the inbox's MCP server (Streamable HTTP, JSON response). */ async function callTool( io: CliIo, @@ -266,9 +327,18 @@ its posts or sends a bearer token, the matching \`verified_urls\` entry once its ## 2. Get woken +One inbox wakes one session. \`watch_webhooks\` says \`wake: "linked"\` to every session that has this MCP server, so +it also names the Agent Relay agent the link wakes (\`linked_agent\`): compare it with your own agent name before +telling the person anything. If it is not you, posts go to that agent, not to this session: say so, and offer a +separate inbox for this session (or, if the person wants, \`link_relay_wake\` from this session, which moves the +link here). When you call \`link_relay_wake\`, pass \`agent\`: your own Agent Relay name. + **Claude Code after \`setup --claude\`: nothing to do.** Setup installed SessionStart and Stop hooks (\`async\`, -\`asyncRewake\`) that wait for the next post and wake this session with it, with or without Agent Relay. Do not poll, -and do not start a listener yourself; tell the person you are watching and end your turn. +\`asyncRewake\`) that wait for the next post and wake the session with it, with or without Agent Relay. They wake one +Claude Code session: the most recently started one, or the one that last called a \`${MCP_SERVER_NAME}\` tool (calling +\`watch_webhooks\` here makes it this one, from the end of this turn). While the inbox has a working relay wake link +(\`linked_agent\` set), no Claude Code session gets posts from the hooks. Do not poll, and do not start a listener +yourself; tell the person you are watching and end your turn. **Codex, Devin, Grok, opencode or Muse after \`setup\`: nothing to do.** Setup links the inbox to the newest open session of those tools through Agent Relay (Desktop's, or its own headless core when Desktop is not running), @@ -1255,7 +1325,8 @@ function chosenClis(io: CliIo, flags: Record): { clis: AgentCli[ } const WAKE_TEXT: Record = { - listener: 'each new session is woken by every post (wake hooks installed; no Agent Relay needed)', + listener: + 'its most recently started session is woken by every post (wake hooks installed; no Agent Relay needed)', core: 'its newest open session is woken by every post (through Agent Relay: Desktop, or its own headless core)', 'relay-only': 'woken by each post under Agent Relay; without it, reads posts when asked', 'when-asked': 'reads posts when asked (no background wake in this client)', @@ -1332,6 +1403,89 @@ async function workspaceFor( return { key, expiresAt }; } +/** The page that makes inboxes, for "make another one". */ +const INBOX_PAGE = 'https://agentrelay.com/mcp-events-shim'; + +/** Whether a CLI's sessions can be woken by an inbox's posts (a wake hook, or a link through the core). */ +function wakes(cli: AgentCli): boolean { + return Boolean(cli.hooks || cli.coreKind); +} + +/** Whether Claude Code's settings already run events-shim's wake hook (a setup before per-CLI inboxes). */ +function claudeHooked(io: CliIo): boolean { + return /@agent-relay\/events-shim@[^"]*listen --hook/.test(io.readText(claudeSettingsPath(io)) ?? ''); +} + +/** The files a turn-end CLI's wake hook is kept in (Droid: either of two). */ +const STOP_HOOK_FILES: Record string[]> = { + copilot: (io) => [copilotHooksPath(io)], + gemini: (io) => [geminiSettingsPath(io)], + droid: (io) => [join(factoryHome(io), 'hooks.json'), join(factoryHome(io), 'settings.json')], + cursor: (io) => [cursorHooksPath(io)], + amp: (io) => [ampPluginPath(io)], +}; + +/** Whether a turn-end CLI's wake hook is installed (a setup before per-CLI inboxes). */ +function stopHooked(io: CliIo, id: StopHookId): boolean { + return STOP_HOOK_FILES[id](io).some((path) => + (io.readText(path) ?? '').includes(`listen --stop-hook ${id}`) + ); +} + +/** + * The inbox each agent CLI used before this setup. A config saved before per-CLI inboxes has one + * inbox for all: the CLIs it is known to have set up (those linked through the core, and those whose + * wake hook is installed) keep it. + */ +function previousInboxes(io: CliIo, previous: Config | null): Record { + if (!previous) return {}; + if (previous.inboxes) return { ...previous.inboxes }; + const known = [ + ...(previous.wakeKinds ?? []).map(cliOfKind), + ...(claudeHooked(io) ? ['claude'] : []), + ...(Object.keys(STOP_HOOK_FILES) as StopHookId[]).filter((id) => stopHooked(io, id)), + ]; + return Object.fromEntries(known.map((id) => [id, previous.mcpUrl])); +} + +/** + * How the inbox picks the one session it wakes when several agent CLIs share it, for setup to say. + */ +function oneSessionLines(sharing: AgentCli[], linkedAgent: string | null): string[] { + const linking = sharing.filter((cli) => cli.coreKind); + const listening = sharing.filter((cli) => !cli.coreKind); + const lines = [ + sharing.length > 1 + ? `One inbox wakes one session, not one per agent. ${sharing.map((cli) => cli.label).join(', ')} share this inbox, so:` + : 'One inbox wakes one session, not one per agent:', + ]; + if (linking.length > 0) { + lines.push( + ` - Once a ${linking.map((cli) => cli.label).join(' or ')} session is open, the inbox is linked to the newest one (through Agent Relay) and it gets every post; a newer one takes the link over.${listening.length > 0 ? ` While that link works, ${listening.map((cli) => cli.label).join(', ')} sessions get none.` : ''}` + ); + } + if (linkedAgent && linking.length === 0) { + lines.push( + ` - The inbox is linked to the Agent Relay agent "${linkedAgent}" now: it gets every post, and ${listening.map((cli) => cli.label).join(', ')} sessions get none until that link is removed (unlink_relay_wake).` + ); + } + if (listening.some((cli) => cli.id === 'claude')) { + lines.push( + ` - ${linking.length > 0 || linkedAgent ? 'Otherwise, the' : 'The'} most recently started Claude Code session gets the posts; telling an older one "watch for webhooks" moves them to it.` + ); + } + const stopHooks = listening.filter((cli) => cli.id !== 'claude'); + if (stopHooks.length > 0) { + lines.push( + ` - ${stopHooks.map((cli) => cli.label).join(', ')}: each post goes to whichever waiting session takes it first.` + ); + } + lines.push( + `To wake each agent on its own, give each its own inbox: make another at ${INBOX_PAGE} and run setup with its MCP URL for just that agent (e.g. --${sharing[sharing.length - 1]!.id}).` + ); + return lines; +} + async function setup(io: CliIo, positional: string[], flags: Record): Promise { const raw = positional[0] ?? flags['mcp-url']; if (!raw) { @@ -1356,19 +1510,44 @@ async function setup(io: CliIo, positional: string[], flags: Record wakes(cli) && before[cli.id] !== mcpUrl); + const already = AGENT_CLIS.filter((cli) => wakes(cli) && !clis.includes(cli) && before[cli.id] === mcpUrl); + if (adding.length > 0 && (already.length > 0 || linkedElsewhere) && flags['share-inbox'] !== 'true') { + const holder = + already.length > 0 + ? already.map((cli) => cli.label).join(', ') + : linkedAgent + ? `the Agent Relay agent "${linkedAgent}"` + : 'another Agent Relay session'; + io.stderr( + [ + `This inbox already wakes ${holder}${linkedAgent && already.length > 0 ? ` (linked to the Agent Relay agent "${linkedAgent}")` : ''}. One inbox wakes one session, not one per agent: set up here too, ${adding.map((cli) => cli.label).join(', ')} would share its posts${linkedAgent !== null ? ' and get none while that link works' : ''}.`, + `Give ${adding.map((cli) => cli.label).join(', ')} its own inbox: make another at ${INBOX_PAGE} and run setup with its MCP URL${adding.length === 1 ? ` --${adding[0]!.id}` : ''}.`, + `To share this inbox anyway (one session at a time gets the posts), run setup again with --share-inbox.`, + ].join('\n') + ); + return 2; + } + // Codex is woken through an Agent Relay core: Desktop's, or a standalone one on its own workspace. + // Setting up another CLI (or another inbox) keeps the workspace an earlier \`setup --codex\` made. const throughCore = clis.filter((cli) => cli.coreKind); + const kept = previous?.workspaceKey + ? { + key: previous.workspaceKey, + ...(previous.workspaceExpiresAt ? { expiresAt: previous.workspaceExpiresAt } : {}), + } + : null; const workspace = - throughCore.length > 0 - ? await workspaceFor(io, mcpUrl, previous) - : previous?.mcpUrl === mcpUrl && previous.workspaceKey - ? { - key: previous.workspaceKey, - ...(previous.workspaceExpiresAt ? { expiresAt: previous.workspaceExpiresAt } : {}), - } - : null; + (throughCore.length > 0 ? await workspaceFor(io, mcpUrl, previous) : null) ?? + (kept && (!kept.expiresAt || Date.parse(kept.expiresAt) > Date.now()) ? kept : null); const config: Config = { mcpUrl, ...(workspace ? { workspaceKey: workspace.key } : {}), @@ -1378,11 +1557,11 @@ async function setup(io: CliIo, positional: string[], flags: Record [cli.id, mcpUrl])) }, ...(() => { - const kinds = new Set([ - ...(previous?.mcpUrl === mcpUrl ? (previous.wakeKinds ?? []) : []), - ...throughCore.map((cli) => cli.coreKind!), - ]); + // Kinds set up with another inbox stay linked to theirs (serve links each inbox apart). + const kinds = new Set([...(previous?.wakeKinds ?? []), ...throughCore.map((cli) => cli.coreKind!)]); return kinds.size > 0 ? { wakeKinds: [...kinds].sort() } : {}; })(), ...(typeof watched.webhook_url === 'string' ? { webhookUrl: watched.webhook_url } : {}), @@ -1427,8 +1606,16 @@ async function setup(io: CliIo, positional: string[], flags: Record wakes(cli) && config.inboxes?.[cli.id] === mcpUrl); if (hooked.includes('claude')) { - io.stdout('Start a new Claude Code session. Each post wakes it by itself; there is nothing to tell it.'); + io.stdout( + 'Start a new Claude Code session: each post wakes the most recently started Claude Code session by itself, with nothing to tell it. One session at a time: a newer session takes the posts over, and telling an older one "watch for webhooks" moves them back to it.' + ); + } + if (sharing.length > 1 || (linkedElsewhere && sharing.length > 0)) { + for (const line of oneSessionLines(sharing, linkedElsewhere ? linkedAgent || 'another session' : null)) + io.stdout(line); } const holding = clis.filter( (cli) => hooked.includes(cli.id) && cli.hooks?.listener.startsWith('--stop-hook') && !cli.heldBack?.(io) @@ -1527,22 +1714,38 @@ async function uninstall(io: CliIo, flags: Record): Promise (cli.coreKind ? [cli.coreKind] : []))); const config = readConfig(io); + if (config?.inboxes) { + // The removed CLIs' own inboxes are forgotten. + const inboxes = Object.fromEntries( + Object.entries(config.inboxes).filter(([id]) => !clis.some((cli) => cli.id === id)) + ); + const { inboxes: _all, ...rest } = config; + writePrivate( + configPath(io), + `${JSON.stringify(Object.keys(inboxes).length > 0 ? { ...rest, inboxes } : rest, null, 2)}\n` + ); + } if (removedKinds.size > 0 && config) { const left = (config.wakeKinds ?? []).filter((kind) => !removedKinds.has(kind)); - const { wakeKinds: _dropped, ...rest } = config; + const { wakeKinds: _dropped, ...rest } = readConfig(io) ?? config; writePrivate( configPath(io), `${JSON.stringify(left.length > 0 ? { ...rest, wakeKinds: left } : rest, null, 2)}\n` ); - if (left.length === 0) { - // The inbox stops forwarding to the session it was linked to (Desktop's core keeps running). + // Each inbox only the removed CLIs were linked through stops forwarding to the session it + // was linked to (Desktop's core keeps running). + const stillLinked = new Set(left.map((kind) => inboxOf(config, cliOfKind(kind)))); + for (const inbox of new Set([...removedKinds].map((kind) => inboxOf(config, cliOfKind(kind))))) { + if (stillLinked.has(inbox)) continue; try { - await callTool(io, config.mcpUrl, 'unlink_relay_wake'); + await callTool(io, inbox, 'unlink_relay_wake'); } catch { io.stdout( ' Could not unlink the inbox from its relay session; run unlink_relay_wake from an agent.' ); } + } + if (left.length === 0) { if (!io.userService.remove()) failed += 1; const lock = join(dirname(configPath(io)), 'serve.pid'); const pid = Number(io.readText(lock)?.trim()); @@ -1705,6 +1908,10 @@ async function settleClaim(io: CliIo, mcpUrl: string, how: 'ack' | 'release', cl * session is gone): the listener then acknowledges or releases the claim. * A batch without a lease is already read and must be kept. * + * \`owns\` turning false (another session took the inbox over, see + * \`claudeOwner\`) ends the listener like a closed session: a wait in flight + * is cut off (the inbox gives a leased batch back at once) and it exits. + * * @returns The exit code: \`deliver\`'s, or 0. */ async function listenAsSessionOwner( @@ -1715,7 +1922,8 @@ async function listenAsSessionOwner( deliver: (text: string, leased: boolean) => Promise, takeOver = false, takeHeld?: () => string | null, - drain: () => boolean = () => false + drain: () => boolean = () => false, + owns: () => boolean = () => true ): Promise { const dir = dirname(configPath(io)); const digest = (value: string) => createHash('sha256').update(value).digest('hex').slice(0, 16); @@ -1739,27 +1947,37 @@ async function listenAsSessionOwner( } try { let backoff = 1_000; + // Whether the inbox holds claims on a lease (it offers release_webhook_events); unknown reads as no. + let leased = false; + let leasesKnown = false; for (;;) { // While another session's listener owns the inbox, keep waiting to take over. while (!tryLock(io, inboxLock)) { - if (!alive()) return 0; + if (!alive() || !owns()) return 0; await io.sleep(3_000); } try { - while (alive() && io.readText(inboxLock)?.trim() === String(io.pid)) { + while (alive() && owns() && io.readText(inboxLock)?.trim() === String(io.pid)) { // A post an earlier owner claimed but could not hand over goes first. const kept = takeHeld?.(); if (kept) return (await deliver(kept, false)) ?? 0; // A relay wake link delivers every post to the session that linked it. Claiming one here // would take it from that session, so stand down. if (await relayWakeLinked(io, mcpUrl)) return 0; - // The session may have closed while that was asked: start no wait for it. - if (!alive()) return 0; + if (!leasesKnown) { + leased = await inboxLeases(io, mcpUrl); + leasesKnown = true; + } + // The session may have closed (or been taken over) while those were asked: start no wait for it. + if (!alive() || !owns()) return 0; const controller = new AbortController(); // While \`drain()\`, a wait in flight is not cut off: the inbox may already have handed it // posts, which \`deliver\` then lets go (leased) or keeps for the next owner. + // A takeover cuts the wait off only on an inbox with leases, which gives back a batch it + // claimed for a client that left. Without leases the inbox may already have marked a batch + // read, so the wait finishes and the check below keeps it for the next owner. const watch = setInterval(() => { - if (!alive() && !drain()) controller.abort(); + if ((!alive() && !drain()) || (!owns() && leased)) controller.abort(); }, 2_000); const signal = AbortSignal.any([controller.signal, AbortSignal.timeout(65_000)]); try { @@ -1774,16 +1992,21 @@ async function listenAsSessionOwner( const events = Array.isArray(batch.events) ? (batch.events as PublicEvent[]) : []; if (events.length > 0) { const claim = claimOf(batch, events); - const exit = await deliver( - [ - `Webhook inbox (agent-relay-webhooks): ${events.length === 1 ? 'a post arrived' : `${events.length} posts arrived`}.`, - '', - events.map(describePost).join('\n\n---\n\n'), - '', - 'Act on it as the person asked when they set up this webhook. You will be woken again by the next post.', - ].join('\n'), - claim !== null - ); + const text = [ + `Webhook inbox (agent-relay-webhooks): ${events.length === 1 ? 'a post arrived' : `${events.length} posts arrived`}.`, + '', + events.map(describePost).join('\n\n---\n\n'), + '', + 'Act on it as the person asked when they set up this webhook. You will be woken again by the next post.', + ].join('\n'); + // Taken over while the wait was in flight: the posts are the new owner's. A leased batch + // goes back to the inbox at once; one already marked read is kept for the next owner. + if (!owns()) { + if (claim) await settleClaim(io, mcpUrl, 'release', claim); + else keepForNextOwner(io, mcpUrl, text); + return 0; + } + const exit = await deliver(text, claim !== null); if (claim) await settleClaim(io, mcpUrl, exit === null ? 'release' : 'ack', claim); return exit ?? 0; } @@ -1793,7 +2016,7 @@ async function listenAsSessionOwner( backoff = Math.min(backoff * 2, 30_000); } } - if (!alive()) return 0; + if (!alive() || !owns()) return 0; } finally { unlock(io, inboxLock); } @@ -1811,25 +2034,39 @@ async function listenAsSessionOwner( async function relayWakeLinked(io: CliIo, mcpUrl: string): Promise { try { const state = await callTool(io, mcpUrl, 'watch_webhooks', {}, AbortSignal.timeout(15_000)); - return state.wake === 'linked'; + if (state.wake !== 'linked') return false; + const agent = typeof state.linked_agent === 'string' ? `"${state.linked_agent}"` : 'another session'; + io.appendLog( + `${new Date().toISOString()} listen: standing down; the inbox's relay wake link delivers every post to ${agent}` + ); + return true; } catch { return false; } } /** The hook's JSON input on stdin (Claude Code and Codex both send \`session_id\`). */ -async function hookInput(io: CliIo): Promise<{ session: string; transcript: string }> { +interface HookInput { + session: string; + transcript: string; + /** \`hook_event_name\`: \`SessionStart\`, \`Stop\`, … */ + event: string; + /** SessionStart's \`source\`: \`startup\`, \`resume\`, \`clear\` or \`compact\`. */ + source: string; +} + +async function hookInput(io: CliIo): Promise { + const text = (value: unknown) => (typeof value === 'string' ? value : ''); try { - const input = JSON.parse((await io.readStdin()) || '{}') as { - session_id?: unknown; - transcript_path?: unknown; - }; + const input = JSON.parse((await io.readStdin()) || '{}') as Record; return { - session: typeof input.session_id === 'string' ? input.session_id : '', - transcript: typeof input.transcript_path === 'string' ? input.transcript_path : '', + session: text(input.session_id), + transcript: text(input.transcript_path), + event: text(input.hook_event_name), + source: text(input.source), }; } catch { - return { session: '', transcript: '' }; + return { session: '', transcript: '', event: '', source: '' }; } } @@ -1860,26 +2097,24 @@ function callsWebhooksTool(line: string): boolean { } /** - * Whether this Claude Code session asked for webhook posts: its transcript shows an assistant - * \`tool_use\` of one of the webhooks MCP tools (the skill starts with \`watch_webhooks\`). - * \`setup --claude\` installs the wake hooks for every session on the machine, but all of them - * share one inbox, so a session that never opted in would otherwise take posts meant for another. - * The transcript is read in chunks, whole lines only, from where the last check stopped (kept in a - * per-session file), so a long transcript is read once in all, not once per turn; the answer is - * remembered once seen. + * Whether this Claude Code session called one of the webhooks MCP tools since the last check: its + * transcript shows an assistant \`tool_use\` of one (the skill starts with \`watch_webhooks\`). Such + * a call takes the inbox over for the session, the explicit way to move the posts to it (a newer + * session takes them by starting). The transcript is read in chunks, whole lines only, from where + * the last check stopped (kept in a per-session file), so a long transcript is read once in all, + * not once per turn. */ -function sessionOptedIn(io: CliIo, mcpUrl: string, session: string, transcript: string): boolean { +function newWebhooksCall(io: CliIo, mcpUrl: string, session: string, transcript: string): boolean { if (!session || !transcript) return false; const digest = createHash('sha256').update(`${mcpUrl}\n${session}`).digest('hex').slice(0, 16); - const marker = join(dirname(configPath(io)), `optin-${digest}`); - if (io.exists(marker)) return true; - const progress = `${marker}.scanned`; + const progress = join(dirname(configPath(io)), `scanned-${digest}`); const saved = Number(io.readText(progress)?.trim()); // \`offset\`: where the first line not yet checked starts; \`carry\`: that line so far, when it is // longer than one read. let offset = Number.isSafeInteger(saved) && saved > 0 ? saved : 0; let position = offset; let carry = ''; + let called = false; for (;;) { const chunk = io.readFrom(transcript, position); if (!chunk || chunk.end <= position) break; @@ -1897,18 +2132,62 @@ function sessionOptedIn(io: CliIo, mcpUrl: string, session: string, transcript: // Everything up to the chunk's last newline is whole lines; only the bytes after it can end // inside a character, so this offset is exact. const head = chunk.text.slice(0, cut + 1); - if ((carry + head).split('\n').some(callsWebhooksTool)) { - writePrivate(marker, `${session}\n`); - rmSync(progress, { force: true }); - return true; - } + if ((carry + head).split('\n').some(callsWebhooksTool)) called = true; offset = position + Buffer.byteLength(head, 'utf8'); position = offset; carry = ''; } // A line still being written is read again next time, from its start. if (offset > 0) writePrivate(progress, `${offset}\n`); - return false; + return called; +} + +/** The Claude Code session whose wake hook takes this inbox's posts. */ +interface ClaudeOwner { + session: string; + /** Its \`claude\` process, to tell when the session closed. */ + pid: number | null; +} + +/** + * The per-inbox record of which Claude Code session takes its posts. \`setup --claude\` installs the + * wake hooks for every Claude Code session on the machine; all of them share one inbox, which wakes + * one session. The most recently started session takes the inbox over (its SessionStart hook + * writes itself here), and so does a session that calls a webhooks MCP tool; every other session's + * listener yields. A record whose session closed is vacant: the next hook to run takes it. + */ +function claudeOwnerPath(io: CliIo, mcpUrl: string): string { + const digest = createHash('sha256').update(mcpUrl).digest('hex').slice(0, 16); + return join(dirname(configPath(io)), `claude-owner-${digest}.json`); +} + +function readClaudeOwner(io: CliIo, mcpUrl: string): ClaudeOwner | null { + try { + const parsed = JSON.parse( + io.readText(claudeOwnerPath(io, mcpUrl)) ?? 'null' + ) as Partial | null; + if (!parsed || typeof parsed.session !== 'string' || !parsed.session) return null; + return { session: parsed.session, pid: typeof parsed.pid === 'number' ? parsed.pid : null }; + } catch { + return null; + } +} + +/** Makes \`session\` the inbox's Claude Code owner (an atomic replace: the last writer wins). */ +function writeClaudeOwner(io: CliIo, mcpUrl: string, owner: ClaudeOwner): void { + const path = claudeOwnerPath(io, mcpUrl); + mkdirSync(dirname(path), { recursive: true, mode: 0o700 }); + const temporary = `${path}.${io.pid}.tmp`; + writeFileSync(temporary, `${JSON.stringify({ ...owner, at: new Date().toISOString() })}\n`, { + mode: 0o600, + }); + renameSync(temporary, path); +} + +/** Whether a Claude Code process runs non-interactively (\`claude -p\`), so starting it takes nothing over. */ +function printMode(io: CliIo, pid: number | null): boolean { + if (pid === null) return false; + return /(^|\s)(-p|--print)(\s|=|$)/.test(io.processArgs(pid) ?? ''); } /** @@ -1916,25 +2195,45 @@ function sessionOptedIn(io: CliIo, mcpUrl: string, session: string, transcript: * \`async\` and \`asyncRewake\`. It waits for the next post and exits 2 with * it on stderr, which Claude Code shows the agent, waking an idle session. * Each turn's Stop hook starts it again. + * + * Only the inbox's owner session listens (see \`claudeOwnerPath\`): a session + * takes the inbox over when it starts (not a \`claude -p\` run, and not a + * compaction), when it calls a webhooks MCP tool, or when the owner's session + * has closed. An older session's listener stops as soon as a newer one takes + * over, so posts never go to more than one session. */ async function listenHook(io: CliIo, flags: Record): Promise { - const mcpUrl = mcpUrlFor(io, flags); + const mcpUrl = mcpUrlFor(io, flags, 'claude'); if (!mcpUrl) return 0; - const { session, transcript } = await hookInput(io); - // Only a session that asked to watch the inbox listens on it. - if (!sessionOptedIn(io, mcpUrl, session, transcript)) return 0; + const { session, transcript, event, source } = await hookInput(io); + if (!session) return 0; const claude = io.ancestor('claude'); + // A non-interactive run (\`claude -p\`) never takes the inbox by itself: only by calling a tool. + const interactive = !printMode(io, claude); + const started = event === 'SessionStart' && source !== 'compact' && interactive; + // Scanned on every run, so a call is noticed once, in the turn that made it. + const called = newWebhooksCall(io, mcpUrl, session, transcript); + const owner = readClaudeOwner(io, mcpUrl); + const vacant = interactive && (!owner || (owner.pid !== null && !io.pidAlive(owner.pid))); + if (started || called || vacant) { + writeClaudeOwner(io, mcpUrl, { session, pid: claude }); + } else if (owner?.session !== session) { + return 0; // another, newer session takes this inbox's posts + } + const owns = () => readClaudeOwner(io, mcpUrl)?.session === session; return listenAsSessionOwner( io, mcpUrl, - session || String(claude ?? 'machine'), + session, () => claude === null || io.pidAlive(claude), async (text) => { io.stderr(text); return 2; }, false, - () => takeHeldPost(io, mcpUrl) + () => takeHeldPost(io, mcpUrl), + () => false, + owns ); } @@ -1947,18 +2246,28 @@ function heldPostPath(io: CliIo, mcpUrl: string): string { return join(dirname(configPath(io)), `held-${digest}.txt`); } +/** Keeps a post already marked read for the inbox's next owner, after any kept before it. */ +function keepForNextOwner(io: CliIo, mcpUrl: string, text: string): void { + const held = heldPostPath(io, mcpUrl); + const before = io.readText(held); + writePrivate(held, before ? `${before}\n\n---\n\n${text}` : text); +} + /** Takes the kept post, if any: one owner gets it (an atomic rename). */ function takeHeldPost(io: CliIo, mcpUrl: string): string | null { - const held = heldPostPath(io, mcpUrl); - const mine = `${held}.${io.pid}`; - try { - renameSync(held, mine); - } catch { - return null; + // A release before inbox URLs were canonical may have kept one under the \`…/mcp/\` form's name. + for (const held of [heldPostPath(io, mcpUrl), heldPostPath(io, `${mcpUrl}/`)]) { + const mine = `${held}.${io.pid}`; + try { + renameSync(held, mine); + } catch { + continue; + } + const kept = io.readText(mine); + rmSync(mine, { force: true }); + return kept; } - const kept = io.readText(mine); - rmSync(mine, { force: true }); - return kept; + return null; } /** The agent CLIs whose turn-end hook can hold a finished turn open and hand it the next post. */ @@ -2192,7 +2501,7 @@ function transcriptWatch(io: CliIo, path: string, released: RegExp, since: numbe async function listenStopHook(io: CliIo, flags: Record): Promise { const id = flags['stop-hook'] as StopHookId; const cli = STOP_HOOK_CLIS[id]; - const mcpUrl = mcpUrlFor(io, flags); + const mcpUrl = mcpUrlFor(io, flags, id); let input: Record = {}; try { const parsed = JSON.parse((await io.readStdin()) || '{}') as unknown; @@ -2448,7 +2757,7 @@ async function linkSession(io: CliIo, flags: Record): Promise): Promise void ): Promise { @@ -2489,7 +2798,8 @@ async function linkAgent( ); } try { - await callTool(io, config.mcpUrl, 'link_relay_wake', { url: hook.url, secret: hook.secret }); + // Named, so every session reading the inbox's wake state learns which one it wakes. + await callTool(io, mcpUrl, 'link_relay_wake', { url: hook.url, secret: hook.secret, agent: name }); } catch (error) { log(`link_relay_wake failed: ${error instanceof Error ? error.message : 'error'}`); return false; @@ -2526,8 +2836,8 @@ async function serve(io: CliIo, flags: Record): Promise // The order sessions were first seen open in: the newest open one gets the posts. const opened = new Map(); let counter = 0; - let linked: string | null = null; - let inbox: string | null = null; + // The session each inbox is linked to (CLIs set up with different inboxes are linked apart). + const linked = new Map(); // A link that failed is tried again, but not on every pass. const retryAt = new Map(); try { @@ -2535,12 +2845,13 @@ async function serve(io: CliIo, flags: Record): Promise const config = readConfig(io); const kinds = new Set(config?.wakeKinds ?? []); if (!config || kinds.size === 0) return 0; - // Another inbox: link it afresh. - if (config.mcpUrl !== inbox) { - inbox = config.mcpUrl; - linked = null; - retryAt.clear(); + const byInbox = new Map>(); + for (const kind of kinds) { + const inbox = inboxOf(config, cliOfKind(kind)); + byInbox.set(inbox, new Set([...(byInbox.get(inbox) ?? []), kind])); } + // An inbox no CLI uses any more is forgotten; a new one is linked afresh. + for (const inbox of [...linked.keys()]) if (!byInbox.has(inbox)) linked.delete(inbox); const log = (line: string) => io.appendLog(`${new Date().toISOString()} serve: ${line}`); const problem = await ensureCore(io, config); if (problem) { @@ -2558,19 +2869,24 @@ async function serve(io: CliIo, flags: Record): Promise for (const session of [...live].sort((a, b) => (a.updated_at_ms ?? 0) - (b.updated_at_ms ?? 0))) { if (!opened.has(session.target!.id!)) opened.set(session.target!.id!, (counter += 1)); } - const pick = live.reduce( - (best, session) => - !best || opened.get(session.target!.id!)! > opened.get(best.target!.id!)! ? session : best, - null - ); - const id = pick?.target?.id ?? null; - if (!id) linked = null; - else if (id !== linked && (retryAt.get(id) ?? 0) <= Date.now()) { - if (await linkAgent(io, config, pick!.registration!.name!, log)) { - linked = id; - retryAt.delete(id); - } else { - retryAt.set(id, Date.now() + 60_000); + for (const [inbox, inboxKinds] of byInbox) { + const pick = live + .filter((session) => inboxKinds.has(session.target!.kind!)) + .reduce( + (best, session) => + !best || opened.get(session.target!.id!)! > opened.get(best.target!.id!)! ? session : best, + null + ); + const id = pick?.target?.id ?? null; + const retryKey = `${inbox}\n${id}`; + if (!id) linked.delete(inbox); + else if (id !== linked.get(inbox) && (retryAt.get(retryKey) ?? 0) <= Date.now()) { + if (await linkAgent(io, inbox, pick!.registration!.name!, log)) { + linked.set(inbox, id); + retryAt.delete(retryKey); + } else { + retryAt.set(retryKey, Date.now() + 60_000); + } } } } diff --git a/packages/events-shim/src/events-shim.test.ts b/packages/events-shim/src/events-shim.test.ts index 802836ce0..6e69a8998 100644 --- a/packages/events-shim/src/events-shim.test.ts +++ b/packages/events-shim/src/events-shim.test.ts @@ -368,6 +368,46 @@ describe('events shim', () => { expect(feed.events.map((event) => event.delivery)).toEqual(['woken', 'woken']); }); + it("names the agent a relay wake link wakes, so a session cannot take another one's link for its own", async () => { + const h = createHarness(); + const shim = await h.create(); + const codex = await h.connect(shim.mcp_url); + const linked = await codex.call('link_relay_wake', { ...RELAY_HOOK, agent: 'codex-session-1' }); + expect(linked.structuredContent).toMatchObject({ wake: 'linked', linked_agent: 'codex-session-1' }); + + // Another session with the same MCP server (a Claude Code session, say) reads the wake state. + const claude = await h.connect(shim.mcp_url); + const watched = (await claude.call('watch_webhooks')).structuredContent as Record; + expect(watched).toMatchObject({ wake: 'linked', linked_agent: 'codex-session-1' }); + const steps = (watched.next_steps as string[]).join('\n'); + expect(steps).toContain('linked to the Agent Relay agent "codex-session-1"'); + expect(steps).toContain('Compare "codex-session-1" with your own Agent Relay agent name'); + expect(steps).not.toContain('injected into this session'); + expect((await h.feed(shim.manage_token)).body.agent.wake_agent).toBe('codex-session-1'); + + // Linking another session moves the link and says which one stops getting posts. + const moved = await claude.call('link_relay_wake', { + url: `${RELAY}/v1/hooks/wh_new`, + secret: RELAY_HOOK.secret, + agent: 'claude-session-2', + }); + expect(moved.structuredContent).toMatchObject({ + linked_agent: 'claude-session-2', + replaced_agent: 'codex-session-1', + }); + expect((moved.structuredContent!.next_steps as string[]).join('\n')).toContain( + 'The inbox no longer wakes "codex-session-1"' + ); + + // A link made without a name (an older client) is never presented as the reader's own. + await claude.call('link_relay_wake', RELAY_HOOK); + const unnamed = (await codex.call('watch_webhooks')).structuredContent as Record; + expect(unnamed).toMatchObject({ wake: 'linked', linked_agent: null }); + expect((unnamed.next_steps as string[]).join('\n')).toContain( + 'Unless you called link_relay_wake yourself in this conversation, assume the link wakes another session' + ); + }); + it('does not let a late failure from an old link break the new link', async () => { const h = createHarness(); const shim = await h.create(); diff --git a/packages/events-shim/src/mcp.ts b/packages/events-shim/src/mcp.ts index 191d0a0c3..f2a448800 100644 --- a/packages/events-shim/src/mcp.ts +++ b/packages/events-shim/src/mcp.ts @@ -3,7 +3,7 @@ import { z } from 'zod'; import { EVENTS_SHIM_LIMITS } from './limits.js'; import { drainStalledWakes, publicEvent, type EventsShimDeps } from './service.js'; -import type { EventsShimStore, ShimEvent, ShimRecord, ShimUrls } from './types.js'; +import type { EventsShimStore, ShimEvent, ShimRecord, ShimUrls, WakeTarget } from './types.js'; import { deliverInBackground, deliverPending } from './delivery.js'; import { checkWakeTarget, DEFAULT_RELAY_ORIGINS, forwardWake } from './wake.js'; @@ -82,6 +82,25 @@ function wakeState(shim: ShimRecord): 'linked' | 'broken' | 'none' { return shim.wake.brokenAt ? 'broken' : 'linked'; } +/** + * Which session a working relay wake link delivers to, for the agent reading it. One inbox wakes + * one session, and every session that has this MCP server sees the same `wake: linked`, so the + * text names the link's agent and tells the reader to compare it with its own name instead of + * taking the link for its own. + */ +function linkedTo(wake: WakeTarget): string[] { + const who = wake.agent; + return who + ? [ + `This inbox is linked to the Agent Relay agent "${who}" (since ${wake.linkedAt}): each post is injected into that agent's session and wakes it. One inbox wakes one session, and while this link works no other session (Claude Code's wake hooks, listen, wait_for_webhook) receives its posts.`, + `Compare "${who}" with your own Agent Relay agent name. If it is not yours, the posts do not come to this session: tell the person the inbox wakes "${who}", not this session. To get them here instead, either use a separate inbox for this session, or call link_relay_wake from this session, which moves the link away from "${who}".`, + ] + : [ + `This inbox is linked to an Agent Relay session (since ${wake.linkedAt}) whose agent name was not recorded: each post is injected into that session and wakes it. One inbox wakes one session, and while this link works no other session (Claude Code's wake hooks, listen, wait_for_webhook) receives its posts.`, + 'Unless you called link_relay_wake yourself in this conversation, assume the link wakes another session, not this one, and tell the person so. To get the posts here instead, either use a separate inbox for this session, or call link_relay_wake from this session (with agent: your Agent Relay name), which moves the link here.', + ]; +} + /** * Whether the store holds `wait_for_webhook` claims on a lease (it implements * the optional `ackPending` and `releasePending`). Without, a claim marks posts @@ -142,7 +161,7 @@ export function registerEventsShimTools(server: McpServer, ctx: EventsShimMcpCon { title: 'Watch for webhooks', description: - "Start here. Returns this inbox's webhook URL, whether posts will wake this session, posts waiting for you, and the exact next steps to get woken when a post arrives.", + "Start here. Returns this inbox's webhook URL, whether a relay wake link delivers its posts and to which Agent Relay agent (linked_agent: compare it with your own name, since one inbox wakes one session), posts waiting for you, and the exact next steps to get woken when a post arrives.", inputSchema: {}, annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false }, }, @@ -157,9 +176,9 @@ export function registerEventsShimTools(server: McpServer, ctx: EventsShimMcpCon const nextSteps = state === 'linked' ? [ - 'You are set: each post is injected into this session by Agent Relay and wakes it when idle.', + ...linkedTo(ctx.shim.wake!), 'Give the person (or whoever sends the webhooks) webhook_url: anyone holding it can post. For a sender that signs its posts (GitHub, Stripe, Linear) or sends a bearer token, use the matching verified_urls entry instead, once its secret is set on the page that created this inbox (until then that URL refuses posts with 409).', - 'Tell the person you are watching, then end your turn. Do not poll.', + 'If the link is yours, tell the person you are watching, then end your turn. Do not poll.', ] : [ ...(state === 'broken' @@ -170,7 +189,7 @@ export function registerEventsShimTools(server: McpServer, ctx: EventsShimMcpCon 'Give the person (or whoever sends the webhooks) webhook_url: anyone holding it can post. For a sender that signs its posts (GitHub, Stripe, Linear) or sends a bearer token, use the matching verified_urls entry instead, once its secret is set on the page that created this inbox.', `If this session runs under Agent Relay (it has a relay socket, e.g. a SessionStart hook named agent-relay-probe or messages with a [reply: …] hint), make your session's relay webhook: run \`${RELAY_WEBHOOK_COMMAND}\` with the socket path you were given. It prints a url and a secret.`, "If the probe answers that it has no webhook command (an older Agent Relay), run `agent-relay-probe socket-request --socket --method POST --path /webhooks --body '{}'` instead; the url and secret are under data.", - 'Then call link_relay_wake with that url and secret. If the probe printed created:false and no secret, the session already has a webhook whose secret was shown earlier: delete it (add --revoke, or the older probe: --method DELETE --path /webhooks), make it again, and use the new secret.', + 'Then call link_relay_wake with that url, that secret and agent: your own Agent Relay agent name (so the inbox can say which session it wakes). If the probe printed created:false and no secret, the session already has a webhook whose secret was shown earlier: delete it (add --revoke, or the older probe: --method DELETE --path /webhooks), make it again, and use the new secret.', 'Without Agent Relay, in Claude Code: start `npx -y @agent-relay/events-shim@latest listen` as a background command (Bash with run_in_background). It exits with the next post, which wakes you; act on it, then start it again. It needs this inbox saved first: the person runs `npx @agent-relay/events-shim@latest setup ` once (it also installs a skill with these steps), or pass `--mcp-url ` to listen.', 'Other clients without Agent Relay: call wait_for_webhook in a background task if you can, and call it again each time it returns; otherwise call get_webhook_events when the person asks. Codex wakes only under Agent Relay.', 'Then tell the person you are watching.', @@ -184,6 +203,10 @@ export function registerEventsShimTools(server: McpServer, ctx: EventsShimMcpCon bearer: ctx.urls.hookUrl(ctx.shim.hookToken, 'bearer'), }, wake: state, + // Which session the link wakes: only that agent's session gets the posts. + ...(ctx.shim.wake + ? { linked_agent: ctx.shim.wake.agent ?? null, linked_at: ctx.shim.wake.linkedAt } + : {}), waiting, next_steps: nextSteps, limits: { @@ -199,7 +222,7 @@ export function registerEventsShimTools(server: McpServer, ctx: EventsShimMcpCon 'link_relay_wake', { title: 'Wake this session through Agent Relay', - description: `Links this inbox to the webhook your local Agent Relay made for this session (run \`${RELAY_WEBHOOK_COMMAND}\` first; an older probe without that command: \`agent-relay-probe socket-request --socket --method POST --path /webhooks --body '{}'\`). Every later post is forwarded there, and Agent Relay injects it into this session, waking it even when idle. Posts already waiting are forwarded too.`, + description: `Links this inbox to the webhook your local Agent Relay made for this session (run \`${RELAY_WEBHOOK_COMMAND}\` first; an older probe without that command: \`agent-relay-probe socket-request --socket --method POST --path /webhooks --body '{}'\`). Every later post is forwarded there, and Agent Relay injects it into this session, waking it even when idle. Posts already waiting are forwarded too. One inbox wakes one session: this replaces any link the inbox had to another session. Pass agent (your own Agent Relay name) so watch_webhooks can tell every session which one the inbox wakes.`, inputSchema: { url: z .string() @@ -213,6 +236,15 @@ export function registerEventsShimTools(server: McpServer, ctx: EventsShimMcpCon .min(1) .max(200) .describe('The wh_live_… secret your relay printed (shown once).'), + agent: z + .string() + .trim() + .min(1) + .max(100) + .optional() + .describe( + "Your own Agent Relay agent name (this session's name on the relay). Recorded so watch_webhooks can say which session the inbox wakes." + ), }, annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true }, }, @@ -220,7 +252,14 @@ export function registerEventsShimTools(server: McpServer, ctx: EventsShimMcpCon const checked = checkWakeTarget(input.url, input.secret, relayOrigins); if (!checked.ok) return failure(checked.message); const at = now(ctx).toISOString(); - const target = { url: checked.url, secret: input.secret, linkedAt: at }; + // The session the inbox woke until now, if another: said in the answer, so the move is visible. + const before = ctx.shim.wake && !ctx.shim.wake.brokenAt ? ctx.shim.wake : undefined; + const target: WakeTarget = { + url: checked.url, + secret: input.secret, + linkedAt: at, + ...(input.agent ? { agent: input.agent } : {}), + }; // Prove the link before storing it: a test post the session will see. const probe = await forwardWake({ url: target.url, @@ -259,19 +298,33 @@ export function registerEventsShimTools(server: McpServer, ctx: EventsShimMcpCon // Keep retrying in the background; the agent can also read them now. void deliverInBackground(ctx.deps, ctx.shim.id, target, undefined, Promise.resolve(pass)); } + const moved = + before && before.url !== target.url + ? [ + `The inbox no longer wakes ${before.agent ? `"${before.agent}"` : 'the session it was linked to before'}: one inbox wakes one session, and that session gets no more posts from it.`, + ] + : []; + const named = { + linked_agent: target.agent ?? null, + ...(before && before.url !== target.url ? { replaced_agent: before.agent ?? null } : {}), + }; if (pass.stalled) { return result({ wake: pass.stalled.permanent ? 'broken' : 'linked', + ...named, forwarded_waiting: forwarded, next_steps: [ `Linked, but some waiting posts could not be forwarded yet (${pass.stalled.reason}). Call get_webhook_events to read them now.`, + ...moved, ], }); } return result({ wake: 'linked', + ...named, forwarded_waiting: forwarded, next_steps: [ + ...moved, 'Tell the person you are watching, then end your turn. Each post arrives in this session as a message from webhook.', ], }); diff --git a/packages/events-shim/src/service.ts b/packages/events-shim/src/service.ts index db0e8a9ad..f3b7c2b48 100644 --- a/packages/events-shim/src/service.ts +++ b/packages/events-shim/src/service.ts @@ -271,6 +271,8 @@ export async function feedFor( last_seen_at: shim.agentSeenAt ?? null, wake: shim.wake ? (shim.wake.brokenAt ? 'broken' : 'linked') : 'none', wake_error: shim.wake?.brokenReason ?? null, + /** The Agent Relay agent the wake link delivers to, when the link named one. */ + wake_agent: shim.wake?.agent ?? null, }, expires_at: new Date(Date.parse(shim.lastUsedAt) + EVENTS_SHIM_LIMITS.idleExpiryMs).toISOString(), events: events.map(publicEvent), diff --git a/packages/events-shim/src/types.ts b/packages/events-shim/src/types.ts index 26064b33e..da572f048 100644 --- a/packages/events-shim/src/types.ts +++ b/packages/events-shim/src/types.ts @@ -25,6 +25,12 @@ export interface WakeTarget { /** The `wh_live_…` bearer Relaycast showed once. Hosts store it encrypted. */ secret: string; linkedAt: string; + /** + * The Agent Relay agent name of the session the link wakes, as the linker gave it + * (`link_relay_wake`'s `agent`). Tools report it so an agent can tell whether the link is its + * own. Hosts that do not store it report the link without a name. + */ + agent?: string; /** Set when the last forward was refused for good (revoked or deleted hook). */ brokenAt?: string; brokenReason?: string;