agent-bridge-service 0.0.0-stage → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/CHANGELOG.md +207 -0
  2. package/LICENSE +21 -0
  3. package/README.md +521 -2
  4. package/README.zh-CN.md +498 -0
  5. package/assets/agent-icons/claude-code.svg +1 -0
  6. package/assets/agent-icons/codebuddy-cli.svg +35 -0
  7. package/assets/agent-icons/codex.svg +1 -0
  8. package/assets/agent-icons/ds-harness.svg +1 -0
  9. package/assets/agent-icons/gemini.svg +1 -0
  10. package/assets/agent-icons/grok-cli.svg +1 -0
  11. package/assets/agent-icons/kimi-code.svg +1 -0
  12. package/assets/agent-icons/mimo-code.svg +1 -0
  13. package/assets/agent-icons/minimax-code.svg +1 -0
  14. package/assets/agent-icons/opencode.svg +1 -0
  15. package/assets/agent-icons/qoder-cli-light.svg +1 -0
  16. package/assets/agent-icons/qoder-cli.svg +1 -0
  17. package/assets/agent-icons/trae-cli.svg +1 -0
  18. package/dist/adapters/agent-adapters.js +437 -0
  19. package/dist/adapters/agent-logos.js +40 -0
  20. package/dist/adapters/win-exec.js +25 -0
  21. package/dist/app/bootstrap.js +101 -0
  22. package/dist/app/service-gate.js +43 -0
  23. package/dist/app/session-log.js +7 -0
  24. package/dist/app/session.js +107 -0
  25. package/dist/app/task-dispatch.js +81 -0
  26. package/dist/cli/dispatch.js +42 -0
  27. package/dist/cli/flags.js +40 -0
  28. package/dist/cli/help.js +36 -0
  29. package/dist/cli/hold.js +15 -0
  30. package/dist/cli/meta.js +16 -0
  31. package/dist/cli/render.js +53 -0
  32. package/dist/cli.js +26 -0
  33. package/dist/commands/connect.js +20 -0
  34. package/dist/commands/daemon.js +13 -0
  35. package/dist/commands/logout.js +18 -0
  36. package/dist/commands/serve.js +65 -0
  37. package/dist/commands/services.js +89 -0
  38. package/dist/commands/status.js +16 -0
  39. package/dist/core/emitter.js +119 -0
  40. package/dist/core/errors.js +89 -0
  41. package/dist/core/redact.js +34 -0
  42. package/dist/core/scan.js +55 -0
  43. package/dist/core/task-supervisor.js +277 -0
  44. package/dist/infra/audit.js +54 -0
  45. package/dist/infra/auth.js +174 -0
  46. package/dist/infra/config.js +191 -0
  47. package/dist/infra/git.js +141 -0
  48. package/dist/infra/service-token.js +198 -0
  49. package/dist/protocol.js +144 -0
  50. package/dist/runner.js +37 -0
  51. package/dist/transport/bridge-client.js +139 -0
  52. package/dist/transport/control-plane.js +482 -0
  53. package/dist/transport/outbox.js +95 -0
  54. package/package.json +80 -4
