diff --git a/AGENTS.md b/AGENTS.md index 8a684ba..dc2a42c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -7,6 +7,7 @@ | `src/cli.ts` | Entry. Core commands, then adapter commands from the registry | | `src/install.ts` | Links `agent-bridge`, then runs each adapter's install or uninstall | | `src/paths.ts` | State locations (`~/.agent-bridge`) and `ensureHome` | +| `src/config.ts` | Opt-in user preferences (`~/.agent-bridge/config.json`: auto-join and folder ignore list) | | `src/schema.ts` | Zod schemas for every boundary: socket requests and replies, messages, peers | | `src/names.ts` | Auto peer names: `-` base, next free suffix. Pure | | `src/format.ts` | Send results, shared by the tools and the CLI. Agent-specific wording lives in the adapter (`agy/format.ts`) | @@ -22,7 +23,7 @@ | `src/lib/` | Generic helpers, no bridge logic: `errors` (errno codes, `toError`, `isDaemonDown`), `json-file` (validated read, atomic write, `readJsonDir`), `log` (tagged stderr), `wire` (JSON lines), `args`, `config` (other tools' config and PATH links), `rate` (token bucket), `tty` (ask on a terminal; undefined without one) | | `src/adapters/types.ts` | The `Adapter` interface every agent kind implements | | `src/adapters/index.ts` | `ADAPTERS` registry, typed `Record` | -| `src/adapters//` | Everything agent-specific. `index.ts` exports the adapter and is the folder's only entry point. The rest is split by concern: `mcp.ts`, `install.ts`, `names.ts` (constants), and the wake path (`agy/push.ts`, `agy/listen.ts`, `agy/hook.ts`, `agy/format.ts`, `claude/socket.ts`, `claude/monitor.ts`, `claude/format.ts`, `claude/channel/`) | +| `src/adapters//` | Everything agent-specific. `index.ts` exports the adapter and is the folder's only entry point. The rest is split by concern: `mcp.ts`, `install.ts`, `names.ts` (constants), and the wake path (`agy/push.ts`, `agy/listen.ts`, `agy/hook.ts`, `agy/format.ts`, `claude/socket.ts`, `claude/session.ts`, `claude/monitor.ts`, `claude/format.ts`, `claude/channel/`) | | `src/adapters/agy/skill/` | The Antigravity `/bridge` skill, copied by install | | `src/adapters/opencode/plugin/` | The opencode plugin. Standalone (node built-ins only): install copies the built file into opencode's plugins folder | | `src/adapters/claude/plugin/` | The Claude plugin: `/bridge` (socket) and `/bridge-monitor` skills sharing `shared/peer-messages.md`, the monitor, and the bypass-guard hook. Registered by install through the repo's `.claude-plugin/marketplace.json` | diff --git a/README.md b/README.md index 4e02423..0e768dc 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ agent-bridge install # once per machine, and again after each updat From source: `git clone https://github.com/logickoder/agent-bridge.git`, then `pnpm install && pnpm build && node dist/cli.js install`. -Then join from each session: `/bridge` in Claude Code or Antigravity, or ask opencode to join the bridge. Without a name you get `-` (e.g. `myapp-claude`); `/bridge planner` picks one. Ask any session to message another by name. `/bridge ` renames, `/bridge off` leaves. `agent-bridge uninstall` removes everything. +Then join from each session: `/bridge` in Claude Code or Antigravity, or ask opencode to join the bridge. Or run `agent-bridge auto-join on` once to join live sessions automatically (with `auto-join ignore [folder]` to skip noisy folders; see [docs/install.md](docs/install.md#auto-join)). Without a name you get `-` (e.g. `myapp-claude`); `/bridge planner` picks one. Ask any session to message another by name. `/bridge ` renames, `/bridge off` leaves. `agent-bridge uninstall` removes everything. Requires Node 22+ (and pnpm to build from source). @@ -56,13 +56,14 @@ Delivery is at least once: a message leaves the queue only when it is acked. Sen | `agent-bridge send [--as me] ` | Send. Without `--as`, the sender is `shell`, unverified. Pass `-` as the text to read it from stdin | | `agent-bridge send [--as me] --to-kind ` | Send to the one online peer of that kind that joined from this folder. Refuses if there are none or several | | `agent-bridge marker` | A random heredoc end marker, for agents sending with `send ... - <<''` | -| `agent-bridge leave ` | Unbind a peer and stop its listeners | +| `agent-bridge leave [name \| --session id]` | Unbind a peer and stop its listeners (no arg: this session) | +| `agent-bridge auto-join [on\|off\|ignore\|unignore]` | Auto-join live sessions to the local bridge, with an optional folder ignore list ([docs/install.md](docs/install.md#auto-join)) | | `agent-bridge status` | Everything, as JSON. Session ids show as tags | | `agent-bridge restart` | Stop the daemon. The next client starts it | | `agent-bridge claude [--as name] [claude args]` | Launch Claude Code with a channel instead of the socket | | `agent-bridge net ` | Networks across machines: `host`, `invite`, `connect`, `status`, `fingerprint`, `verify`, `trust`, `allow`, `share`, `kick`, `set-url`, `leave`, `stop`. `agent-bridge net` lists them | -Agent-side commands, called by skills, hooks and plugins: `listen`, `agy-hook`, `monitor`, `claude-guard`, `opencode-stream`, `mcp `, `daemon`. `agent-bridge` with no arguments lists them all. +Agent-side commands, called by skills, hooks and plugins: `listen`, `agy-hook`, `agy-session-start`, `monitor`, `claude-guard`, `claude-session-start`, `claude-session-end`, `opencode-stream`, `mcp `, `daemon`. `agent-bridge` with no arguments lists them all. ## Development diff --git a/docs/agents/antigravity.md b/docs/agents/antigravity.md index e0ed8a0..950f093 100644 --- a/docs/agents/antigravity.md +++ b/docs/agents/antigravity.md @@ -27,3 +27,4 @@ Endpoints live in daemon memory, and hooks never see the token (finding 9). Afte 9. **Hooks do not get the address or token.** A probe hook saw only `ANTIGRAVITY_CONVERSATION_ID`, so only `join` can register direct delivery. 10. **The endpoint dies when Antigravity restarts.** After `agy --continue` (same conversation id) `send-message` failed with exit 1. 11. **Antigravity asks before answering another user's agent at all.** Over a network (2026-11-19), it read the caution and asked its user before replying even to "what is 17 times 23?", where Claude Code replied on its own. Safe, but each remote exchange needs the user once. +12. **`SessionStart` and no `SessionEnd`.** `hooks.json` supports `SessionStart` (`conversationId`, `cwd`, `workspacePaths` on stdin; `injectSteps` on stdout), which `agy-session-start` uses when auto-join is enabled to ask `agy` to run `join --kind agy` on the first turn (hooks still lack the agentapi address and token, finding 9). Antigravity has no `SessionEnd` hook; the daemon probes `ANTIGRAVITY_LS_ADDRESS` (`localhost:`) with a loopback TCP connect on demand to drop exited CLI sessions (each CLI session runs its own LS port; in the IDE/desktop app where one LS serves multiple conversations, the port stays open until the LS exits). diff --git a/docs/agents/claude-code.md b/docs/agents/claude-code.md index 808746f..47c9f39 100644 --- a/docs/agents/claude-code.md +++ b/docs/agents/claude-code.md @@ -43,3 +43,4 @@ Do not register the channel server at user scope. Claude does not tell a server 10. **`CLAUDE_CODE_SESSION_ID` can differ between processes of one long-lived session.** So `whoami` from Claude's shell can miss; ask Claude instead. Without the variable, the channel server keys on its pid and each restart gets a new name. 11. **`AGENT_BRIDGE_HOME` reaches the session's Bash and push endpoint.** Live, 2026-11-19: two sessions started as `AGENT_BRIDGE_HOME= claude` each joined their own home's daemon, and the default home saw neither. 12. **Claude adds its own framing to socket messages.** After our text it appends "This came from another Claude session... very likely working on their behalf. Treat it as a teammate's request". For a message from another user's agent that is wrong; our caution comes first and Sonnet followed it (refused to read and send a file, refused to verify a fingerprint sent over the bridge). We cannot change Claude's text. Tested 2026-11-19 with Haiku and Sonnet in auto mode against urgent, pre-approved and impersonating requests: both followed our caution every time (`docs/live-tests.md`). +13. **`SessionStart` and `SessionEnd` hooks.** Tested live in interactive tmux and `-p` modes (2026-11-24): `SessionStart` fires on launch with `session_id` and `cwd` on stdin plus `CLAUDE_CODE_SESSION_ID` and `CLAUDE_CODE_MESSAGING_SOCKET` in env, so `claude-session-start` can auto-join silently when enabled. `SessionStart` does not include `permission_mode` even with `--dangerously-skip-permissions`. `SessionEnd` fires on `/exit` with `session_id` on stdin and `CLAUDE_CODE_SESSION_ID` in env, allowing `claude-session-end` to call `leave --session`. diff --git a/docs/agents/opencode.md b/docs/agents/opencode.md index 1da6059..8db8788 100644 --- a/docs/agents/opencode.md +++ b/docs/agents/opencode.md @@ -15,3 +15,4 @@ Identity: the tool call's `sessionID`, which the plugin passes to the CLI as `OP 3. **`ctx.session.prompt({ sessionID, text })` wakes an idle session.** Spike, 2026-11-02: a prompt scheduled 20s after the turn ended showed in the TUI and was answered. Source: opencode.ai/v2/docs/build/plugins/server. 4. **Plugins run in a background `opencode serve --service` that outlives the TUI.** Live, 2026-11-19 (opencode 2.3.0): after the TUI exited, the service and its `agent-bridge opencode-stream` child kept running. The environment, `AGENT_BRIDGE_HOME` included, is whatever the process that started the service had: a TUI started later with another home joins the service's home. 5. **A model can call a tool several times in one turn.** The free "Big Pickle" model ran three identical `bridge_send` calls for one reply; the bridge delivered each. +6. **v2 event stream (`ctx.event.subscribe`).** Tested live in tmux on opencode 2.4.1 (2026-11-24): events arrive as `{ type, location: { directory }, data: { sessionID, ... } }`. The plugin subscribes to `session.created` (auto-joins when enabled for `ctx.location.directory`) and `session.deleted` (stops the stream and runs `leave --session`). diff --git a/docs/decisions.md b/docs/decisions.md index c4570be..62e5274 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -25,7 +25,7 @@ Why the bridge works the way it does. Findings referenced here live in [agents/] | `mcp `, not env sniffing | Each client's config names its kind; sniffing does not scale past two | | Push endpoints are listeners in the hub (`PushConn`) | Delivery, ack and fallback reuse the same rules for every push path | | One receive path per session | A push next to a stream listener is refused, and `join` reports it | -| An adapter with `alive` gets its endpoints saved | Claude's socket path is safe on disk and survives a daemon restart. Antigravity's holds a CSRF token, so it has no `alive` and stays in memory. A restored endpoint is checked before it gets mail. The check compares the socket file's inode and creation time: the path holds a pid, which a later session can reuse | +| An adapter with `persistEndpoint` gets its endpoints saved; `alive` probes liveness | Claude's socket path is safe on disk and survives a daemon restart (`persistEndpoint: true`). Antigravity's holds a CSRF token, so it stays in memory (`persistEndpoint` unset), while `alive` still probes its loopback TCP port. Restored endpoints are checked before getting mail (Claude compares socket inode and creation time). Background sweeps kicked by `status` and `send --to-kind` (with a 3s per-endpoint cooldown and one retry after 100ms) plus a 45s timer drop dead endpoints without losing `peer.session` | | Peers record their folder; the daemon resolves `--to-kind` | The agent next to you is usually the one you mean. The hub holds the folders, so any client can use it. Several matches refuse rather than guess. Exact folder only: a subfolder does not match | | Agents send text on stdin, through a quoted heredoc with a random end marker (`send ... - <<''`) | The marker is made where the hint is shown, per hint, or by `agent-bridge marker`, never by the agent (a model's "random" marker repeats): the shell ends a heredoc at the first line equal to its marker and runs the rest, so a fixed marker would let a quoted message plant it. Text passed as a double-quoted argument is expanded by the shell: backticks or `$(...)` quoted from a message ran on the sender's machine and dropped out of the text (#8). Sending only through MCP tools would avoid the shell but lose the session-id check on `--as`. opencode's tool passes the text on stdin too, never through a shell | @@ -42,7 +42,7 @@ Why the bridge works the way it does. Findings referenced here live in [agents/] | Antigravity: push runs only an absolute `.../agy` | The endpoint arrives over the socket. The socket is 0600, so this is defence in depth | | Antigravity: hook drain is acked after print | The hook's 1.5s cap or Antigravity's 3s kill could fire between drain and print | | Antigravity: the PreInvocation hook never blocks | 1.5s cap, `{}` on any failure | -| Antigravity: `/bridge` skill, not SessionStart auto-join | `hooks.json` is global: auto-join would make every Antigravity session take the binding | +| Opt-in auto-join (`agent-bridge auto-join on\|off\|ignore\|unignore`) | Off by default in `~/.agent-bridge/config.json`, with a folder ignore list so one-time setup does not require per-repo config. Claude (`SessionStart` / `SessionEnd`) and opencode (`session.created` / `session.deleted`) auto-join silently; Antigravity's `SessionStart` asks `agy` to run `join --kind agy` on the first turn because hooks lack the agentapi token. Auto-join never auto-shares to a network | | opencode: an in-process plugin | Its tools know the sessionID and `ctx.session.prompt` wakes an idle session, so no ports or passwords. The plugin stays thin; naming, queues and acks stay in the CLI | ## Names and senders diff --git a/docs/install.md b/docs/install.md index c0d562a..67629a8 100644 --- a/docs/install.md +++ b/docs/install.md @@ -5,14 +5,29 @@ | Target | Change | |---|---| | `/opt/homebrew/bin` (or `/usr/local/bin`, `~/.local/bin`) | Symlinks `agent-bridge` to `dist/cli.js`, unless an `agent-bridge` from this package is already on PATH (an npm global install). Uninstall removes only a link install made. Also removes a `claude-bridge` link from older installs | -| Claude Code plugins | `claude plugin marketplace add ` and `claude plugin install agent-bridge@agent-bridge`. The repo is a local marketplace (`.claude-plugin/marketplace.json`); the plugin lives in `src/adapters/claude/plugin/` and loads in place | +| Claude Code plugins | `claude plugin marketplace add ` and `claude plugin install agent-bridge@agent-bridge` (refreshing any cached copy so updated hooks and skills take effect). The repo is a local marketplace (`.claude-plugin/marketplace.json`); the plugin lives in `src/adapters/claude/plugin/` | | `~/.gemini/config/mcp_config.json` | Adds the `agent-bridge` server. Other servers untouched | -| `~/.gemini/config/hooks.json` | Adds the `agent-bridge` hook group (PreInvocation). Other groups untouched | +| `~/.gemini/config/hooks.json` | Adds the `agent-bridge` hook group (`SessionStart`, `PreInvocation`). Other groups untouched | | `~/.gemini/config/skills/bridge/` | Copies the Antigravity `/bridge` skill from `src/adapters/agy/skill/` | | `~/.config/opencode/plugins/agent-bridge.js` | Copies the built opencode plugin. Restart opencode to load it | To pause the Antigravity hook, set `"enabled": false` on the `agent-bridge` group in `hooks.json`. +## Auto-join + +Auto-join is off by default. Turn it on once to join live sessions to the local bridge automatically (saved in `~/.agent-bridge/config.json`): + +```sh +agent-bridge auto-join on +agent-bridge auto-join ignore /path/to/scratch # skip noisy folders (exact match) +agent-bridge auto-join off +``` + +- **Claude Code:** joins silently on `SessionStart` and leaves on `SessionEnd`. +- **opencode:** joins silently on `session.created` and leaves on `session.deleted`. +- **Antigravity:** `SessionStart` prompts `agy` to run `agent-bridge join --kind agy` on its first turn (hooks do not receive the agentapi address or token). Antigravity has no `SessionEnd` hook; the daemon probes its local `ANTIGRAVITY_LS_ADDRESS` port to drop exited CLI sessions. In the IDE or desktop app where one language server serves multiple conversations, a closed conversation stays listed online until that language server exits. +- Auto-join only joins the local bridge. Network sharing (`/bridge share`) stays opt-in per session. + ## Environment overrides | Variable | Overrides | diff --git a/package.json b/package.json index fc7a298..55c8329 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@logickoder/agent-bridge", - "version": "0.2.2", + "version": "0.2.3", "description": "Live messaging between agent CLI sessions (Claude Code, Antigravity, opencode). Each message wakes the receiving session in place.", "author": { "name": "Jeffery Orazulike", diff --git a/src/adapters/agy/hook.test.ts b/src/adapters/agy/hook.test.ts index c555a2c..9762e17 100644 --- a/src/adapters/agy/hook.test.ts +++ b/src/adapters/agy/hook.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it, vi } from 'vitest' +import { DEFAULT_CONFIG, ignoreAutoJoinFolder } from '../../config.js' import type { Message } from '../../schema.js' -import { hookOutput, type Drained } from './hook.js' +import { hookOutput, sessionStartOutput, type Drained } from './hook.js' const msg = (id: string): Message => ({ id, from: 'claude', to: 'agy', text: `text ${id}`, ts: '2026-11-02T00:00:00.000Z' }) const drained = (msgs: Message[], rejoin = false): Drained => ({ msgs, rejoin, ack: vi.fn(async () => {}) }) @@ -51,3 +52,24 @@ describe('hookOutput', () => { expect(JSON.stringify(r.out)).toMatch(/text m1[\s\S]*agent-bridge join --kind agy/) }) }) + +describe('sessionStartOutput', () => { + const onCfg = { autoJoin: { enabled: true, ignore: [] } } + + it('returns {} when off, ignored, missing conversationId, or already online', async () => { + const isOnline = vi.fn(async () => false) + expect(await sessionStartOutput('{"conversationId":"c1","cwd":"/p/app"}', { config: () => DEFAULT_CONFIG, isOnline })).toEqual({}) + expect(await sessionStartOutput('{"conversationId":"c1","cwd":"/p/app"}', { config: () => ignoreAutoJoinFolder(onCfg, '/p/app'), isOnline })).toEqual({}) + expect(await sessionStartOutput('{"cwd":"/p/app"}', { config: () => onCfg, isOnline })).toEqual({}) + expect(await sessionStartOutput('{"conversationId":"c1","cwd":"/p/app"}', { config: () => onCfg, isOnline: async () => true })).toEqual({}) + expect(isOnline).not.toHaveBeenCalled() + }) + + it('injects the auto-join instruction when enabled for the folder', async () => { + const out = await sessionStartOutput('{"conversationId":"c1","workspacePaths":["/p/app"]}', { + config: () => onCfg, + isOnline: async () => false, + }) + expect(out).toEqual({ injectSteps: [{ userMessage: expect.stringMatching(/agent-bridge join --kind agy/) }] }) + }) +}) diff --git a/src/adapters/agy/hook.ts b/src/adapters/agy/hook.ts index a0bee3b..d15b416 100644 --- a/src/adapters/agy/hook.ts +++ b/src/adapters/agy/hook.ts @@ -1,10 +1,12 @@ import { z } from 'zod' -import type { Message } from '../../schema.js' +import type { BridgeConfig, Message } from '../../schema.js' import { request } from '../../client/index.js' +import { loadConfig, shouldAutoJoin } from '../../config.js' import { formatDrained } from './format.js' import { toError } from '../../lib/errors.js' import { logger } from '../../lib/log.js' -import { readStdin, writeLine } from '../../lib/wire.js' +import { parseHookInput, readStdin, writeLine } from '../../lib/wire.js' +import { sessionTag } from '../../names.js' /** Hard cap so a slow or missing daemon never stalls agy. */ const HOOK_BUDGET_MS = 1500 @@ -14,7 +16,16 @@ const log = logger('hook') const REJOIN = '[agent-bridge] Direct delivery to this session is off (the bridge daemon restarted). Run `agent-bridge join --kind agy` in the foreground to restore it, then carry on with what the user asked.' -const HookInput = z.object({ conversationId: z.string().min(1).optional() }).loose() +const AUTO_JOIN = + '[agent-bridge] Auto-join is enabled. Run `agent-bridge join --kind agy` once in the foreground to join the local bridge, then carry on with what the user asked.' + +const HookInput = z + .object({ + conversationId: z.string().min(1).optional(), + cwd: z.string().min(1).optional(), + workspacePaths: z.array(z.string().min(1)).optional(), + }) + .loose() /** Messages shown to this session, and how to remove them from the queue once they are printed. */ export interface Drained { @@ -75,3 +86,42 @@ export async function runHook(): Promise { await ack?.().catch((err: unknown) => log(`ack failed, messages will show again: ${toError(err).message}`)) process.exit(0) } + +/** What SessionStart prints for a given stdin, config, and online check. Never throws. */ +export async function sessionStartOutput( + stdin: string, + deps: { config: () => BridgeConfig; isOnline: (session: string) => Promise }, +): Promise { + const input = parseHookInput(stdin, HookInput) + if (!input?.conversationId) return {} + const folder = input.cwd ?? input.workspacePaths?.[0] + if (!shouldAutoJoin(deps.config(), folder)) return {} + const online = await deps.isOnline(input.conversationId).catch(() => false) + if (online) return {} + return { injectSteps: [{ userMessage: AUTO_JOIN }] } +} + +/** + * agy SessionStart hook. Asks agy to run `join --kind agy` once when auto-join is enabled for this folder. + * Hooks do not receive ANTIGRAVITY_LS_ADDRESS or ANTIGRAVITY_CSRF_TOKEN, so join must run via run_command. + */ +export async function runSessionStart(): Promise { + let printed = false + const print = (out: object): Promise => { + if (printed) return Promise.resolve() + printed = true + return new Promise(resolve => writeLine(process.stdout, out, resolve)) + } + setTimeout(() => void print({}).then(() => process.exit(0)), HOOK_BUDGET_MS).unref() + const out = await sessionStartOutput(await readStdin(), { + config: loadConfig, + isOnline: async session => { + const { peers } = await request({ op: 'status' }, 'status', { spawnDaemon: false }) + const tag = sessionTag(session) + return peers.some(p => p.session === tag && p.online) + }, + }) + if (printed) return process.exit(0) + await print(out) + process.exit(0) +} diff --git a/src/adapters/agy/index.ts b/src/adapters/agy/index.ts index df2f73b..dc7d02a 100644 --- a/src/adapters/agy/index.ts +++ b/src/adapters/agy/index.ts @@ -19,6 +19,8 @@ export const agy: Adapter = { joinHint: 'Antigravity: type `/bridge [name]`.', sessionEnv: SESSION_ENV, joined: async (name, pushed) => (await import('./format.js')).joinedText(name, pushed), + // Never set persistEndpoint: agy endpoints carry a CSRF token and stay in daemon memory only. + alive: async endpoint => (await import('./push.js')).alive(endpoint), pushEndpoint: async env => (await import('./push.js')).endpointFromEnv(env), deliver: async (endpoint, msg) => (await import('./push.js')).deliver(endpoint, msg), serveMcp: async () => (await import('./mcp.js')).serveAgyMcp(), @@ -37,6 +39,10 @@ export const agy: Adapter = { usage: 'agy-hook agy PreInvocation hook', run: async () => (await import('./hook.js')).runHook(), }, + 'agy-session-start': { + usage: 'agy-session-start agy SessionStart hook, asks agy to join when auto-join is on', + run: async () => (await import('./hook.js')).runSessionStart(), + }, }, install: async ctx => (await import('./install.js')).install(ctx), uninstall: async ctx => (await import('./install.js')).uninstall(ctx), diff --git a/src/adapters/agy/install.ts b/src/adapters/agy/install.ts index 4c13f23..97208de 100644 --- a/src/adapters/agy/install.ts +++ b/src/adapters/agy/install.ts @@ -29,7 +29,11 @@ export function install(ctx: InstallContext): string[] { writeObject(f.mcp, { ...mcp, mcpServers: { ...mcp.mcpServers, [GROUP]: { command: ctx.exe, args: ['mcp', 'agy'], disabled: false } } }) const hooks = readObject(f.hooks, JsonObject) ?? {} - hooks[GROUP] = { enabled: true, PreInvocation: [{ type: 'command', command: `${ctx.exe} agy-hook`, timeout: HOOK_TIMEOUT_S }] } + hooks[GROUP] = { + enabled: true, + SessionStart: [{ type: 'command', command: `${ctx.exe} agy-session-start`, timeout: HOOK_TIMEOUT_S }], + PreInvocation: [{ type: 'command', command: `${ctx.exe} agy-hook`, timeout: HOOK_TIMEOUT_S }], + } writeObject(f.hooks, hooks) fs.rmSync(f.skillDst, { recursive: true, force: true }) diff --git a/src/adapters/agy/push.test.ts b/src/adapters/agy/push.test.ts index e777eb0..11aaba5 100644 --- a/src/adapters/agy/push.test.ts +++ b/src/adapters/agy/push.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest' import type { Message } from '../../schema.js' -import { deliverWith, endpointFromEnv, type Run } from './push.js' +import { aliveWith, deliverWith, endpointFromEnv, parseAddress, type Run } from './push.js' const env = { ANTIGRAVITY_LS_ADDRESS: '127.0.0.1:1', @@ -51,3 +51,27 @@ describe('deliverWith', () => { await expect(deliverWith(run)({ ...endpoint, agy: 'agy' }, msg)).rejects.toThrow(/absolute path/) }) }) + +describe('parseAddress and aliveWith', () => { + it('parses host:port and IPv6 addresses and rejects invalid ones', () => { + expect(parseAddress('localhost:59106')).toEqual({ host: 'localhost', port: 59106 }) + expect(parseAddress('[::1]:8080')).toEqual({ host: '::1', port: 8080 }) + expect(parseAddress('localhost:0')).toBeUndefined() + expect(parseAddress('not-an-address')).toBeUndefined() + }) + + it('probes the parsed host and port', async () => { + const seen: [string, number][] = [] + const alive = aliveWith(async (host, port) => { + seen.push([host, port]) + return port === 59106 + }) + expect(await alive({ address: 'localhost:59106' })).toBe(true) + expect(await alive({ address: 'localhost:9999' })).toBe(false) + expect(await alive({})).toBe(false) + expect(seen).toEqual([ + ['localhost', 59106], + ['localhost', 9999], + ]) + }) +}) diff --git a/src/adapters/agy/push.ts b/src/adapters/agy/push.ts index 42b8b36..2e03d64 100644 --- a/src/adapters/agy/push.ts +++ b/src/adapters/agy/push.ts @@ -1,4 +1,5 @@ import { spawn } from 'node:child_process' +import net from 'node:net' import path from 'node:path' import { z } from 'zod' import type { Message } from '../../schema.js' @@ -66,3 +67,42 @@ export const deliverWith = } export const deliver = deliverWith(runProcess) + +const PROBE_TIMEOUT_MS = 200 + +/** Parses `host:port` (including IPv6 `[::1]:port`) from `ANTIGRAVITY_LS_ADDRESS`. */ +export function parseAddress(address: string): { host: string; port: number } | undefined { + const m = /^(?:\[([^\]]+)\]|([^:]+)):(\d+)$/.exec(address.trim()) + if (!m) return undefined + const host = m[1] ?? m[2] + const port = Number(m[3]) + if (!host || !Number.isInteger(port) || port < 1 || port > 65535) return undefined + return { host, port } +} + +export type ProbeConnect = (host: string, port: number) => Promise + +const tcpAlive: ProbeConnect = (host, port) => + new Promise(resolve => { + const sock = net.createConnection({ host, port }) + const done = (ok: boolean) => { + clearTimeout(timer) + sock.destroy() + resolve(ok) + } + const timer = setTimeout(() => done(false), PROBE_TIMEOUT_MS) + sock.once('connect', () => done(true)) + sock.once('error', () => done(false)) + }) + +/** True if the session's local agentapi port is still accepting connections. Never persists credentials. */ +export const aliveWith = + (connect: ProbeConnect) => + async (endpoint: Record): Promise => { + const addr = endpoint['address'] + const parsed = addr ? parseAddress(addr) : undefined + if (!parsed) return false + return connect(parsed.host, parsed.port) + } + +export const alive = aliveWith(tcpAlive) diff --git a/src/adapters/claude/index.ts b/src/adapters/claude/index.ts index 0bf4bbe..0ddb675 100644 --- a/src/adapters/claude/index.ts +++ b/src/adapters/claude/index.ts @@ -16,6 +16,7 @@ export const claude: Adapter = { sessionEnv: SESSION_ENV, joined: async (name, pushed) => (await import('./format.js')).joinedText(name, pushed), // Only the socket path, never the messaging token: safe to keep on disk across daemon restarts. + persistEndpoint: true, alive: async endpoint => (await import('./socket.js')).alive(endpoint), pushEndpoint: async env => (await import('./socket.js')).endpointFromEnv(env), deliver: async (endpoint, msg) => (await import('./socket.js')).deliver(endpoint, msg), @@ -28,6 +29,14 @@ export const claude: Adapter = { usage: 'claude-guard claude: plugin PreToolUse hook, keeps bypass-mode sessions off the socket', run: async () => (await import('./guard.js')).runGuard(), }, + 'claude-session-start': { + usage: 'claude-session-start claude: plugin SessionStart hook, auto-joins when enabled', + run: async () => (await import('./session.js')).runSessionStart(), + }, + 'claude-session-end': { + usage: 'claude-session-end claude: plugin SessionEnd hook, releases binding on exit', + run: async () => (await import('./session.js')).runSessionEnd(), + }, monitor: { usage: 'monitor claude: plugin monitor, one line per message for this session', run: async () => (await import('./monitor.js')).runMonitor(), diff --git a/src/adapters/claude/install.ts b/src/adapters/claude/install.ts index 1d73418..e8920d2 100644 --- a/src/adapters/claude/install.ts +++ b/src/adapters/claude/install.ts @@ -4,8 +4,9 @@ import { unlinkBin } from '../../lib/config.js' import type { InstallContext } from '../types.js' // Claude joins through a local plugin: the repo is a marketplace (.claude-plugin/marketplace.json) whose -// plugin lives in src/adapters/claude/plugin. A local-path marketplace loads in place, so a rebuild needs -// no reinstall. The channel launcher is opt-in now: `agent-bridge claude`, or an alias for it. +// plugin lives in src/adapters/claude/plugin. Claude caches installed plugins by version under +// ~/.claude/plugins/cache, so install removes any cached copy before installing to pick up hook/skill edits. +// The channel launcher is opt-in now: `agent-bridge claude`, or an alias for it. const MARKETPLACE = 'agent-bridge' const PLUGIN = `agent-bridge@${MARKETPLACE}` @@ -29,11 +30,15 @@ function removeLegacyLauncher(ctx: InstallContext): string[] { } export function install(ctx: InstallContext): string[] { - return [ - ...removeLegacyLauncher(ctx), - claude(ctx, ['plugin', 'marketplace', 'add', ctx.repo], `claude marketplace ${MARKETPLACE} (${ctx.repo})`), - claude(ctx, ['plugin', 'install', PLUGIN], `claude plugin ${PLUGIN}`), - ] + // Refresh any cached copy so updated hooks/skills take effect without bumping plugin.json. + const removed = spawnSync(claudeBin(ctx), ['plugin', 'uninstall', PLUGIN], { encoding: 'utf8' }) + const hadPlugin = !removed.error && removed.status === 0 + const okLine = `claude plugin ${PLUGIN}` + const marketplace = claude(ctx, ['plugin', 'marketplace', 'add', ctx.repo], `claude marketplace ${MARKETPLACE} (${ctx.repo})`) + const plugin = claude(ctx, ['plugin', 'install', PLUGIN], okLine) + // The old copy is gone by now. Say so when the reinstall failed, so the user is not left guessing. + const lost = hadPlugin && plugin !== okLine ? [`claude the installed plugin was removed first. Run \`claude plugin install ${PLUGIN}\` to restore it.`] : [] + return [...removeLegacyLauncher(ctx), marketplace, plugin, ...lost] } export function uninstall(ctx: InstallContext): string[] { diff --git a/src/adapters/claude/plugin/.claude-plugin/plugin.json b/src/adapters/claude/plugin/.claude-plugin/plugin.json index d8f53b9..4b93b29 100644 --- a/src/adapters/claude/plugin/.claude-plugin/plugin.json +++ b/src/adapters/claude/plugin/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "agent-bridge", - "version": "0.1.0", + "version": "0.2.0", "description": "Join agent-bridge from Claude Code with /bridge. A monitor delivers messages from peer agents (other Claude sessions, agy).", "author": { "name": "logickoder" } } diff --git a/src/adapters/claude/plugin/hooks/hooks.json b/src/adapters/claude/plugin/hooks/hooks.json index b698f71..6134984 100644 --- a/src/adapters/claude/plugin/hooks/hooks.json +++ b/src/adapters/claude/plugin/hooks/hooks.json @@ -1,5 +1,27 @@ { "hooks": { + "SessionStart": [ + { + "hooks": [ + { + "type": "command", + "command": "agent-bridge claude-session-start", + "timeout": 5 + } + ] + } + ], + "SessionEnd": [ + { + "hooks": [ + { + "type": "command", + "command": "agent-bridge claude-session-end", + "timeout": 3 + } + ] + } + ], "PreToolUse": [ { "matcher": "Bash", diff --git a/src/adapters/claude/session.test.ts b/src/adapters/claude/session.test.ts new file mode 100644 index 0000000..909548f --- /dev/null +++ b/src/adapters/claude/session.test.ts @@ -0,0 +1,57 @@ +import { describe, expect, it, vi } from 'vitest' +import { DEFAULT_CONFIG, ignoreAutoJoinFolder } from '../../config.js' +import { sessionEndAction, sessionStartOutput } from './session.js' + +const onCfg = { autoJoin: { enabled: true, ignore: [] } } + +describe('claude sessionStartOutput', () => { + it('returns nothing when auto-join is off or folder is ignored', async () => { + const join = vi.fn(async () => 'app-claude') + expect( + await sessionStartOutput('{"session_id":"s1","cwd":"/p/app"}', { CLAUDE_CODE_SESSION_ID: 's1' }, { config: () => DEFAULT_CONFIG, endpoint: () => ({ socket: '/tmp/s.sock' }), join }), + ).toBeUndefined() + const ignored = ignoreAutoJoinFolder(onCfg, '/p/app') + expect( + await sessionStartOutput('{"session_id":"s1","cwd":"/p/app"}', { CLAUDE_CODE_SESSION_ID: 's1' }, { config: () => ignored, endpoint: () => ({ socket: '/tmp/s.sock' }), join }), + ).toBeUndefined() + expect(join).not.toHaveBeenCalled() + }) + + it('skips bypass-permissions mode and sessions without a socket', async () => { + const join = vi.fn(async () => 'app-claude') + expect( + await sessionStartOutput('{"session_id":"s1","cwd":"/p/app","permission_mode":"bypassPermissions"}', {}, { config: () => onCfg, endpoint: () => ({ socket: '/tmp/s.sock' }), join }), + ).toBeUndefined() + expect( + await sessionStartOutput('{"session_id":"s1","cwd":"/p/app"}', {}, { config: () => onCfg, endpoint: () => undefined, join }), + ).toBeUndefined() + expect(join).not.toHaveBeenCalled() + }) + + it('joins and returns additionalContext when enabled', async () => { + const join = vi.fn(async () => 'app-claude') + const out = await sessionStartOutput( + '{"session_id":"s1","cwd":"/p/app"}', + { CLAUDE_CODE_SESSION_ID: 's1' }, + { config: () => onCfg, endpoint: () => ({ socket: '/tmp/s.sock', file: '1:2' }), join }, + ) + expect(join).toHaveBeenCalledWith('/p/app', 's1', { socket: '/tmp/s.sock', file: '1:2' }) + expect(out).toEqual({ + hookSpecificOutput: { + hookEventName: 'SessionStart', + additionalContext: expect.stringContaining('Auto-joined agent-bridge as "app-claude"'), + }, + }) + }) +}) + +describe('claude sessionEndAction', () => { + it('calls leave with the env or stdin session id', async () => { + const leave = vi.fn(async () => {}) + expect(await sessionEndAction('{"session_id":"s1"}', {}, leave)).toBe(true) + expect(leave).toHaveBeenCalledWith('s1') + expect(await sessionEndAction('not json', { CLAUDE_CODE_SESSION_ID: 's2' }, leave)).toBe(true) + expect(leave).toHaveBeenCalledWith('s2') + expect(await sessionEndAction('{}', {}, leave)).toBe(false) + }) +}) diff --git a/src/adapters/claude/session.ts b/src/adapters/claude/session.ts new file mode 100644 index 0000000..6034f1a --- /dev/null +++ b/src/adapters/claude/session.ts @@ -0,0 +1,111 @@ +import { z } from 'zod' +import { request, resolveName } from '../../client/index.js' +import { loadConfig, shouldAutoJoin } from '../../config.js' +import { sendGuide } from '../../format.js' +import { toError } from '../../lib/errors.js' +import { logger } from '../../lib/log.js' +import { parseHookInput, readStdin, writeLine } from '../../lib/wire.js' +import type { BridgeConfig } from '../../schema.js' +import { SESSION_ENV } from './names.js' +import { endpointFromEnv } from './socket.js' + +/** Hard cap so a slow daemon never stalls Claude startup or exit. */ +const HOOK_BUDGET_MS = 1500 + +const log = logger('claude-session') + +const SessionInput = z + .object({ + session_id: z.string().min(1).optional(), + cwd: z.string().min(1).optional(), + permission_mode: z.string().optional(), + }) + .loose() + +export interface SessionStartDeps { + config: () => BridgeConfig + endpoint: (env: NodeJS.ProcessEnv) => Record | undefined + join: (folder: string, session: string, endpoint: Record) => Promise +} + +/** + * Pure SessionStart decision: auto-joins the local bridge when enabled for `cwd`, unless the session + * is in bypass-permissions mode or lacks a messaging socket. Returns hook JSON to print, or undefined. + */ +export async function sessionStartOutput( + stdin: string, + env: NodeJS.ProcessEnv, + deps: SessionStartDeps, +): Promise { + const input = parseHookInput(stdin, SessionInput) + if (!input) return undefined + const { session_id, cwd, permission_mode } = input + if (permission_mode === 'bypassPermissions') return undefined + const folder = cwd ?? process.cwd() + if (!shouldAutoJoin(deps.config(), folder)) return undefined + const session = env[SESSION_ENV] ?? session_id + const endpoint = deps.endpoint(env) + if (!session || !endpoint) { + log(`auto-join skipped: missing ${!session ? 'session id' : 'CLAUDE_CODE_MESSAGING_SOCKET'}.`) + return undefined + } + const name = await deps.join(folder, session, endpoint) + return { + hookSpecificOutput: { + hookEventName: 'SessionStart', + additionalContext: `Auto-joined agent-bridge as "${name}". Messages from peers arrive directly in this session. Send with ${sendGuide(name)}. \`agent-bridge peers\` lists who is online.`, + }, + } +} + +/** Pure SessionEnd action: unbinds the session if a session id is present. */ +export async function sessionEndAction( + stdin: string, + env: NodeJS.ProcessEnv, + leave: (session: string) => Promise, +): Promise { + const session = env[SESSION_ENV] ?? parseHookInput(stdin, SessionInput)?.session_id + if (!session) return false + await leave(session) + return true +} + +/** Claude Code SessionStart hook. Always exits 0; never blocks startup. */ +export async function runSessionStart(): Promise { + let done = false + const finish = (out?: object): Promise => { + if (done) return Promise.resolve() + done = true + if (!out) return Promise.resolve() + return new Promise(resolve => writeLine(process.stdout, out, resolve)) + } + setTimeout(() => void finish().then(() => process.exit(0)), HOOK_BUDGET_MS).unref() + try { + const out = await sessionStartOutput(await readStdin(), process.env, { + config: loadConfig, + endpoint: endpointFromEnv, + join: async (folder, session, endpoint) => { + const name = await resolveName({ folder }, 'claude', session, { folder }) + await request({ op: 'push', kind: 'claude', session, endpoint }, 'ok') + return name + }, + }) + await finish(out) + } catch (err) { + log(`auto-join failed: ${toError(err).message}`) + } + process.exit(0) +} + +/** Claude Code SessionEnd hook. Releases the session binding without starting a stopped daemon. */ +export async function runSessionEnd(): Promise { + setTimeout(() => process.exit(0), HOOK_BUDGET_MS).unref() + try { + await sessionEndAction(await readStdin(), process.env, async session => { + await request({ op: 'leave', session }, 'ok', { spawnDaemon: false }) + }) + } catch (err) { + log(`auto-leave failed: ${toError(err).message}`) + } + process.exit(0) +} diff --git a/src/adapters/opencode/plugin/agent-bridge.test.ts b/src/adapters/opencode/plugin/agent-bridge.test.ts index 8bfbb34..60b5e58 100644 --- a/src/adapters/opencode/plugin/agent-bridge.test.ts +++ b/src/adapters/opencode/plugin/agent-bridge.test.ts @@ -1,5 +1,5 @@ import { PassThrough } from 'node:stream' -import { describe, expect, it } from 'vitest' +import { describe, expect, it, vi } from 'vitest' import { createPlugin, type Exec, type Spawn, type Tool } from './agent-bridge.js' /** A fake opencode ctx: records registered tools and prompts. */ @@ -90,4 +90,67 @@ describe('opencode plugin', () => { ]) expect(execs[1]?.env['OPENCODE_SESSION_ID']).toBe('ses_1') }) + + it('auto-joins on session.created and auto-leaves on session.deleted when enabled', async () => { + const execs: { args: string[]; env: NodeJS.ProcessEnv; cwd: string }[] = [] + const exec: Exec = async (args, env, cwd) => { + execs.push({ args, env, cwd }) + return args[0] === 'join' ? 'Joined agent-bridge as "proj-opencode".' : 'ok' + } + let killed = 0 + const spawn: Spawn = () => ({ stdout: new PassThrough(), kill: () => void killed++ }) + const events = [ + { type: 'session.created', location: { directory: '/p/other' }, data: { sessionID: 'ses_other' } }, + { type: 'session.created', data: { sessionID: 'ses_nodir' } }, + { type: 'session.created', location: { directory: '/p/proj' }, data: { sessionID: 'ses_child', parentID: 'ses_auto' } }, + { type: 'session.created', location: { directory: '/p/proj' }, data: { sessionID: 'ses_auto' } }, + { type: 'session.deleted', location: { directory: '/p/proj' }, data: { sessionID: 'ses_auto' } }, + ] + const f = fakeCtx() + const ctx = { + ...f.ctx, + event: { + subscribe: async function* () { + for (const ev of events) yield ev + }, + }, + } + await createPlugin({ exec, spawn, shouldAutoJoin: () => true }).setup(ctx) + await new Promise(r => setTimeout(r, 20)) + expect(execs.map(e => [e.args, e.env['OPENCODE_SESSION_ID']])).toEqual([ + [['join', '--kind', 'opencode'], 'ses_auto'], + [['leave', '--session', 'ses_auto'], 'ses_auto'], + ]) + expect(killed).toBe(1) + }) + + it('logs when a session.created has no directory and auto-join is on, and stays quiet when it is off', async () => { + const written: string[] = [] + const stderr = vi.spyOn(process.stderr, 'write').mockImplementation((chunk: string | Uint8Array) => { + written.push(String(chunk)) + return true + }) + try { + for (const enabled of [true, false]) { + written.length = 0 + const exec: Exec = async () => 'Joined agent-bridge as "proj-opencode".' + const spawn: Spawn = () => ({ stdout: new PassThrough(), kill: () => {} }) + const f = fakeCtx() + const ctx = { + ...f.ctx, + event: { + subscribe: async function* () { + yield { type: 'session.created', data: { sessionID: 'ses_nodir' } } + }, + }, + } + await createPlugin({ exec, spawn, shouldAutoJoin: () => enabled }).setup(ctx) + await new Promise(r => setTimeout(r, 20)) + const logged = written.filter(line => line.includes('session.created event has no directory')) + expect(logged).toHaveLength(enabled ? 1 : 0) + } + } finally { + stderr.mockRestore() + } + }) }) diff --git a/src/adapters/opencode/plugin/agent-bridge.ts b/src/adapters/opencode/plugin/agent-bridge.ts index 0d5e98f..6d6075b 100644 --- a/src/adapters/opencode/plugin/agent-bridge.ts +++ b/src/adapters/opencode/plugin/agent-bridge.ts @@ -7,6 +7,9 @@ // idle session. import { execFile, spawn as spawnChild } from 'node:child_process' +import fs from 'node:fs' +import os from 'node:os' +import path from 'node:path' import { createInterface } from 'node:readline' import type { Readable } from 'node:stream' @@ -29,6 +32,57 @@ export interface Ctx { location: { directory: string } tool: { transform: (fn: (editor: { add: (tool: Tool) => void }) => void) => Promise } session: { prompt: (p: { sessionID: string; text: string }) => Promise } + event?: { subscribe: (options?: { types?: string[]; signal?: AbortSignal }) => AsyncIterable } +} + +/** Resolves symlinks where the path exists, like `normalizeFolder` in src/config.ts, so ignore entries match across agents. */ +function realFolder(dir: string): string { + const resolved = path.resolve(dir) + try { + return fs.realpathSync(resolved) + } catch { + return resolved + } +} + +/** Returns whether auto-join is enabled for `dir`, reading `~/.agent-bridge/config.json` directly. */ +export function shouldAutoJoinFromFile(dir: string, env: NodeJS.ProcessEnv = process.env): boolean { + // Same home as src/paths.ts. The plugin is standalone (node built-ins only), so it cannot import it. + const home = env['AGENT_BRIDGE_HOME'] ?? path.join(os.homedir(), '.agent-bridge') + try { + const raw = JSON.parse(fs.readFileSync(path.join(home, 'config.json'), 'utf8')) as unknown + if (typeof raw !== 'object' || raw === null) return false + const autoJoin: unknown = Reflect.get(raw, 'autoJoin') + if (typeof autoJoin !== 'object' || autoJoin === null) return false + if (Reflect.get(autoJoin, 'enabled') !== true) return false + const ignore: unknown = Reflect.get(autoJoin, 'ignore') + if (!Array.isArray(ignore)) return true + const target = realFolder(dir) + return !ignore.some(item => typeof item === 'string' && realFolder(item) === target) + } catch { + return false + } +} + +const errMsg = (err: unknown): string => (err instanceof Error ? err.message : String(err)) + +const logErr = (msg: string): void => { + process.stderr.write(`[agent-bridge] ${msg}\n`) +} + +/** Extracts `type`, `sessionID`, `isChild`, and optional `directory` from an opencode v2 event. */ +function parseSessionEvent(value: unknown): { type: string; sessionID: string; isChild: boolean; directory?: string } | undefined { + if (typeof value !== 'object' || value === null) return undefined + const type: unknown = Reflect.get(value, 'type') + const data: unknown = Reflect.get(value, 'data') + if (typeof type !== 'string' || typeof data !== 'object' || data === null) return undefined + const sessionID: unknown = Reflect.get(data, 'sessionID') + if (typeof sessionID !== 'string' || !sessionID) return undefined + const parent: unknown = Reflect.get(data, 'parentID') ?? Reflect.get(data, 'parentSessionID') + const isChild = typeof parent === 'string' && parent.length > 0 + const loc: unknown = Reflect.get(value, 'location') ?? Reflect.get(data, 'location') + const dir: unknown = typeof loc === 'object' && loc !== null ? Reflect.get(loc, 'directory') : undefined + return typeof dir === 'string' ? { type, sessionID, isChild, directory: dir } : { type, sessionID, isChild } } /** Runs the CLI to completion and returns stdout, writing `input` to its stdin. Rejects with stderr on failure. */ @@ -60,7 +114,7 @@ const StreamLine = (value: unknown): { type: string; text: string } | undefined return typeof type === 'string' && typeof text === 'string' ? { type, text } : undefined } -export function createPlugin(deps: { exec: Exec; spawn: Spawn }) { +export function createPlugin(deps: { exec: Exec; spawn: Spawn; shouldAutoJoin?: (dir: string) => boolean }) { return { id: 'agent-bridge', async setup(ctx: Ctx) { @@ -68,6 +122,7 @@ export function createPlugin(deps: { exec: Exec; spawn: Spawn }) { const streams = new Map void>() const envFor = (sessionID: string): NodeJS.ProcessEnv => ({ ...process.env, [SESSION_ENV]: sessionID }) const cwd = ctx.location.directory + const autoJoinCheck = deps.shouldAutoJoin ?? (dir => shouldAutoJoinFromFile(dir)) const startStream = (sessionID: string): void => { if (streams.has(sessionID)) return @@ -87,12 +142,55 @@ export function createPlugin(deps: { exec: Exec; spawn: Spawn }) { }) } + const joinSession = async (sessionID: string, args: string[] = []): Promise => { + const out = await deps.exec(['join', '--kind', 'opencode', ...args], envFor(sessionID), cwd) + const name = /Joined agent-bridge as "([^"]+)"/.exec(out)?.[1] + if (name) names.set(sessionID, name) + startStream(sessionID) + return out + } + const requireName = (sessionID: string): string => { const name = names.get(sessionID) if (!name) throw new Error('not on agent-bridge yet. Call bridge_join first.') return name } + const ac = new AbortController() + if (ctx.event?.subscribe) { + const stream = ctx.event.subscribe({ types: ['session.created', 'session.deleted'], signal: ac.signal }) + void (async () => { + try { + for await (const raw of stream) { + const ev = parseSessionEvent(raw) + if (!ev) continue + if (ev.type === 'session.created') { + if (ev.isChild) continue + // Without the session's folder the plugin's own would be recorded, which can be another project's. + if (!ev.directory) { + if (autoJoinCheck(cwd)) logErr('auto-join skipped: the session.created event has no directory.') + continue + } + if (realFolder(ev.directory) !== realFolder(cwd)) continue + if (names.has(ev.sessionID) || !autoJoinCheck(cwd)) continue + await joinSession(ev.sessionID).catch((err: unknown) => logErr(`auto-join failed: ${errMsg(err)}`)) + } else if (ev.type === 'session.deleted') { + if (ev.directory && realFolder(ev.directory) !== realFolder(cwd)) continue + if (!streams.has(ev.sessionID) && !names.has(ev.sessionID)) continue + streams.get(ev.sessionID)?.() + streams.delete(ev.sessionID) + names.delete(ev.sessionID) + await deps.exec(['leave', '--session', ev.sessionID], envFor(ev.sessionID), cwd).catch((err: unknown) => + logErr(`auto-leave failed: ${errMsg(err)}`), + ) + } + } + } catch (err) { + if (!ac.signal.aborted) logErr(`event stream ended: ${errMsg(err)}`) + } + })() + } + await ctx.tool.transform(editor => { editor.add({ name: 'bridge_join', @@ -107,12 +205,8 @@ export function createPlugin(deps: { exec: Exec; spawn: Spawn }) { additionalProperties: false, }, execute: async (input, context) => { - const args = ['join', '--kind', 'opencode', ...(input['take'] === true ? ['--take'] : []), ...(typeof input['name'] === 'string' ? [input['name']] : [])] - const out = await deps.exec(args, envFor(context.sessionID), cwd) - const name = /Joined agent-bridge as "([^"]+)"/.exec(out)?.[1] - if (name) names.set(context.sessionID, name) - startStream(context.sessionID) - return { content: out } + const extra = [...(input['take'] === true ? ['--take'] : []), ...(typeof input['name'] === 'string' ? [input['name']] : [])] + return { content: await joinSession(context.sessionID, extra) } }, }) editor.add({ @@ -170,6 +264,7 @@ export function createPlugin(deps: { exec: Exec; spawn: Spawn }) { }) return () => { + ac.abort() for (const kill of streams.values()) kill() } }, diff --git a/src/adapters/types.ts b/src/adapters/types.ts index 47dae41..785048a 100644 --- a/src/adapters/types.ts +++ b/src/adapters/types.ts @@ -31,10 +31,15 @@ export interface Adapter { /** A push endpoint from the agent's environment, registered by `join`. Absent: the agent receives by listening. */ pushEndpoint?: (env: NodeJS.ProcessEnv) => Promise | undefined> /** - * True if an endpoint still reaches its session. Set it only when the endpoint holds no credential: the daemon - * then saves the endpoint, restores it after a restart, and drops it at start if this says it is gone. + * True if an endpoint still reaches its session. Used by the daemon to drop dead push endpoints on demand, + * on a slow network-presence timer, and when restoring saved endpoints at start. */ alive?: (endpoint: Record) => Promise + /** + * True only when the push endpoint holds no credential and is safe to save to disk (`endpoints.json`) + * so it survives a daemon restart. Requires `alive`. + */ + persistEndpoint?: boolean /** Pushes one message through an endpoint from pushEndpoint. Runs in the daemon. */ deliver?: (endpoint: Record, msg: Message) => Promise /** `agent-bridge mcp `: the MCP server this agent's client launches. */ diff --git a/src/cli.ts b/src/cli.ts index b06a969..fdae132 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -25,7 +25,8 @@ const USAGE = [ ' whoami this session\'s peer name(s), from the agent\'s session id', ' marker a random heredoc end marker, for `send ... - <<\'\'`', ' send [--as me] send; - reads the text from stdin; --to-kind: the one online peer of that kind in this folder', - ' leave unbind a peer and stop its listeners', + ' leave [name | --session id] unbind a peer and stop its listeners (no arg: this session)', + ' auto-join [on|off|ignore|unignore] auto-join live sessions (with optional folder ignore list)', ' net host|invite|connect|status|share|unshare|verify|... networks across machines: `agent-bridge net help`', ' restart stop the daemon; the next client starts the new one', ` mcp MCP server for one agent kind: ${adapters.map(a => a.kind).join(', ')}`, @@ -131,7 +132,33 @@ async function main(argv: string[]): Promise { return (await import('./net/keeper.js')).runKeeper(args) case 'net': return (await import('./net/cli.js')).runNet(args, { sessions: () => envSessions().map(s => s.id), out, confirm: askTerminal }) + case 'auto-join': { + const { formatAutoJoin, ignoreAutoJoinFolder, loadConfig, saveConfig, setAutoJoin, unignoreAutoJoinFolder } = await import('./config.js') + const cfg = loadConfig() + const sub = args[0] + if (!sub) return out(formatAutoJoin(cfg)) + const folder = args[1] ?? process.cwd() + const updates: Record typeof cfg> = { + on: () => setAutoJoin(cfg, true), + off: () => setAutoJoin(cfg, false), + ignore: () => ignoreAutoJoinFolder(cfg, folder), + unignore: () => unignoreAutoJoinFolder(cfg, folder), + } + const update = updates[sub] + if (!update) throw new Error(`unknown auto-join command "${sub}". Use on, off, ignore [folder], or unignore [folder].`) + const next = update() + saveConfig(next) + return out(formatAutoJoin(next)) + } case 'leave': { + const sessionFlag = takeFlag(args, '--session') + if (sessionFlag !== undefined || args[0] === undefined) { + const [only, ...rest] = envSessions() + const session = sessionFlag !== undefined ? sessionFlag.trim() : only && !rest.length ? only.id : '' + if (!session) throw new Error(sessionFlag !== undefined ? 'leave --session needs a non-empty session id.' : 'leave needs a peer name, or --session . Pass the name from `agent-bridge whoami`.') + await request({ op: 'leave', session }, 'ok') + return out('Left agent-bridge. Listeners exited and the binding is released.') + } const name = peerName(args[0], 'Peer name') await request({ op: 'leave', as: name }, 'ok') return out(`"${name}" left. Its listeners exited and the binding is released.`) diff --git a/src/config.test.ts b/src/config.test.ts new file mode 100644 index 0000000..2d86534 --- /dev/null +++ b/src/config.test.ts @@ -0,0 +1,39 @@ +import { describe, expect, it } from 'vitest' +import { DEFAULT_CONFIG, formatAutoJoin, ignoreAutoJoinFolder, shouldAutoJoin, unignoreAutoJoinFolder } from './config.js' + +describe('auto-join config', () => { + it('defaults to off', () => { + expect(shouldAutoJoin(DEFAULT_CONFIG, '/p/app')).toBe(false) + expect(formatAutoJoin(DEFAULT_CONFIG)).toBe('auto-join: off.') + }) + + it('joins every folder when enabled and ignore list is empty, failing closed without a folder', () => { + const cfg = { autoJoin: { enabled: true, ignore: [] } } + expect(shouldAutoJoin(cfg, '/p/app')).toBe(true) + expect(shouldAutoJoin(cfg, undefined)).toBe(false) + expect(formatAutoJoin(cfg)).toBe('auto-join: on.') + }) + + it('skips exact ignored folders, normalizing trailing slashes', () => { + const cfg = ignoreAutoJoinFolder({ autoJoin: { enabled: true, ignore: [] } }, '/p/scratch/') + expect(shouldAutoJoin(cfg, '/p/scratch')).toBe(false) + expect(shouldAutoJoin(cfg, '/p/scratch/')).toBe(false) + expect(shouldAutoJoin(cfg, '/p/scratch/sub')).toBe(true) + expect(shouldAutoJoin(cfg, '/p/app')).toBe(true) + }) + + it('deduplicates ignored folders and unignores them cleanly', () => { + let cfg = ignoreAutoJoinFolder({ autoJoin: { enabled: true, ignore: [] } }, '/p/a') + cfg = ignoreAutoJoinFolder(cfg, '/p/a/') + cfg = ignoreAutoJoinFolder(cfg, '/p/b') + expect(cfg.autoJoin.ignore).toEqual(['/p/a', '/p/b']) + expect(formatAutoJoin(cfg)).toBe('auto-join: on.\nIgnored folders:\n /p/a\n /p/b') + + cfg = unignoreAutoJoinFolder(cfg, '/p/a') + expect(cfg.autoJoin.ignore).toEqual(['/p/b']) + + cfg = unignoreAutoJoinFolder(cfg, '/p/b') + expect(cfg.autoJoin.ignore).toEqual([]) + expect(formatAutoJoin(cfg)).toBe('auto-join: on.') + }) +}) diff --git a/src/config.ts b/src/config.ts new file mode 100644 index 0000000..c96f772 --- /dev/null +++ b/src/config.ts @@ -0,0 +1,69 @@ +import fs from 'node:fs' +import path from 'node:path' +import { readJson, writeJson } from './lib/json-file.js' +import { CONFIG_FILE, ensureHome } from './paths.js' +import { BridgeConfig } from './schema.js' + +export const DEFAULT_CONFIG: BridgeConfig = { autoJoin: { enabled: false, ignore: [] } } + +/** Normalizes a folder path for exact matching (resolves symlinks where the path exists, else `path.resolve`). */ +export function normalizeFolder(folder: string): string { + const resolved = path.resolve(folder) + try { + return fs.realpathSync(resolved) + } catch { + return resolved + } +} + +/** True when a session started in `folder` should auto-join the local bridge. Fails closed without a folder. */ +export function shouldAutoJoin(config: BridgeConfig, folder: string | undefined): boolean { + if (!config.autoJoin.enabled || !folder) return false + const target = normalizeFolder(folder) + // Stored entries are already normalized, so the string compare skips a realpath per entry in the common case. + return !config.autoJoin.ignore.some(f => f === target || normalizeFolder(f) === target) +} + +/** Returns a new config with auto-join switched on or off. */ +export function setAutoJoin(config: BridgeConfig, enabled: boolean): BridgeConfig { + return { ...config, autoJoin: { ...config.autoJoin, enabled } } +} + +/** Returns a new config with `folder` added to the ignore list. */ +export function ignoreAutoJoinFolder(config: BridgeConfig, folder: string): BridgeConfig { + const norm = normalizeFolder(folder) + const ignore = config.autoJoin.ignore.map(normalizeFolder) + if (!ignore.includes(norm)) ignore.push(norm) + return { ...config, autoJoin: { ...config.autoJoin, ignore } } +} + +/** Returns a new config with `folder` removed from the ignore list. */ +export function unignoreAutoJoinFolder(config: BridgeConfig, folder: string): BridgeConfig { + const norm = normalizeFolder(folder) + const ignore = config.autoJoin.ignore.map(normalizeFolder).filter(f => f !== norm) + return { ...config, autoJoin: { ...config.autoJoin, ignore } } +} + +/** Human-readable summary for `agent-bridge auto-join`. */ +export function formatAutoJoin(config: BridgeConfig): string { + const { enabled, ignore } = config.autoJoin + const head = enabled ? 'auto-join: on.' : 'auto-join: off.' + if (!ignore.length) return head + return [head, 'Ignored folders:', ...ignore.map(f => ` ${f}`)].join('\n') +} + +/** Loads `~/.agent-bridge/config.json`. Missing or invalid files fall back to defaults (never throws). */ +export function loadConfig(file = CONFIG_FILE): BridgeConfig { + try { + const read = readJson(file, BridgeConfig) + return read.status === 'ok' ? read.value : DEFAULT_CONFIG + } catch { + return DEFAULT_CONFIG + } +} + +/** Writes `~/.agent-bridge/config.json` atomically. */ +export function saveConfig(config: BridgeConfig, file = CONFIG_FILE): void { + if (file === CONFIG_FILE) ensureHome() + writeJson(file, config, { pretty: true }) +} diff --git a/src/daemon/hub.test.ts b/src/daemon/hub.test.ts index 6771c22..db31b88 100644 --- a/src/daemon/hub.test.ts +++ b/src/daemon/hub.test.ts @@ -48,7 +48,16 @@ type Deliver = NonNullable[0]['deliver']> function setup(store = memoryStore(), log: (msg: string) => void = () => {}, deliver?: Deliver, alive: (endpoint: Record) => Promise = async () => true) { let n = 0 const clock = { now: new Date('2026-11-02T00:00:00Z') } - const hub = new Hub({ store, now: () => clock.now, newId: () => `m${++n}`, pid: 1, log, ...(deliver ? { deliver } : {}), probe: kind => (kind === 'claude' ? alive : undefined) }) + const hub = new Hub({ + store, + now: () => clock.now, + newId: () => `m${++n}`, + pid: 1, + log, + ...(deliver ? { deliver } : {}), + probe: kind => (kind === 'claude' ? alive : undefined), + persistEndpoint: kind => kind === 'claude', + }) const call = (req: Exclude, conn = new FakeConn()): FakeConn => { hub.handle(req, conn) return conn @@ -905,3 +914,88 @@ describe('send by kind', () => { }) }) }) + +describe('leave by session and push liveness', () => { + it('unbinds a peer by session id, even after rename', () => { + const { call, listen, hub } = setup() + call({ op: 'claim', kind: 'claude', session: 'c1', folder: '/p/app' }) + call({ op: 'claim', kind: 'claude', session: 'c1', name: 'renamed', folder: '/p/app' }) + listen('renamed', 'claude', 'c1') + expect(hub.status().find(p => p.name === 'renamed')?.online).toBe(true) + call({ op: 'leave', session: 'c1' }) + const p = hub.status().find(p => p.name === 'renamed') + expect(p?.online).toBe(false) + expect(p?.session).toBeNull() + }) + + it('probePushers drops dead endpoints, keeps peer.session, respects cooldown, and honors persistEndpoint', async () => { + let ok = true + let probes = 0 + const store = memoryStore() + let n = 0 + const clock = { now: new Date('2026-11-02T00:00:00Z') } + const hub = new Hub({ + store, + now: () => clock.now, + newId: () => `m${++n}`, + pid: 1, + deliver: async () => {}, + probe: () => async () => { + probes++ + return ok + }, + persistEndpoint: kind => kind === 'claude', + }) + const call = (req: Exclude) => { + const c = new FakeConn() + hub.handle(req, c) + return c + } + call({ op: 'claim', kind: 'agy', session: 'a1', folder: '/p/app' }) + call({ op: 'push', kind: 'agy', session: 'a1', endpoint: { address: 'localhost:1234', token: 'secret' } }) + // agy endpoint is probed, never saved to disk. + expect(store.endpoints).toEqual([]) + expect(hub.status().find(p => p.name === 'app-agy')?.online).toBe(true) + + // Freshly registered endpoint skips probing within 3s cooldown. + expect(await hub.probePushers()).toBe(0) + expect(probes).toBe(0) + + clock.now = new Date(clock.now.getTime() + 4000) + expect(await hub.probePushers()).toBe(0) + expect(probes).toBe(1) + // Within 3s of the last successful probe: skipped. + expect(await hub.probePushers()).toBe(0) + expect(probes).toBe(1) + + // A single transient failure followed by success keeps the endpoint alive. + let calls = 0 + ok = true + const store2 = memoryStore() + const hub2 = new Hub({ + store: store2, + now: () => clock.now, + newId: () => `m${++n}`, + pid: 1, + deliver: async () => {}, + probe: () => async () => ++calls > 1, + }) + hub2.handle({ op: 'claim', kind: 'agy', session: 'a2', folder: '/p/app' }, new FakeConn()) + hub2.handle({ op: 'push', kind: 'agy', session: 'a2', endpoint: { address: 'localhost:1234', token: 'secret' } }, new FakeConn()) + // Without persistEndpoint, endpoints are never saved to disk even when probe is provided. + expect(store2.endpoints).toEqual([]) + clock.now = new Date(clock.now.getTime() + 4000) + expect(await hub2.probePushers()).toBe(0) + expect(calls).toBe(2) + expect(hub2.status().find(p => p.name === 'app-agy')?.online).toBe(true) + + ok = false + clock.now = new Date(clock.now.getTime() + 4000) + expect(await hub.probePushers()).toBe(1) + expect(probes).toBe(3) + const after = hub.status().find(p => p.name === 'app-agy') + expect(after?.online).toBe(false) + // Session stays bound so `agy --continue` can still drain queued mail and trigger REJOIN. + expect(after?.session).toBe('a1') + }) +}) diff --git a/src/daemon/hub.ts b/src/daemon/hub.ts index 65b1c49..ab4ce0e 100644 --- a/src/daemon/hub.ts +++ b/src/daemon/hub.ts @@ -11,6 +11,10 @@ const PRUNE_QUEUED_AFTER_MS = 7 * 24 * 3600_000 /** The bridge's own notices use this sender, so no peer may send as it, claim it or listen on it. */ const RESERVED = `"${BRIDGE_SENDER}" is reserved for notices from the bridge itself. Pick another name.` const PERSIST_SEEN_MS = 3600_000 +/** Minimum gap between on-demand push-endpoint liveness sweeps. */ +const PROBE_COOLDOWN_MS = 3_000 +/** Short pause before retrying a failed liveness probe so a transient stall does not drop direct delivery. */ +const PROBE_RETRY_DELAY_MS = 100 /** At most this many messages from the network wait per local peer. More are left with the sender's host. */ export const REMOTE_QUEUE_CAP = 50 @@ -86,10 +90,14 @@ export interface HubDeps { /** Pushes one message through an adapter's endpoint. Resolves once delivered. */ deliver?: (kind: PeerKind, endpoint: Record, msg: Message) => Promise /** - * The kind's check that an endpoint still reaches its session, or undefined. A kind with one holds no - * credential in its endpoints, so they are saved, and checked before they are restored after a restart. + * The kind's check that an endpoint still reaches its session, or undefined. */ probe?: (kind: PeerKind) => ((endpoint: Record) => Promise) | undefined + /** + * True when the kind's endpoints hold no credential and are safe to persist to disk. + * Defaults to `false` when omitted so credential-bearing endpoints are never written by mistake. + */ + persistEndpoint?: (kind: PeerKind) => boolean /** Told when the set of shared peers or their online state may have changed, so the link can publish it. */ net?: { changed(): void } } @@ -107,6 +115,8 @@ function redact(p: PeerStatus): PeerStatus { class PushConn implements Conn { closed = false readonly async = true + /** Last time this endpoint was registered, delivered to, or passed a liveness probe. */ + lastVerifiedAt: number constructor( private readonly hub: Hub, private readonly deliver: NonNullable, @@ -117,7 +127,9 @@ class PushConn implements Conn { /** Saved to disk, so it is restored after a daemon restart. */ readonly saved: boolean, private readonly onDrop: (conn: PushConn, why: string) => void, - ) {} + ) { + this.lastVerifiedAt = now().getTime() + } send(reply: Reply): void { if (reply.type !== 'msg') { @@ -126,7 +138,10 @@ class PushConn implements Conn { } const msg = reply.msg this.deliver(this.kind, this.endpoint, msg).then( - () => this.hub.handle({ op: 'ack', as: msg.to, id: msg.id }, this), + () => { + this.lastVerifiedAt = this.now().getTime() + this.hub.handle({ op: 'ack', as: msg.to, id: msg.id }, this) + }, (err: unknown) => this.onDrop(this, toError(err).message), ) } @@ -191,6 +206,7 @@ export class Hub { /** Outbox key to the id handed to the link and not yet acked. */ private readonly remoteInflight = new Map() private net: NetView | undefined + private probing: Promise | undefined constructor(private readonly deps: HubDeps) { const { peers, queues, endpoints } = deps.store.load() @@ -231,7 +247,8 @@ export class Hub { return refused ? this.fail(conn, refused) : this.reply(conn, { type: 'ok' }) } case 'leave': - this.leave(req.as) + if (req.as !== undefined) this.leave(req.as) + else if (req.session !== undefined) this.leaveBySession(req.session) return this.reply(conn, { type: 'ok' }) case 'share': { const refused = this.share(req.as, req.sessions, req.on) @@ -397,7 +414,7 @@ export class Hub { private push(kind: PeerKind, session: string, endpoint: Record, deliver: NonNullable, write: boolean): string | undefined { const old = this.pushers.get(session) if (old) this.dropPusher(old, false) - const saved = this.deps.probe?.(kind) !== undefined + const saved = Boolean(this.deps.persistEndpoint?.(kind)) let refused: string | undefined const conn = new PushConn(this, deliver, kind, this.deps.now, session, endpoint, saved, (c, why) => { refused ??= why @@ -753,6 +770,60 @@ export class Hub { } } + hasPushers(): boolean { + return this.pushers.size > 0 + } + + /** + * Probes registered push endpoints in parallel and drops any whose session is gone. + * Skips endpoints verified within PROBE_COOLDOWN_MS unless `force` is true, and deduplicates concurrent sweeps. + */ + async probePushers(force = false): Promise { + if (!this.pushers.size || !this.deps.probe) return 0 + if (this.probing) return this.probing + const now = this.deps.now().getTime() + const due = [...this.pushers.entries()].filter(([, conn]) => force || now - conn.lastVerifiedAt >= PROBE_COOLDOWN_MS) + if (!due.length) return 0 + const run = (async (): Promise => { + const checks = await Promise.all( + due.map(async ([session, conn]) => { + const probe = this.deps.probe?.(conn.kind) + if (!probe) return { session, conn, ok: true } + // Retry once after a short pause so a transient stall does not drop direct delivery. + let ok = await probe(conn.endpoint).catch(() => false) + if (!ok) { + await new Promise(r => setTimeout(r, PROBE_RETRY_DELAY_MS)) + ok = await probe(conn.endpoint).catch(() => false) + } + return { session, conn, ok } + }), + ) + const doneAt = this.deps.now().getTime() + let dropped = 0 + for (const { session, conn, ok } of checks) { + if (this.pushers.get(session) !== conn) continue + if (ok) { + conn.lastVerifiedAt = doneAt + continue + } + this.deps.log?.(`push endpoint for session ${sessionTag(session)} is gone: dropped.`) + this.dropPusher(conn) + dropped++ + } + return dropped + })().finally(() => { + this.probing = undefined + }) + this.probing = run + return run + } + + private leaveBySession(session: string): void { + const pusher = this.pushers.get(session) + if (pusher) this.dropPusher(pusher) + for (const p of this.boundTo(session)) this.leave(p.name) + } + private leave(name: string): void { const peer = this.peers.get(name) if (!peer) return diff --git a/src/daemon/server.ts b/src/daemon/server.ts index 489eef7..8b7ff5d 100644 --- a/src/daemon/server.ts +++ b/src/daemon/server.ts @@ -14,6 +14,8 @@ import { fileStore } from './store.js' import { onLines, writeLine } from '../lib/wire.js' const log = logger('daemon', { timestamps: true }) +/** Slow background liveness sweep so remote network members see offline presence without local `peers` calls. */ +const PROBE_INTERVAL_MS = 45_000 function socketConn(sock: net.Socket): Conn { return { @@ -37,6 +39,7 @@ export function runDaemon(): void { log, net: { changed: () => netService?.changed() }, probe: kind => ADAPTERS[kind].alive, + persistEndpoint: kind => Boolean(ADAPTERS[kind].persistEndpoint), deliver: async (kind, endpoint, msg) => { const deliver = ADAPTERS[kind].deliver if (!deliver) throw new Error(`${kind} has no push delivery.`) @@ -92,7 +95,12 @@ export function runDaemon(): void { ) .finally(() => conn.end()) } - hub.handle(parsed.data, conn) + const req = parsed.data + // Sweep in the background: the reply must not wait on a dead endpoint's timeout. The next call sees the result. + if (req.op === 'status' || (req.op === 'send' && req.toKind !== undefined)) { + hub.probePushers().catch((err: unknown) => log(`probe failed: ${toError(err).message}`)) + } + hub.handle(req, conn) }, line => log(`unparseable line: ${line.slice(0, 200)}`), ) @@ -108,6 +116,9 @@ export function runDaemon(): void { fs.chmodSync(SOCK, 0o600) log(`listening on ${SOCK} pid=${process.pid}`) }) + setInterval(() => { + if (hub.hasPushers()) void hub.probePushers(true) + }, PROBE_INTERVAL_MS).unref() process.on('SIGINT', exit) process.on('SIGTERM', exit) } diff --git a/src/lib/wire.ts b/src/lib/wire.ts index c27fd0b..ae7a9c2 100644 --- a/src/lib/wire.ts +++ b/src/lib/wire.ts @@ -1,4 +1,5 @@ import type { Readable, Writable } from 'node:stream' +import type { z } from 'zod' /** Calls `onValue` for each newline-delimited JSON value. Unparseable lines go to `onBadLine`. */ export function onLines(stream: Readable, onValue: (value: unknown) => void, onBadLine: (line: string) => void): void { @@ -34,3 +35,13 @@ export async function readStdin(): Promise { for await (const chunk of process.stdin) buf += String(chunk) return buf } + +/** Parses a hook's stdin (empty counts as `{}`) against `schema`. Undefined when it is not JSON or does not match. */ +export function parseHookInput(stdin: string, schema: S): z.infer | undefined { + try { + const parsed = schema.safeParse(stdin.trim() ? JSON.parse(stdin) : {}) + return parsed.success ? parsed.data : undefined + } catch { + return undefined + } +} diff --git a/src/paths.ts b/src/paths.ts index 8038640..6d6471d 100644 --- a/src/paths.ts +++ b/src/paths.ts @@ -7,6 +7,8 @@ export const HOME = process.env['AGENT_BRIDGE_HOME'] ?? path.join(os.homedir(), export const SOCK = path.join(HOME, 'bridge.sock') export const QUEUE_DIR = path.join(HOME, 'queue') export const PEERS_FILE = path.join(HOME, 'peers.json') +/** User preferences (auto-join mode and folders). */ +export const CONFIG_FILE = path.join(HOME, 'config.json') export const DAEMON_LOG = path.join(HOME, 'daemon.log') export const DAEMON_LOCK = path.join(HOME, 'daemon.lock') /** Push endpoints that hold no credential (Claude's inbox socket path), restored on daemon start. */ diff --git a/src/schema.ts b/src/schema.ts index 0a86935..375b054 100644 --- a/src/schema.ts +++ b/src/schema.ts @@ -87,6 +87,17 @@ export const Peer = z.object({ /** A push endpoint saved to disk so it survives a daemon restart. Only endpoints with no credential are saved. */ export const SavedEndpoint = z.object({ session: z.string().min(1), kind: PeerKind, endpoint: z.record(z.string(), z.string()) }) +/** Opt-in auto-join settings. Off by default. */ +export const AutoJoinConfig = z.object({ + enabled: z.boolean().default(false), + ignore: z.array(z.string().min(1)).default([]), +}) + +/** User settings saved in `~/.agent-bridge/config.json`. */ +export const BridgeConfig = z.object({ + autoJoin: AutoJoinConfig.default({ enabled: false, ignore: [] }), +}) + /** `agent-bridge net `, as sent to the daemon. */ export const NetCommand = z.discriminatedUnion('cmd', [ /** @@ -169,7 +180,10 @@ export const Request = z.discriminatedUnion('op', [ z.object({ op: z.literal('ack'), as: PeerName, id: z.string() }), z.object({ op: z.literal('drain'), session: z.string().min(1) }), z.object({ op: z.literal('ack-drained'), session: z.string().min(1), ids: z.array(z.string()) }), - z.object({ op: z.literal('leave'), as: PeerName }), + z.object({ op: z.literal('leave'), as: PeerName.optional(), session: z.string().min(1).optional() }).refine( + r => (r.as === undefined) !== (r.session === undefined), + 'leave needs exactly one of `as` or `session`.', + ), /** * Register a way to push messages into the session itself, e.g. agy's `agentapi send-message`. The endpoint * is adapter-defined and may hold a credential, so the daemon never shows it. It keeps it in memory only, @@ -279,6 +293,8 @@ export type PeerKind = z.infer export type Message = z.infer export type Peer = z.infer export type SavedEndpoint = z.infer +export type AutoJoinConfig = z.infer +export type BridgeConfig = z.infer export type PeerStatus = z.infer export type RemotePeer = z.infer export type NetworkStatus = z.infer diff --git a/test/e2e.test.ts b/test/e2e.test.ts index c351e47..38fa856 100644 --- a/test/e2e.test.ts +++ b/test/e2e.test.ts @@ -596,6 +596,23 @@ describe('install', () => { expect(fs.readlinkSync(npmLink)).toBe(path.relative(npmBin, fs.realpathSync(CLI))) }) + it('says the plugin was removed when the reinstall fails after a successful uninstall', () => { + const binDir = path.join(HOME, 'bin-lost') + const fakeClaude = path.join(HOME, 'fake-claude-lost') + // Uninstall succeeds, so a plugin was there. Install fails. + fs.writeFileSync(fakeClaude, '#!/bin/sh\n[ "$1 $2" = "plugin install" ] && { echo "boom" >&2; exit 1; }\nexit 0\n', { mode: 0o755 }) + const targets = { + PATH: '/usr/bin:/bin', + AGENT_BRIDGE_BIN_DIR: binDir, + AGENT_BRIDGE_CLAUDE_BIN: fakeClaude, + AGY_CONFIG_DIR: path.join(HOME, 'agy-lost'), + OPENCODE_CONFIG_DIR: path.join(HOME, 'opencode-lost'), + } + const output = run(['install'], targets) + expect(output).toMatch(/failed: boom/) + expect(output).toContain('Run `claude plugin install agent-bridge@agent-bridge` to restore it.') + }) + it('adds and removes only agent-bridge entries, idempotently', () => { const agyDir = path.join(HOME, 'agy') const binDir = path.join(HOME, 'bin') @@ -661,3 +678,63 @@ describe('network sharing', () => { expect(() => run(['net', 'share', 'net-coder'])).toThrow(/No agent session id/) }) }) + +describe('auto-join, auto-leave and liveness', () => { + it('toggles auto-join config, runs claude SessionStart/SessionEnd and agy SessionStart, and drops dead sockets on status', async () => { + const dir = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'ab-auto-'))) + const ignored = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'ab-ign-'))) + const runWithInput = (args: string[], input: string, extra: Record = {}) => + execFileSync(process.execPath, [CLI, ...args], { env: { ...env, ...extra }, input, encoding: 'utf8', cwd: dir }) + + expect(run(['auto-join'])).toMatch(/auto-join: off/) + expect(run(['auto-join', 'on'])).toMatch(/auto-join: on/) + expect(run(['auto-join', 'ignore', ignored])).toContain(ignored) + + // Claude SessionStart auto-joins in a non-ignored folder with a live inbox socket. + const sockPath = path.join(dir, 'inbox.sock') + const srv = net.createServer().listen(sockPath) + await new Promise(r => srv.once('listening', () => r())) + const claudeEnv = { CLAUDE_CODE_SESSION_ID: 'auto-c1', CLAUDE_CODE_MESSAGING_SOCKET: sockPath } + const startOut = runWithInput(['claude-session-start'], JSON.stringify({ session_id: 'auto-c1', cwd: dir }), claudeEnv) + expect(startOut).toContain('Auto-joined agent-bridge') + const joinedName = /Auto-joined agent-bridge as \\"([^\\"]+)\\"/.exec(startOut)?.[1] + expect(joinedName).toBeTruthy() + expect(status().peers.find(p => p.name === joinedName)?.online).toBe(true) + + // Ignored folder does not auto-join. + expect(runWithInput(['claude-session-start'], JSON.stringify({ session_id: 'auto-c2', cwd: ignored }), { CLAUDE_CODE_SESSION_ID: 'auto-c2', CLAUDE_CODE_MESSAGING_SOCKET: sockPath })).toBe('') + + // Antigravity SessionStart injects the join prompt for non-ignored folders. + const agyOut = JSON.parse(runWithInput(['agy-session-start'], JSON.stringify({ conversationId: 'auto-a1', cwd: dir }))) as { + injectSteps?: { userMessage: string }[] + } + expect(agyOut.injectSteps?.[0]?.userMessage).toContain('agent-bridge join --kind agy') + expect(JSON.parse(runWithInput(['agy-session-start'], JSON.stringify({ conversationId: 'auto-a2', cwd: ignored })))).toEqual({}) + + // Closing the Claude socket drops it offline automatically on the next status/peers sweep. + await new Promise(r => srv.close(() => r())) + fs.rmSync(sockPath, { force: true }) + await until(() => status().peers.find(p => p.name === joinedName)?.online === false, 'dead socket reaped') + + // Re-register with a fresh socket and verify SessionEnd unbinds it immediately. + const sock2 = path.join(dir, 'inbox2.sock') + const srv2 = net.createServer().listen(sock2) + await new Promise(r => srv2.once('listening', () => r())) + runWithInput(['claude-session-start'], JSON.stringify({ session_id: 'auto-c1', cwd: dir }), { + CLAUDE_CODE_SESSION_ID: 'auto-c1', + CLAUDE_CODE_MESSAGING_SOCKET: sock2, + }) + expect(status().peers.find(p => p.name === joinedName)?.online).toBe(true) + runWithInput(['claude-session-end'], JSON.stringify({ session_id: 'auto-c1' }), { CLAUDE_CODE_SESSION_ID: 'auto-c1' }) + const afterEnd = status().peers.find(p => p.name === joinedName) + expect(afterEnd?.online).toBe(false) + expect(afterEnd?.session).toBeNull() + await new Promise(r => srv2.close(() => r())) + + // Reset auto-join off so other tests stay unaffected. + expect(run(['auto-join', 'unignore', ignored])).not.toContain(ignored) + expect(run(['auto-join', 'off'])).toMatch(/auto-join: off/) + fs.rmSync(dir, { recursive: true, force: true }) + fs.rmSync(ignored, { recursive: true, force: true }) + }) +}) diff --git a/test/opencode-folders.test.ts b/test/opencode-folders.test.ts new file mode 100644 index 0000000..3fcf69d --- /dev/null +++ b/test/opencode-folders.test.ts @@ -0,0 +1,53 @@ +import fs from 'node:fs' +import os from 'node:os' +import path from 'node:path' +import { PassThrough } from 'node:stream' +import { afterAll, describe, expect, it } from 'vitest' +import { createPlugin, shouldAutoJoinFromFile, type Exec, type Spawn, type Tool } from '../src/adapters/opencode/plugin/agent-bridge.js' + +// Real folders and a symlink, so this lives in test/, not next to the unit. +const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'ab-ocfolders-'))) +afterAll(() => fs.rmSync(root, { recursive: true, force: true })) + +const proj = path.join(root, 'proj') +const link = path.join(root, 'proj-link') +fs.mkdirSync(proj) +fs.symlinkSync(proj, link) + +function homeWith(autoJoin: unknown): NodeJS.ProcessEnv { + const home = fs.mkdtempSync(path.join(root, 'home-')) + fs.writeFileSync(path.join(home, 'config.json'), JSON.stringify({ autoJoin })) + return { AGENT_BRIDGE_HOME: home } +} + +describe('opencode plugin folders', () => { + it('matches an ignore entry that is a symlink to the session folder', () => { + const env = homeWith({ enabled: true, ignore: [link] }) + expect(shouldAutoJoinFromFile(proj, env)).toBe(false) + expect(shouldAutoJoinFromFile(link, env)).toBe(false) + expect(shouldAutoJoinFromFile(path.join(root, 'elsewhere'), env)).toBe(true) + }) + + it('joins a session whose event directory is a symlink to the plugin folder', async () => { + const execs: string[][] = [] + const exec: Exec = async args => { + execs.push(args) + return 'Joined agent-bridge as "proj-opencode".' + } + const spawn: Spawn = () => ({ stdout: new PassThrough(), kill: () => {} }) + const tools: Tool[] = [] + const ctx = { + location: { directory: proj }, + tool: { transform: async (fn: (e: { add: (t: Tool) => void }) => void) => fn({ add: t => tools.push(t) }) }, + session: { prompt: async () => undefined }, + event: { + subscribe: async function* () { + yield { type: 'session.created', location: { directory: link }, data: { sessionID: 'ses_link' } } + }, + }, + } + await createPlugin({ exec, spawn, shouldAutoJoin: () => true }).setup(ctx) + await new Promise(r => setTimeout(r, 20)) + expect(execs).toEqual([['join', '--kind', 'opencode']]) + }) +})