package/README.md CHANGED
@@ -1,3 +1,522 @@
1
- # Temporary Holding Version
1
+ # agent-bridge-service
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Give a remote orchestration platform control of the AI agents installed on your machine — over a single
4
+ outbound WebSocket. No inbound ports, no reverse tunnels, no API keys leaving the host.
5
+
6
+ **English** · [简体中文](README.zh-CN.md)
7
+
8
+ 📚 **Documentation site (EN / 中文, with full-text search): <https://shaylanwu.github.io/agent-bridge/>**
9
+ — protocol reference, CLI reference, and two integration guides (platform builders / local programs).
10
+ Built from the same machine-readable contracts, so it cannot drift from the code.
11
+
12
+ ---
13
+
14
+ ## Overview
15
+
16
+ AI coding agents (Claude Code, Codex, Gemini CLI and friends) live on developers' laptops. A web platform
17
+ cannot inspect them: browsers are sandboxed and have no access to `PATH`, executable files or credential
18
+ stores. And a platform hosted elsewhere cannot reach a laptop behind NAT.
19
+
20
+ `agent-bridge-service` closes that gap. It runs on the machine that owns the CLIs, keeps an outbound
21
+ WebSocket to the platform, and answers three questions the platform can never answer on its own:
22
+
23
+ 1. **What is installed here?** — a real probe of the local `PATH` and common install locations.
24
+ 2. **Is it actually usable?** — distinguishes “installed”, “installed but missing credentials” and
25
+ “installed but broken”.
26
+ 3. **Can you run this for me?** — executes a whitelisted CLI in a guarded working directory and streams
27
+ the output back in real time.
28
+
29
+ The package is self-contained: its only runtime dependencies are `ws` and `smol-toml`, and it speaks a
30
+ small JSON protocol over HTTP + WebSocket.
31
+
32
+ ## Features
33
+
34
+ - **12 built-in adapters** — Claude Code, CodeBuddy CLI, Codex, DeepSeek Harness, Gemini CLI, opencode, Mimo Code,
35
+ Qoder CLI, Grok CLI, Kimi Code, MiniMax Code, Trae CLI.
36
+ - **Three-state probing** — `ready` / `installed without credentials` / `not installed`, plus a
37
+ `broken` flag when a binary exists but cannot execute (`--version` fails).
38
+ - **Zero inbound network** — the bridge dials out; the platform never connects into your network.
39
+ - **Binding without copy-pasting tokens** — localhost callback + PKCE S256, reusing the browser session
40
+ you already have. Device-code fallback for SSH/headless machines, `--token` for CI.
41
+ - **Guarded execution** — adapter whitelist, argument arrays (never a shell string), working-directory
42
+ validation, per-task timeout, graceful cancel (`SIGTERM` → 2 s → `SIGKILL`).
43
+ - **Streaming logs** — output is chunked at 4 KB and forwarded as it is produced; finished runs can be
44
+ replayed from the platform's history.
45
+ - **Resilient connection** — 15 s heartbeat, exponential backoff (1 s → 30 s), buffered status messages
46
+ replayed after reconnect.
47
+ - **Secrets stay put** — the bridge never reads or uploads API keys or credential files; it only reports
48
+ whether they exist.
49
+
50
+ ## Installation
51
+
52
+ ```bash
53
+ npm install -g agent-bridge-service
54
+ ```
55
+
56
+ Requirements: **Node.js ≥ 20** on macOS, Linux or Windows.
57
+
58
+ From source:
59
+
60
+ ```bash
61
+ git clone https://github.com/shaylanwu/agent-bridge.git
62
+ cd agent-bridge
63
+ npm ci
64
+ npm run build
65
+ npm link # exposes the `agent-bridge` command
66
+ ```
67
+
68
+ ## Usage
69
+
70
+ ```bash
71
+ # Bind this machine and keep the connection open (opens a browser to approve)
72
+ agent-bridge connect https://platform.example.com
73
+
74
+ # Headless / SSH: print a device code instead of opening a browser
75
+ agent-bridge connect https://platform.example.com --no-browser
76
+
77
+ # CI or scripted setup: use a device token issued by the platform
78
+ # (--device-id is optional; also read from AGENT_BRIDGE_DEVICE_ID)
79
+ agent-bridge connect https://platform.example.com --token=<device-token> --device-id=<device-id>
80
+
81
+ # Inspect the local toolchain only (no connection required)
82
+ agent-bridge status
83
+ agent-bridge status --json --fresh # --fresh bypasses the 30 s cache
84
+
85
+ # Remove the local device credentials
86
+ agent-bridge logout
87
+
88
+ # Issue a scoped service token for an external system / backend service (P0-8)
89
+ agent-bridge services issue --label=repair-orchestrator --scopes=task:create,task:cancel --ttl-days=90
90
+ agent-bridge services list
91
+ agent-bridge services rotate svc_9f1c2a --grace-hours=24 # rotate: old token stays valid for 24h
92
+ agent-bridge services revoke svc_9f1c2a
93
+ ```
94
+
95
+ > `agent-bridge daemon` is **not implemented yet** (Phase 3). Until it lands, keep `connect` running in the
96
+ > foreground under your own process manager (systemd / launchd / a Windows service wrapper).
97
+
98
+ With `--token` the bridge has no `deviceId` unless you pass `--device-id` or set `AGENT_BRIDGE_DEVICE_ID`
99
+ (resolution order: auth response → `--device-id` → env → saved config for the same platform URL). When it
100
+ resolves to nothing, the WS URL omits the `deviceId` query parameter instead of sending an empty one, and
101
+ `hello.deviceId` is an empty string — **the platform must then resolve the device from `Authorization: Bearer`**.
102
+ That is the normal case for CI runners that were never bound interactively.
103
+
104
+ Example `status` output:
105
+
106
+ ```
107
+ Tool Version Status
108
+ ──────────────────────────────────────────────────────────
109
+ Claude Code 2.1.282 ready
110
+ Codex 0.163.0 ready
111
+ DeepSeek Harness 0.1.5-rc.3 ready
112
+ Gemini CLI 0.64.0 no credentials
113
+ opencode 1.19.3 no credentials
114
+ Qoder CLI 1.1.75 ready
115
+ MiniMax Code - broken
116
+ Kimi Code - not installed
117
+
118
+ 11 tools scanned, 4 usable
119
+ ```
120
+
121
+ Configuration lives in `~/.agent-bridge/config.toml` (Windows: `%APPDATA%\agent-bridge\config.toml`)
122
+ with `0600` permissions. The device token is never printed in full.
123
+
124
+ Optional working-directory allow-list — confine task execution to specific directories:
125
+
126
+ ```toml
127
+ allowed_cwd = ["/Users/me/work", "/Users/me/repos"]
128
+ ```
129
+
130
+ When set, a `run_task` whose `cwd` is outside every listed directory fails before anything is spawned
131
+ (`{"status":"failed","error":"工作目录不在允许范围内:…"}`). Entries are resolved to absolute paths and
132
+ compared by directory boundary, so `/Users/me/work-old` is **not** covered by `/Users/me/work`. Omit the key
133
+ to keep the default behaviour (only "exists and is a directory" is checked).
134
+
135
+ How many tasks may run at the same time, and how many may wait — defaults 3 and 32:
136
+
137
+ ```toml
138
+ max_tasks = 3
139
+ max_queue = 32 # 0 = no queueing at all
140
+ ```
141
+
142
+ Tasks beyond `max_tasks` wait in a FIFO queue and start as slots free up; only when the queue is full does a new
143
+ task fail immediately (`任务队列已满(并发 N,排队 M)`). `timeoutMs` is measured **from queueing**, so a task can
144
+ never sit in the queue for hours and then run for ten more minutes. `AGENT_BRIDGE_MAX_TASKS` /
145
+ `AGENT_BRIDGE_MAX_QUEUE` override the file (handy for CI).
146
+
147
+ Whether a finished task carries a diff, and whether a service token is mandatory:
148
+
149
+ ```toml
150
+ diff_default = false # true = capture even when the platform did not ask for it
151
+ diff_max_bytes = 262144 # cap for the diff text (default 256 KB); AGENT_BRIDGE_DIFF_MAX_BYTES overrides
152
+ require_service_token = false # true = reject any task without a valid service token (off by default for compatibility)
153
+ ```
154
+
155
+ ## Security boundaries
156
+
157
+ | Concern | Behaviour |
158
+ | ---------------------- | -------------------------------------------------------------------------------------- |
159
+ | API keys / credentials | Never read, never uploaded. Only “present / absent” is reported. |
160
+ | What can be executed | Whitelisted agent kinds only; an unknown `agentType` is rejected locally. |
161
+ | How it is executed | Argument arrays, no shell interpolation (Windows `.cmd` shims are quoted explicitly). |
162
+ | Env from the platform | **Not accepted**: any `env` inside `run_task` is ignored; children always run with the bridge's own environment. |
163
+ | Concurrency | `max_tasks` (default 3) run at once; the rest queue FIFO up to `max_queue` (default 32), then fail. `timeoutMs` counts from queueing. |
164
+ | Local control plane | Optional extension, **off by default**; when enabled it binds loopback only, requires a scoped Bearer token, and never sends CORS headers. |
165
+ | Diff capture | One `git diff` per task, only when `captureDiff` is set; untracked paths are restored afterwards. Nothing is committed and the index is left as it was. |
166
+ | Service identity | Service tokens are stored as SHA-256 only and checked per scope; `cancel_task` needs `task:cancel`, holding `task:create` is not enough. |
167
+ | Where it runs | `cwd` must exist and be a directory; `allowed_cwd` (optional) confines it further. |
168
+ | Runaway processes | Every task has a timeout; cancel sends `SIGTERM`, then `SIGKILL` after 2 s. |
169
+ | Transport | `wss://` only; handshake authenticated with `Authorization: Bearer <device_token>`. |
170
+ | Token storage | `0600` file in the user's home; the platform stores only a SHA-256 hash. |
171
+ | Audit trail | `~/.agent-bridge/audit.jsonl` (`0600`, one JSON per line): id / scope / action / outcome only — never tokens or credentials. |
172
+ | Revocation | A revoked device is rejected on the next handshake (`4401`/`4403`, no reconnect loop). |
173
+
174
+ The bridge holds no privileges beyond the OS user that started it, and it opens **no inbound port**: the only
175
+ listeners are the short-lived `127.0.0.1` callback used during authorization and — if you explicitly enable it —
176
+ the loopback control plane, which is bound to `127.0.0.1` and never reaches the network.
177
+
178
+ ## Architecture
179
+
180
+ ```
181
+ ┌──────────────────────────┐ outbound WSS ┌────────────────────────┐
182
+ │ Your machine │ ───────────────────────────▶ │ Orchestration platform│
183
+ │ │ │ │
184
+ │ agent-bridge │ ◀── run_task / cancel / scan ──│ device registry │
185
+ │ ├─ auth (PKCE) │ ─── hello / agent_list / ───▶ │ task dispatch │
186
+ │ ├─ scan (adapters) │ task_log / task_status │ log storage │
187
+ │ ├─ runner (spawn) │ │ │
188
+ │ └─ config (~/.agent-…) │ optional: 127.0.0.1 callback │ │
189
+ └──────────────────────────┘ (authorization only) └────────────────────────┘
190
+ │
191
+ └── spawns ──▶ claude / codex / dsh / gemini / … (the user's own CLI and credentials)
192
+ ```
193
+
194
+ | Module | Responsibility |
195
+ | ----------------------- | ------------------------------------------------------------------------------------- |
196
+ The source tree is layered. Dependencies point **inwards only**:
197
+
198
+ ```
199
+ cli.ts → cli/ (flags · render · help · dispatch) → commands/ (one file per command)
200
+ → app/ (use-case orchestration) → { core, transport, adapters, infra }
201
+ ```
202
+
203
+ `core` (domain) sits in the middle; `transport` / `adapters` / `infra` are the three edges; only the entry point
204
+ and the wire contract stay at the root. `src/cli.ts` contains **no business logic** — it forwards argv to
205
+ `cli/dispatch.ts` and nothing else (548 → 31 lines on 2026-10-23).
206
+
207
+ | Module | Responsibility |
208
+ | ---------------------------- | ---------------------------------------------------------------------------------- |
209
+ | `src/cli.ts` | Entry point only: `argv → dispatch()` + top-level error guard |
210
+ | `src/cli/dispatch.ts` | Command registry (`COMMANDS`) — add a command here, not in the entry file |
211
+ | `src/cli/render.ts` | Terminal rendering: colors, tables, `out.{info,ok,warn,error}` |
212
+ | `src/cli/flags.ts` | Flag parsing (`--k=v`, `--flag`, positional) |
213
+ | `src/cli/help.ts` / `meta.ts`| Help text / package version read from `package.json` |
214
+ | `src/commands/*.ts` | One file per command; thin: parse flags → call `app/` → print |
215
+ | `src/app/session.ts` | Platform session: initial report, command routing, live task table |
216
+ | `src/app/task-dispatch.ts` | `run_task` / `cancel_task` orchestration (gate → spawn → upstream) |
217
+ | `src/app/service-gate.ts` | Service identity authorization + audit (P0-8) |
218
+ | `src/protocol.ts` | Wire contract — the single source of truth (wire types are only defined here) |
219
+ | `src/runner.ts` | v1 compatibility shim; new code should import `src/core/task-supervisor.ts` |
220
+ | `src/core/errors.ts` | Controlled error-code enum + `BridgeError` |
221
+ | `src/core/redact.ts` | Log redaction (home directory → `~`, long base64/hex runs folded) |
222
+ | `src/core/emitter.ts` | **Single upstream exit**: idempotency, redaction, audit, CloudEvents envelope |
223
+ | `src/core/task-supervisor.ts`| Task scheduling as an instantiable domain object (concurrency, queue, cancel) |
224
+ | `src/core/scan.ts` | Probe orchestration with a 30 s cache |
225
+ | `src/transport/bridge-client.ts` | Outbound WebSocket: handshake auth, heartbeat, backoff, offline queue |
226
+ | `src/transport/outbox.ts` | Bounded replay buffer for disconnects |
227
+ | `src/adapters/agent-adapters.ts` | Adapter table, binary resolution, version and credential probing |
228
+ | `src/adapters/win-exec.ts` | Correct quoting for Windows `.cmd` / `.bat` shims |
229
+ | `src/adapters/agent-logos.ts`| Brand icons as base64 data URIs |
230
+ | `src/infra/config.ts` | `config.toml` read/write with `0600`, token redaction |
231
+ | `src/infra/auth.ts` | Localhost callback server, PKCE S256, token exchange, device-code fallback |
232
+ | `src/infra/git.ts` | Worktree diff capture (read-only, bounded, never fails a task) |
233
+ | `src/infra/service-token.ts` | Scoped service tokens: issue / verify / rotate / revoke, SHA-256 only |
234
+ | `src/infra/audit.ts` | Audit trail (`audit.jsonl`, one JSON per line, redacted) |
235
+
236
+ Protocol (JSON over one connection):
237
+
238
+ | Direction | Messages |
239
+ | ----------------- | ----------------------------------------------------------------------- |
240
+ | bridge → platform | `hello`, `agent_list`, `scan_progress`, `scan_result`, `task_log`, `task_status`, `pong` |
241
+ | platform → bridge | `run_task`, `cancel_task`, `scan`, `ping` |
242
+
243
+ ### Capability negotiation (`hello.capabilities`)
244
+
245
+ `hello` carries `capabilities: string[]`, the **optional** features this device supports. A third-party platform
246
+ should degrade on this list rather than guessing from a CLI version:
247
+
248
+ | capability | Meaning |
249
+ | ---------------- | ------------------------------------------------------------------------- |
250
+ | `diff` | Supports `run_task.captureDiff` and a unified diff on the terminal status |
251
+ | `service-token` | Supports scoped service tokens plus `requestedBy` / `purpose` passthrough |
252
+ | `queue` | Tasks beyond the concurrency limit queue instead of being rejected |
253
+ | `scan-progress` | Streams `scan_progress` while probing |
254
+ | `cloud-events` | Can wrap upstream messages in a CloudEvents 1.0 envelope (CNCF standard) |
255
+
256
+ Evolution rule: a new optional field keeps the protocol version; a semantic change or a new required field bumps it.
257
+
258
+ ### Diff capture (P0-6)
259
+
260
+ When `run_task` carries `captureDiff: true`, the bridge takes one diff of `cwd` when the task **settles**
261
+ (success / failed / cancelled / timeout) and ships it with `task_status`:
262
+
263
+ ```json
264
+ { "type": "run_task", "taskId": "bt_7f3a", "agentType": "codex", "cwd": "/Users/me/work/api", "args": [], "prompt": "fix the failing login test", "captureDiff": true }
265
+ ```
266
+
267
+ ```json
268
+ { "type": "task_status", "taskId": "bt_7f3a", "status": "success", "exitCode": 0, "changedFiles": ["src/login.ts"], "diffTruncated": false }
269
+ ```
270
+
271
+ Constraints: a non-git directory yields an empty diff **without an error**; text beyond `diff_max_bytes`
272
+ (default 256 KB) is cut on a **line boundary** with `diffTruncated: true`; untracked files are `git add -N`-ed
273
+ for the duration of the capture and `git reset -q`-ed right after — **nothing is committed, the worktree is
274
+ untouched, and no intent-to-add entry is left behind**.
275
+
276
+ ### Service identity and scopes (P0-8)
277
+
278
+ Any external system (orchestrator backend, CI, IDE plugin) can call the task capabilities with a scoped service
279
+ token. Tokens look like `abs_<kid>_<secret>`; only the SHA-256 of `secret` is stored locally and comparison is
280
+ constant-time:
281
+
282
+ | scope | Allows |
283
+ | -------------- | --------------------------------- |
284
+ | `task:create` | sending `run_task` |
285
+ | `task:cancel` | sending `cancel_task` |
286
+ | `task:read` | reading task / scan results |
287
+ | `device:read` | reading the local tool list (`scan`) |
288
+
289
+ `run_task` / `cancel_task` may carry `requestedBy` (≤128 chars), `purpose` (≤64 chars) and `serviceToken`;
290
+ the bridge **echoes `requestedBy` on the terminal `task_status`** so the platform can persist `requested_by`.
291
+
292
+ Compatibility: with no token registered locally and `require_service_token = false`, behaviour is identical to
293
+ v1. **But if a message carries a token, it must verify** — there is no "present but skipped" path.
294
+
295
+ > **Checklist for the platform side** (auth on `/api/bridge/*` lives in the platform repo, not here):
296
+ > 1. accept a service token on `POST /api/bridge/tasks`, `GET /api/bridge/tasks/:id` and
297
+ > `POST /api/bridge/tasks/:id/cancel`, alongside the user token branch;
298
+ > 2. bind each service token to a project / user scope and answer 403 on cross-tenant access;
299
+ > 3. pass `requestedBy` through when sending `run_task`, and persist the echoed `requested_by` on
300
+ > `bridge_task_runs`.
301
+
302
+ ### Controlled error codes
303
+
304
+ `task_status.error` is a human-readable string (render it directly). `task_status.errorCode` is the
305
+ **controlled** code for programmatic branching, so a platform never has to match on prose:
306
+
307
+ | Code | Meaning |
308
+ | --- | --- |
309
+ | `tool_not_installed` | Kind unknown or the binary is missing on this host |
310
+ | `tool_no_credentials` | Installed but no credentials present |
311
+ | `tool_broken` | Installed but `--version` fails |
312
+ | `cwd_missing` / `cwd_not_allowed` | Working directory absent, or outside `allowed_cwd` |
313
+ | `device_busy` | Concurrency limit and queue both full |
314
+ | `timeout` / `cancelled` | Timed out (including while queued) / cancelled |
315
+ | `agent_error` | Non-zero CLI exit, or the process failed to start |
316
+ | `unauthorized` / `invalid_token` / `token_expired` / `insufficient_scope` | Service-token failures |
317
+ | `protocol_incompatible` / `internal` | Version mismatch / bridge-side fault |
318
+
319
+ The enum lives in `src/core/errors.ts` and is mirrored by `contracts/asyncapi-3.0.yaml`; `npm run contracts:check`
320
+ fails if the two drift.
321
+
322
+ ### Queueing semantics
323
+
324
+ Tasks beyond the concurrency limit queue instead of failing. To stay v1-compatible the `status` value stays
325
+ `running`; queued tasks additionally carry `phase: 'queued'` and `queuePosition` (1-based). A platform that
326
+ ignores both still behaves exactly as before. `timeoutMs` is measured **from queueing**, so a task can never
327
+ wait for hours and then run for ten more minutes.
328
+
329
+ ### Machine-readable contracts
330
+
331
+ Prose drifts; contracts are checked in CI.
332
+
333
+ | File | Describes |
334
+ | --- | --- |
335
+ | `contracts/asyncapi-3.0.yaml` | The WebSocket channel (both directions, every message, error codes) |
336
+ | `contracts/openapi-3.1.yaml` | The HTTP endpoints **a platform must implement** to drive this bridge |
337
+ | `llms.txt` | Entry points for AI clients |
338
+
339
+ `npm run contracts:check` verifies every wire type, capability, error code and platform endpoint in the code
340
+ is actually documented — drift fails the build.
341
+
342
+ ### Local control plane (optional, off by default)
343
+
344
+ `agent-bridge serve <platformUrl> [--port=8787]` is `connect` **plus** a loopback-only HTTP control plane.
345
+ It exists for **other programs on this machine** — IDE extensions, scripts, MCP servers, CI runners.
346
+ Remote platforms keep using the outbound WebSocket; this is a separate channel, not a replacement.
347
+
348
+ | Rule | Value |
349
+ | --- | --- |
350
+ | Bind | `127.0.0.1` / `::1` only — a non-loopback host is rejected at startup |
351
+ | Default | **off**. Enable with `[control_plane] enabled = true` in `config.toml`, or `--port` for this run only |
352
+ | Auth | scoped Bearer (`abs_<kid>_<secret>`, the same tokens as P0-8); `/v1/health` is the only open route |
353
+ | CORS | never sent — a browser script cannot call it silently |
354
+ | Scheduling | tasks go through the same `TaskSupervisor`, so `max_tasks` covers both channels |
355
+ | Upstream | control-plane tasks report through the same `Emitter`, so the platform view never half-disappears |
356
+
357
+ | Method | Path | Scope |
358
+ | --- | --- | --- |
359
+ | GET | `/v1/health` | — (liveness/readiness/version) |
360
+ | GET | `/v1/capabilities` | `device:read` |
361
+ | GET | `/v1/agents` | `device:read` |
362
+ | POST | `/v1/agents:scan` | `device:read` |
363
+ | POST | `/v1/tasks` | `task:create` |
364
+ | GET | `/v1/tasks` | `task:read` (cursor-paginated) |
365
+ | GET | `/v1/tasks/{id}` | `task:read` |
366
+ | POST | `/v1/tasks/{id}:cancel` | `task:cancel` (idempotent) |
367
+ | GET | `/v1/tasks/{id}/events` | `task:read` (SSE: log + status) |
368
+ | GET | `/v1/tasks/{id}/diff` | `task:read` (artifact only, task is not re-run) |
369
+
370
+ ```bash
371
+ agent-bridge services issue --label=vscode --scopes=task:create,task:read
372
+ curl --noproxy '*' -H "Authorization: Bearer abs_…" http://127.0.0.1:8787/v1/agents
373
+ curl --noproxy '*' -H "Authorization: Bearer abs_…" -H "Idempotency-Key: $(uuidgen)" \
374
+ -d '{"agentType":"codex","cwd":"/work/api","prompt":"fix the failing login test","captureDiff":true}' \
375
+ http://127.0.0.1:8787/v1/tasks
376
+ ```
377
+
378
+ Errors are RFC 9457 `application/problem+json` carrying the same `code` enum as the wire protocol, so a
379
+ client branches on `code` instead of matching prose. `Idempotency-Key` makes a retried `POST /v1/tasks` return
380
+ the same `taskId` instead of running twice. Contract: `contracts/openapi.control-plane.yaml`.
381
+
382
+ ### Live scan progress and brand icons
383
+
384
+ Probing 11 CLIs takes a few seconds, so results stream in instead of arriving as one batch: for every adapter
385
+ that finishes, the bridge sends `scan_progress` with the newly finished `items` and `done: false`; one final
386
+ `scan_progress` with `done: true` closes the probing phase, followed by the terminal list (`agent_list` on
387
+ connect, or `scan_result` carrying the same `requestId` when answering `scan`). A platform that ignores
388
+ `scan_progress` still gets the complete list.
389
+
390
+ Every item carries what a card needs: `display` (name), `version`, `status`, and `logo` — a
391
+ `data:image/svg+xml;base64,…` SVG on a uniform 24×24 canvas (artwork inset to 20×20, official brand colours
392
+ kept) taken from the brand marks in `assets/agent-icons/<kind>.svg`. The same logos repeat in each message
393
+ (~70 KB for all 12), so cache them by `kind` rather than re-parsing every frame. A missing asset just omits
394
+ the field.
395
+
396
+ ### Logs while the socket is down
397
+
398
+ `task_log` frames produced during a disconnect are buffered, not dropped: up to 256 KB of log frames per
399
+ disconnect (oldest dropped first, control messages kept in a separate bounded queue). On reconnect everything
400
+ is replayed in order. If the buffer overflowed, the replay starts with
401
+ `[agent-bridge] 断线期间日志超出缓冲上限(N KB),已丢弃较早部分`, so a gap is never silent.
402
+
403
+ ## Examples
404
+
405
+ **Bind a laptop and confirm the device is online**
406
+
407
+ ```bash
408
+ $ agent-bridge connect https://platform.example.com
409
+ [agent-bridge] starting device authorization…
410
+ [agent-bridge] browser opened; if nothing happens, visit:
411
+ https://platform.example.com/bridge/authorize?code_challenge=…
412
+ device bound: bd_9f1c… (credentials written to ~/.agent-bridge/config.toml)
413
+ [agent-bridge] connected
414
+ [agent-bridge] reported 11 tools, waiting for tasks…
415
+ ```
416
+
417
+ **Scan without connecting** (useful when filing a support ticket)
418
+
419
+ ```bash
420
+ $ agent-bridge status --json | jq -r '.agents[] | select(.status=="ready") | .display'
421
+ Claude Code
422
+ Codex
423
+ DeepSeek Harness
424
+ ```
425
+
426
+ **Let the platform run a task on this machine**
427
+
428
+ The platform sends:
429
+
430
+ ```json
431
+ {
432
+ "type": "run_task",
433
+ "taskId": "bt_7f3a",
434
+ "agentType": "codex",
435
+ "cwd": "/Users/me/work/api",
436
+ "args": [],
437
+ "prompt": "fix the failing login test"
438
+ }
439
+ ```
440
+
441
+ `args` is required by the protocol, even when you want the adapter's default argument template: send `"args": []`
442
+ and the bridge expands its own template (here `codex exec --json {{prompt}}`) with the `prompt` above.
443
+
444
+ The bridge validates the adapter and directory, spawns the CLI, and streams:
445
+
446
+ ```json
447
+ { "type": "task_log", "taskId": "bt_7f3a", "stream": "stdout", "data": "…", "isAnsi": true }
448
+ { "type": "task_status", "taskId": "bt_7f3a", "status": "success", "exitCode": 0 }
449
+ ```
450
+
451
+ **Unbind the machine**
452
+
453
+ ```bash
454
+ $ agent-bridge logout
455
+ local device credentials cleared (bd_9f1c…)
456
+ ```
457
+
458
+ ## Development
459
+
460
+ ```bash
461
+ npm ci
462
+ npm run build # tsc → dist/
463
+ npm test # unit tests (protocol, quoting, probing)
464
+ npm run typecheck
465
+ npm run dev status # run TypeScript directly via tsx
466
+ npm start # build, then run dist/ (same as a global install)
467
+ ```
468
+
469
+ Project layout:
470
+
471
+ ```
472
+ src/
473
+ cli.ts entry point — argv → cli/dispatch.ts, nothing else
474
+ protocol.ts wire contract (single source of truth)
475
+ runner.ts v1 compatibility shim → core/task-supervisor.ts
476
+ cli/ flags · terminal rendering · help · command registry
477
+ commands/ one file per command (connect/status/logout/services/daemon)
478
+ app/ use-case orchestration: session · task dispatch · service gate
479
+ core/ domain: scheduling · upstream emitter · redaction · errors · scan
480
+ transport/ outbound WebSocket + bounded offline replay
481
+ adapters/ 12 CLI adapters · Windows shim quoting · brand icons
482
+ infra/ config · auth · git diff · service tokens · audit
483
+ test/
484
+ bridge.test.ts unit tests
485
+ ```
486
+
487
+ Adding an adapter: append one entry to `AGENTS` in `src/adapters/agent-adapters.ts` (binary name, display name,
488
+ capability, task argument template, credential signals). No transport or scheduling changes are needed.
489
+
490
+ ### Releasing
491
+
492
+ Version numbers are decided by commit messages, not by hand. Merge a
493
+ [Conventional Commit](https://www.conventionalcommits.org/) into `main` and
494
+ [`.github/workflows/release.yml`](./.github/workflows/release.yml) does the rest:
495
+
496
+ | Commit | Bump |
497
+ | --- | --- |
498
+ | `feat: …` | minor |
499
+ | `fix: …` | patch |
500
+ | `feat!: …` / `BREAKING CHANGE:` | major — needs approval, and `PROTOCOL_VERSION` must be bumped in the same commit |
501
+ | `docs` `chore` `test` `refactor` `style` `ci` `build` | no release at all |
502
+
503
+ semantic-release then bumps `package.json`, writes `CHANGELOG.md`, tags `v<version>`, opens the GitHub Release
504
+ and publishes to npm. It needs two repository secrets: `AGENT_BRIDGE_NPM_TOKEN` (npm automation token) and the default
505
+ `GITHUB_TOKEN`. `commit-msg` runs commitlint locally, so a malformed message is rejected before it can
506
+ produce a wrong version.
507
+
508
+ **Never tag by hand** — a manual `v1.2.3` and a semantic-release tag will fight over the same version number.
509
+ The docs site (`.github/workflows/site.yml`) redeploys on every `main` push, and its changelog page is
510
+ rendered from the same `CHANGELOG.md` at build time — one source of truth, two places it shows up.
511
+ One wrinkle worth knowing: commits pushed with `GITHUB_TOKEN` don't trigger workflows, so `release.yml`
512
+ dispatches `site.yml` explicitly at the end; without that step the changelog page would lag one release behind.
513
+
514
+ Verify the release toolchain offline (no tokens, no network, nothing written to the repo):
515
+
516
+ ```bash
517
+ node scripts/verify-release.mjs # runs notes generation + CHANGELOG writing against the real v0.1.0..HEAD commits
518
+ ```
519
+
520
+ ## License
521
+
522
+ MIT — see [LICENSE](./LICENSE).