agent-bridge-service 0.2.3 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/CHANGELOG.md +122 -140
  2. package/README.md +526 -36
  3. package/README.zh-CN.md +457 -34
  4. package/assets/agent-icons/agy.svg +27 -0
  5. package/dist/adapters/acp-auth.js +51 -0
  6. package/dist/adapters/acp-codebuddy.js +507 -0
  7. package/dist/adapters/agent-adapters.js +470 -46
  8. package/dist/adapters/claude-stream.js +159 -0
  9. package/dist/adapters/codex-app-server.js +365 -0
  10. package/dist/adapters/host-env.js +48 -0
  11. package/dist/adapters/mcp-elicitation.js +148 -0
  12. package/dist/adapters/mcp-host.js +70 -0
  13. package/dist/adapters/step-parsers.js +583 -0
  14. package/dist/app/bootstrap.js +163 -74
  15. package/dist/app/claude-resident.js +204 -0
  16. package/dist/app/conversation.js +639 -0
  17. package/dist/app/service-gate.js +1 -1
  18. package/dist/app/session.js +426 -14
  19. package/dist/app/task-dispatch.js +883 -7
  20. package/dist/app/task-registry.js +168 -0
  21. package/dist/cli/dispatch.js +4 -0
  22. package/dist/cli/flags.js +11 -0
  23. package/dist/cli/help.js +26 -7
  24. package/dist/cli/panel.js +334 -0
  25. package/dist/cli/render.js +2 -0
  26. package/dist/commands/approvals.js +80 -0
  27. package/dist/commands/connect.js +124 -4
  28. package/dist/commands/daemon-service.js +81 -0
  29. package/dist/commands/daemon.js +269 -6
  30. package/dist/commands/logout.js +13 -10
  31. package/dist/commands/serve.js +100 -12
  32. package/dist/commands/sessions.js +106 -0
  33. package/dist/core/ansi.js +5 -0
  34. package/dist/core/artifact-extract.js +158 -0
  35. package/dist/core/artifact-transfer.js +583 -0
  36. package/dist/core/device-identity.js +22 -0
  37. package/dist/core/emitter.js +50 -8
  38. package/dist/core/errors.js +43 -0
  39. package/dist/core/form-schema.js +72 -0
  40. package/dist/core/interaction-broker.js +440 -0
  41. package/dist/core/interaction-url.js +63 -0
  42. package/dist/core/partial-messages.js +99 -0
  43. package/dist/core/permission-ledger.js +146 -0
  44. package/dist/core/permission-policy.js +88 -0
  45. package/dist/core/port-fallback.js +22 -0
  46. package/dist/core/redact.js +13 -0
  47. package/dist/core/scan.js +12 -7
  48. package/dist/core/session-store.js +1632 -0
  49. package/dist/core/task-supervisor.js +968 -30
  50. package/dist/infra/atomic-file.js +111 -0
  51. package/dist/infra/audit.js +7 -0
  52. package/dist/infra/auth.js +143 -40
  53. package/dist/infra/config.js +511 -72
  54. package/dist/infra/device-identity-store.js +87 -0
  55. package/dist/infra/jwt.js +149 -0
  56. package/dist/infra/profile-lock.js +295 -0
  57. package/dist/infra/proxy-env.js +81 -0
  58. package/dist/infra/service-token.js +25 -4
  59. package/dist/protocol.js +298 -2
  60. package/dist/transport/a2a-mapping.js +206 -0
  61. package/dist/transport/acp-gateway-mapping.js +186 -0
  62. package/dist/transport/bridge-client.js +31 -22
  63. package/dist/transport/control-plane-page.js +820 -0
  64. package/dist/transport/control-plane-sessions-page.js +90 -0
  65. package/dist/transport/control-plane.js +935 -71
  66. package/dist/transport/gateway.js +1023 -0
  67. package/dist/transport/office-preview.js +154 -0
  68. package/package.json +6 -3
  69. package/assets/agent-icons/gemini.svg +0 -1
package/README.md CHANGED
@@ -13,7 +13,7 @@ Built from the same machine-readable contracts, so it cannot drift from the code
13
13
 
14
14
  ## Overview
15
15
 
16
- AI coding agents (Claude Code, Codex, Gemini CLI and friends) live on developers' laptops. A web platform
16
+ AI coding agents (Claude Code, Codex, Antigravity CLI and friends) live on developers' laptops. A web platform
17
17
  cannot inspect them: browsers are sandboxed and have no access to `PATH`, executable files or credential
18
18
  stores. And a platform hosted elsewhere cannot reach a laptop behind NAT.
19
19
 
@@ -31,8 +31,8 @@ small JSON protocol over HTTP + WebSocket.
31
31
 
32
32
  ## Features
33
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.
34
+ - **12 built-in adapters** — Claude Code, CodeBuddy CLI, Codex, DeepSeek Harness, Antigravity CLI, opencode, Mimo Code,
35
+ Qoder CLI, Grok Build, Kimi Code, MiniMax Code, Trae CLI.
36
36
  - **Three-state probing** — `ready` / `installed without credentials` / `not installed`, plus a
37
37
  `broken` flag when a binary exists but cannot execute (`--version` fails).
38
38
  - **Zero inbound network** — the bridge dials out; the platform never connects into your network.
@@ -44,6 +44,10 @@ small JSON protocol over HTTP + WebSocket.
44
44
  replayed from the platform's history.
45
45
  - **Resilient connection** — 15 s heartbeat, exponential backoff (1 s → 30 s), buffered status messages
46
46
  replayed after reconnect.
47
+ - **Terminal task board** — `connect` / `serve` show a resident status table in a TTY (four-state dots,
48
+ current step per task, elapsed, capacity water level); task logs never scroll the main window. Per-task
49
+ logs live behind a button in the Web dashboard (address printed when `serve` starts the control plane),
50
+ streamed live over SSE while a task is running.
47
51
  - **Secrets stay put** — the bridge never reads or uploads API keys or credential files; it only reports
48
52
  whether they exist.
49
53
 
@@ -53,7 +57,7 @@ small JSON protocol over HTTP + WebSocket.
53
57
  npm install -g agent-bridge-service
54
58
  ```
55
59
 
56
- Requirements: **Node.js ≥ 20** on macOS, Linux or Windows.
60
+ Requirements: **Node.js 24.x** on macOS, Linux or Windows.
57
61
 
58
62
  From source:
59
63
 
@@ -75,7 +79,7 @@ agent-bridge connect https://platform.example.com
75
79
  agent-bridge connect https://platform.example.com --no-browser
76
80
 
77
81
  # CI or scripted setup: use a device token issued by the platform
78
- # (--device-id is optional; also read from AGENT_BRIDGE_DEVICE_ID)
82
+ # A stable ID must come from local state, --device-id, or AGENT_BRIDGE_DEVICE_ID
79
83
  agent-bridge connect https://platform.example.com --token=<device-token> --device-id=<device-id>
80
84
 
81
85
  # Inspect the local toolchain only (no connection required)
@@ -90,16 +94,27 @@ agent-bridge services issue --label=repair-orchestrator --scopes=task:create,tas
90
94
  agent-bridge services list
91
95
  agent-bridge services rotate svc_9f1c2a --grace-hours=24 # rotate: old token stays valid for 24h
92
96
  agent-bridge services revoke svc_9f1c2a
97
+
98
+ # Persistent approvals (1.0): only written when approval_ledger_enabled = true
99
+ agent-bridge approvals list # --all also shows revoked rows
100
+ agent-bridge approvals revoke ap_7c31f0d2a4b8 # stop auto-approving that fingerprint
101
+ agent-bridge approvals purge # drop expired rows
102
+
103
+ # Session history (1.0): the only producer of session_deleted (410) — close_session keeps history
104
+ agent-bridge sessions list # sessions + event range + last update
105
+ agent-bridge sessions purge --session=tk_9f1c2a # delete one terminated session
106
+ agent-bridge sessions purge --older-than=14 # delete terminated sessions idle for 14+ days
93
107
  ```
94
108
 
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).
109
+ > `agent-bridge daemon start <platformUrl>` / `stop` / `status` provides lightweight background management
110
+ > (detached process + PID + `daemon.log`). `install` / `uninstall` registers a per-user service: Linux
111
+ > systemd user, macOS LaunchAgent, or a Windows logon scheduled task. Both support `--dry-run`.
97
112
 
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.
113
+ With `--token`, the bridge must resolve a stable `deviceId` from `identity.toml`, the saved `config.toml`
114
+ mirror, `--device-id`, or `AGENT_BRIDGE_DEVICE_ID`. If no persisted, migratable, or explicit ID exists,
115
+ startup fails: the bridge never generates a random ID for a pre-issued token, sends an empty ID, or asks the
116
+ platform to reverse-lookup identity from Bearer. An explicit ID may migrate missing local state or confirm
117
+ the persisted ID; it cannot override a different identity that is already stored.
103
118
 
104
119
  Example `status` output:
105
120
 
@@ -108,18 +123,58 @@ Tool Version Status
108
123
  ──────────────────────────────────────────────────────────
109
124
  Claude Code 2.1.282 ready
110
125
  Codex 0.163.0 ready
111
- DeepSeek Harness 0.1.5-rc.3 ready
112
- Gemini CLI 0.64.0 no credentials
126
+ DeepSeek Harness 0.2.1-rc.2 ready
127
+ Antigravity CLI 1.5.9 ready
113
128
  opencode 1.19.3 no credentials
114
129
  Qoder CLI 1.1.75 ready
115
130
  MiniMax Code - broken
116
131
  Kimi Code - not installed
117
132
 
118
- 11 tools scanned, 4 usable
133
+ 12 tools scanned, 5 usable
119
134
  ```
120
135
 
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.
136
+ Credential evidence comes from environment variables, known credential files, or explicitly registered OS
137
+ keyring targets. For agy on Windows, the bridge checks `gemini:antigravity` and reports only
138
+ `credentialSource = "keyring:gemini:antigravity"`; it never reads or uploads the secret. Qoder uses
139
+ `~/.qoder/.auth/user` / `QODER_PERSONAL_ACCESS_TOKEN`. opencode accepts either the official
140
+ `~/.local/share/opencode/auth.json` login state or a custom provider apiKey configured in
141
+ `~/.config/opencode/opencode.json`. kimi probes the oauth state `~/.kimi-code/credentials/kimi-code.json`
142
+ and the custom-provider config `~/.kimi-code/config.toml`. minimax probes mcode's oauth state
143
+ `~/.minimax/auth/prod/cn/mcode-public/auth.json` and the provider config `~/.minimax/config.yaml`. Trae uses `TRAECLI_PERSONAL_ACCESS_TOKEN` or the exit
144
+ code of the official `traecli login status`; installation directories are not treated as credentials, and status
145
+ output is never reported. Note: trae-cli 0.121.3 ships no `login` subcommand — it authenticates through the OS
146
+ keyring written by the Trae IDE team/enterprise sign-in, or the PAT env above; without either, no model task can run.
147
+
148
+ For agy and codex, external requests use `AGENT_BRIDGE_EXTERNAL_PROXY` when set, otherwise Windows reads the
149
+ current user's system proxy; set it to `off` (or `none`) to inject nothing and connect directly. This avoids
150
+ Google API 502s when the WorkBuddy process proxy differs from the system proxy, and keeps codex's responses
151
+ WebSocket from stalling for ~113s on a direct route, without hardcoding a local port. agy declares ACP starting
152
+ at 1.5.9; older versions remain headless-only. First and resumed turns were verified, while permission/form
153
+ interactions that were not tested individually are not declared.
154
+
155
+ ### Stable device identity and local state
156
+
157
+ | State | POSIX | Windows |
158
+ | --- | --- | --- |
159
+ | Identity (source of truth) | `~/.agent-bridge/identity.toml` | `%APPDATA%\.agent-bridge\identity.toml` |
160
+ | Credentials, settings, identity mirror | `~/.agent-bridge/config.toml` | `%APPDATA%\.agent-bridge\config.toml` |
161
+
162
+ `identity.toml` stores the stable `deviceId`; `config.toml` keeps the same value only as a compatibility
163
+ mirror. State files are private to the current user (`0600` on POSIX and a restricted ACL on Windows), and
164
+ the device token is never printed in full. `AGENT_BRIDGE_CONFIG` points to a profile's `config.toml`; its
165
+ **parent directory is the profile**, so `identity.toml` and the other state files live beside it. Use a
166
+ different parent directory for each profile.
167
+
168
+ Reauthorization, switching authorization methods, and uninstalling/reinstalling the package do not change
169
+ the ID while this state directory is preserved. Deleting only `identity.toml` restores the same ID from the
170
+ config mirror. Deleting the entire profile (or both the identity and every migratable mirror) makes the next
171
+ interactive bind a new installation with a new ID. `logout` removes credentials but preserves identity and
172
+ settings; after revocation, run `logout` → `connect` to bind the same ID again.
173
+
174
+ The platform returns `409 device_bound_to_other_account` for an ID owned by another account and
175
+ `409 device_identity_ambiguous` for duplicate platform history. Both require a platform administrator;
176
+ the bridge never changes its ID to evade the conflict and never automatically merges devices or transfers
177
+ cross-account ownership.
123
178
 
124
179
  Optional working-directory allow-list — confine task execution to specific directories:
125
180
 
@@ -132,17 +187,216 @@ When set, a `run_task` whose `cwd` is outside every listed directory fails befor
132
187
  compared by directory boundary, so `/Users/me/work-old` is **not** covered by `/Users/me/work`. Omit the key
133
188
  to keep the default behaviour (only "exists and is a directory" is checked).
134
189
 
135
- How many tasks may run at the same time, and how many may wait — defaults 3 and 32:
190
+ How many tasks may run at the same time, and how many may wait — defaults 30 and 60:
136
191
 
137
192
  ```toml
138
- max_tasks = 3
139
- max_queue = 32 # 0 = no queueing at all
193
+ max_tasks = 30
194
+ max_queue = 60 # 0 = no queueing at all
140
195
  ```
141
196
 
142
197
  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
198
  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).
199
+ never sit in the queue for hours and then run for ten more minutes. Precedence: startup flags
200
+ `--max-tasks` / `--max-queue` (both `connect` and `serve`) > `AGENT_BRIDGE_MAX_TASKS` /
201
+ `AGENT_BRIDGE_MAX_QUEUE` > the config file > defaults.
202
+
203
+ **Permission mode** (`permissionMode`): the platform may ask for `default` or `full` per task — **whether it gets
204
+ it is a local decision**:
205
+
206
+ ```toml
207
+ permission_policy = "default" # default | allow-full | full
208
+ external_sandbox = false # only CodeBuddy's full mode requires this
209
+ ```
210
+
211
+ | permission_policy | omitted | requests default | requests full |
212
+ | --- | --- | --- | --- |
213
+ | `default` (default) | default | default | **denied** (`permission_policy_denied`) |
214
+ | `allow-full` | default | default | full when eligible |
215
+ | `full` | full | default | full when eligible |
216
+
217
+ `allow-full` / `full` also switch on **managed-argument mode**: the platform may only send empty `args`, and argv
218
+ comes entirely from the adapter template (non-empty args are denied outright). `full` only picks a different
219
+ argument set — it is **not** proof of OS privilege escalation, config isolation, or a sandbox. When a tool has no
220
+ verified full mapping, or CodeBuddy runs without `external_sandbox = true`, the request is rejected with
221
+ `permission_mode_unsupported` rather than silently downgraded to `default`. Startup flags
222
+ `--permission-policy=` / `--external-sandbox` override the config file for one session.
223
+
224
+ ### Per-agent capability matrix
225
+
226
+ `agent_list` describes every tool honestly — an omitted capability means **not verified**, never "assume it works":
227
+
228
+ | agentType | full argv | modes | continuation |
229
+ | --- | --- | --- | --- |
230
+ | `claude-code` | `--dangerously-skip-permissions` | headless | native `--resume` |
231
+ | `codebuddy-cli` | `-y` (+ fixed `CODEBUDDY_IS_SANDBOX=1`, needs `external_sandbox = true`) | headless, ACP | native `--resume` |
232
+ | `codex` | `--dangerously-bypass-approvals-and-sandbox` | headless | app-server thread |
233
+ | `ds-harness` | `--permission-mode danger-full-access --approval-policy never` | headless, ACP | native `--session-id` / ACP `session/resume` |
234
+ | `agy` | `--dangerously-skip-permissions` | headless, ACP | native `--conversation` / ACP session |
235
+ | `opencode` | `--auto` | headless, ACP | ACP session |
236
+ | `mimo-code` | `--dangerously-skip-permissions` | headless, ACP | ACP session |
237
+ | `qoder-cli` | `--dangerously-skip-permissions` | headless | native `--resume` |
238
+ | `grok-cli` | `--always-approve` | headless, ACP | native `--resume` / ACP session |
239
+ | `kimi-code` | *(none — `-p` already runs auto)* | headless, ACP | ACP session |
240
+ | `minimax-code` | `--permission full` | headless, ACP | ACP session |
241
+ | `trae-cli` | `--yolo` | headless, ACP | ACP session |
242
+
243
+ ACP mode is always `default` (it uses native permission prompts instead of a bypass flag), so a `full` request
244
+ is either served by headless or rejected — never silently downgraded. agy uses a dedicated full template that
245
+ places the flag before `-p`, keeping the prompt as the final argv item. Full conversations use managed headless
246
+ with full canonical-transcript replay; default `send_message` turns resume through the channel above and replay
247
+ only when no continuation channel is available.
248
+
249
+ Two internal channels are **not** separately requestable modes, because the bridge picks the channel itself
250
+ (`run_task` has no `executionMode` field): codex conversations run over app-server `thread/resume`, and
251
+ Claude conversations over a resident stream-json process; Qoder uses headless with native `--resume`. They are described in the table instead of
252
+ being encoded as `executionMode` values, and each is at least as capable as the continuation declared for the
253
+ mode it replaces — the declaration never overstates. ACP `native-session` for the seven agents without local
254
+ credentials rests on the ACP spec plus the `codebuddy`/`ds-harness` probes, not on per-tool measurement; if an
255
+ agent rejects both `session/load` and `session/resume`, the turn opens a new session **with the full transcript
256
+ as its first prompt** — never a fresh session that silently lost the history.
257
+
258
+ `AgentListItem.capability` (`non_interactive` / `interactive_only`) is a 0.x display label kept for old
259
+ platforms — most `interactive_only` entries do run headless here. **Treat `executionModes` as
260
+ authoritative** and use `capability` only for copy.
261
+
262
+ ### `executionModes` field format
263
+
264
+ Each entry describes one execution mode of one agent. Absent field = "headless only, capability identical
265
+ to the legacy label"; every dimension is reported **per mode** because a tool's headless and ACP behaviour
266
+ differ:
267
+
268
+ | field | values | meaning |
269
+ | --- | --- | --- |
270
+ | `mode` | `headless`, `acp-stdio` | how the task is executed |
271
+ | `permissionModes` | `default`, `full` | permission modes this mode can actually serve; if `full` is missing, a `full` request is rejected before spawn (`permission_mode_unsupported`) — never downgraded |
272
+ | `interactionKinds` | `permission`, `form`, `auth-url` | interaction kinds this mode can relay; `[]` is a hard "cannot ask", not "unknown" — do not wait for a question |
273
+ | `feedKinds` | `messages`, `steps`, `artifacts` | canonical feed dimensions actually extracted in this mode |
274
+ | `continuation` | `native-session`, `resume-session`, `replay-session`, `single-turn` | how a later turn reattaches to this session: the agent holds it (`session/load`, `session/resume`, app-server `thread/resume`), a CLI resume flag reattaches it, the full persisted transcript is replayed as the prompt, or the CLI cannot take a follow-up at all. Every tool here is at least `replay-session`; `single-turn` would make `sessionMode = conversation` fail at creation with `session_not_continuable` instead of being accepted and then failing |
275
+
276
+ `capabilities` in `hello` is build-level ("this binary can do it"), `execution` is machine-level policy
277
+ ("this install allows it"), `executionModes` is per-agent ("this tool, in this mode, really can"). The
278
+ platform needs all three to pick a combination that will not fail mid-task.
279
+
280
+ **Interactions (permission prompts / forms / auth URLs) are off by default.** While off, the bridge never
281
+ sends a `task_interaction_request`; upstream sees no answer and settles the request as declined/cancelled —
282
+ which beats making the platform wait for a question that will never arrive:
283
+
284
+ ```toml
285
+ interaction_enabled = false # true to allow interaction round-trips
286
+ interaction_timeout_ms = 900000 # per-wait cap (15 min default, clamped 10s–2h)
287
+ max_interactions_per_task = 16 # per-task interaction budget (16 default, clamped 1–256)
288
+ ```
289
+
290
+ An adapter-supplied `expiresAt` is capped by `interaction_timeout_ms` (the tighter value wins); requests
291
+ beyond the budget are dropped and logged rather than forwarded. Flags `--interaction-enabled` /
292
+ `--interaction-timeout-ms=` / `--max-interactions-per-task=` override for one session.
293
+
294
+ `hello.execution` reports the effective local policy (`permissionPolicy`, `externalSandbox`,
295
+ `interactionEnabled`, `interactionTimeoutMs`, `maxInteractionsPerTask`, `approvalLedgerEnabled`) so the
296
+ platform can decide whether to ask for full and whether to expect interactions at all.
297
+
298
+ **Persistent approvals are off by default** and only start from a human answer:
299
+
300
+ ```toml
301
+ approval_ledger_enabled = false # true to remember "always allow" answers
302
+ approval_ttl_ms = 604800000 # 7 days (clamped 1 min – 90 days)
303
+ ```
304
+
305
+ When on, an interactive `allow_always` answer is stored with tenant/principal/agent/tool/resource/scope and
306
+ an expiry — but **only if the responder holds `approval:persist` in addition to `task:approve`**; without it
307
+ the answer still applies to the current session, it is just not remembered (audited as `approval_grant`
308
+ with `outcome=denied`). Later requests are auto-approved **only** when all three hold: the mode is
309
+ `default`, the request really offers a persistent allow option, and the fingerprint (agent + tool kind +
310
+ normalized resource) matches an unexpired record. `full` mode never uses the ledger, and model text or tool
311
+ titles never create or widen an approval. A request with no normalizable resource (no location, command or
312
+ URL in its `toolCall`) is **never** auto-approved and never written to the ledger — otherwise one approval
313
+ would silently cover every unnamed call of that tool. Inspect and revoke with `agent-bridge approvals list` /
314
+ `agent-bridge approvals revoke <approvalId>` (audited as `approval_hit` / `approval_revoke`).
315
+
316
+ **Event history is bounded by count, not by age**, so a long conversation cannot grow the state DB forever:
317
+
318
+ ```toml
319
+ event_retention_max_events = 5000 # per-session event cap (0 = keep everything, ceiling 1000000)
320
+ ```
321
+
322
+ Trimming is lazy — every 100th appended event trims the session back to the newest
323
+ `event_retention_max_events` rows. The high-water mark is persisted, so `eventSeq` stays monotonic and a
324
+ number is never re-issued after its row was reclaimed. Only events are trimmed: turns, artifacts and
325
+ interactions are the evidence that the task happened and stay. `--event-retention-max-events=` overrides for
326
+ one session.
327
+
328
+ **On top of count-based retention, the canonical feed is bounded per task** (default policy, not a hard
329
+ product limit — tune or disable per dimension via the `[feed]` section):
330
+
331
+ ```toml
332
+ [feed]
333
+ max_messages = 200 # newest task_message events kept per session (0 = off)
334
+ max_steps = 200 # newest task_step events (0 = off)
335
+ max_artifacts = 50 # newest task_artifact events (0 = off)
336
+ task_max_bytes = 4194304 # payload byte budget per session (0 = off)
337
+ global_max_bytes = 67108864 # payload byte budget across the whole DB (0 = off)
338
+ ```
339
+
340
+ Omit the section to take the defaults shown above; set a dimension to `0` to disable just that dimension.
341
+ Eviction always keeps the newest terminal `task_status` and the newest event of every session (pending
342
+ interactions live in their own table and are never touched). An in-window eviction is reported explicitly:
343
+ `eventWindow.gaps` entries carry `reason: count | task_bytes | global_bytes`, and prefix deletions advance
344
+ `prunedThrough` (so old cursors get `session_history_pruned` instead of a silent hole).
345
+
346
+ **The state DB runs `PRAGMA quick_check` when it is opened** (`SessionStore`'s `integrityCheck`, on by
347
+ default, can be disabled). Not for tidiness: a corrupt SQLite file usually **opens fine** and even reads its
348
+ schema, then fails on a page read halfway through a task — the crime scene is "task failed with an internal
349
+ error", which is nearly impossible to diagnose. The check moves that to startup: a failing database refuses to
350
+ start, and the bridge never silently degrades to an in-memory store. Measured on a 22 MB database: ~19 ms
351
+ with the check, 1.7 ms without. Be precise about what it buys: `quick_check` catches **structural** damage
352
+ (page headers, b-tree, indexes); bytes flipped inside a text value are not validated. Re-check any time with
353
+ `GET /v1/health?integrity=quick`, which returns `db: { ok, detail? }`.
354
+
355
+ `get_task` therefore has three cursor shapes, and they mean different things:
356
+
357
+ | request | returns | use it for |
358
+ | --- | --- | --- |
359
+ | no cursor | the newest `limit` events (tail) | rebuilding current state after a reload |
360
+ | `afterEventSeq` | ascending events **strictly after** the cursor | filling a gap after a reconnect |
361
+ | `beforeEventSeq` | the newest `limit` events **strictly before** the cursor, ascending | paging history backwards |
362
+
363
+ **Half-finished text travels in `partialMessages`**, not in events. Assistant text is normally persisted
364
+ only once, as a `state: "complete"` `task_message` at the end of the turn, so a reload mid-turn would show
365
+ nothing at all. The snapshot therefore carries the assistant text accumulated so far, per turn, with a
366
+ `pm_<taskId>` id (deliberately not a `msg_*` idempotency key) and a 32 KiB cap (`truncated` once hit). It is
367
+ **memory only and never written to SQLite**: streaming chunks are token-sized, persisting them would drown the
368
+ event table and let retention evict real events. The buckets are cleared when the turn settles, so after a
369
+ terminal status read the `complete` message from events instead. Adapters with no streaming text channel
370
+ (headless) simply return nothing — an honest gap, not a bug.
371
+
372
+ Note the asymmetry: the bridge does **not** push `task_message` frames with `state: "delta"` today. Live
373
+ streaming is only exposed as `task_log` chunks plus `task_step`; `partialMessages` in the snapshot is the
374
+ only canonical, structured view of in-flight text. Treat `delta` as reserved rather than something to wait for.
375
+
376
+ `hasMoreBefore` tells you whether anything exists before the returned window (the tail page sets it to
377
+ `true` on a long session). When a cursor points into reclaimed history, `get_task` still answers
378
+ `found: true` but adds `errorCode: "session_history_pruned"` plus `prunedThrough`, meaning "the older part is
379
+ gone, this is where retention starts" — not "the task ended there". Supplying both `afterEventSeq` and
380
+ `beforeEventSeq` is rejected with `protocol_incompatible` instead of silently picking one. Closed sessions
381
+ stay readable after `close_session`; only deleted ones answer `session_deleted` (410), and only
382
+ `agent-bridge sessions purge` deletes: `task_not_found` means the id never existed, `session_deleted` means
383
+ give up and stop retrying.
384
+
385
+ ACP: `codebuddy-cli`, `ds-harness`, `agy`, `opencode`, `mimo-code`, `kimi-code`, `minimax-code`,
386
+ `grok-cli`, and `trae-cli` declare native ACP and prefer it for tasks/conversations. `ds-harness` is
387
+ automation-only on that channel: it announces `permission` nowhere (tools run without asking, so its
388
+ `executionModes` declares an empty `interactionKinds`) and continues sessions through its own
389
+ `session/resume` rather than the standard `session/load`. `codex` uses the
390
+ `codex app-server` JSON-RPC surface (thread/resume, turn/steer, approvals); Claude
391
+ conversations keep a resident `stream-json` process across turns; Qoder uses headless with native `--resume`.
392
+ CodeBuddy prefers an explicit `CODEBUDDY_AUTH_TOKEN`; otherwise the bridge reads the plaintext
393
+ `auth/*.info` from the local CodeBuddyExtension and injects it into the ACP child. If neither exists it
394
+ keeps headless `codebuddy -p` and never starts an unauthenticated ACP child.
395
+
396
+ Re-sending a `run_task` with the same `taskId` is safe: the bridge is idempotent by `taskId` —
397
+ a live task gets a current-state snapshot, a settled task replays its terminal snapshot, and nothing
398
+ is spawned twice. The platform also gets a live water level: `hello.capacity` carries the effective
399
+ caps, and every scheduling change pushes a `capacity_update { running, queued, maxTasks, maxQueued }`.
146
400
 
147
401
  Whether a finished task carries a diff, and whether a service token is mandatory:
148
402
 
@@ -150,6 +404,15 @@ Whether a finished task carries a diff, and whether a service token is mandatory
150
404
  diff_default = false # true = capture even when the platform did not ask for it
151
405
  diff_max_bytes = 262144 # cap for the diff text (default 256 KB); AGENT_BRIDGE_DIFF_MAX_BYTES overrides
152
406
  require_service_token = false # true = reject any task without a valid service token (off by default for compatibility)
407
+ session_idle_ms = 0 # close waiting_user sessions after this idle time (0=off; AGENT_BRIDGE_SESSION_IDLE_MS overrides)
408
+
409
+ # Local MCP server host (stdio). Platform Form still needs an MCP proxy or ACP extension channel.
410
+ [mcp.servers.echo]
411
+ command = "node"
412
+ args = ["mcp-server.js"]
413
+ cwd = "."
414
+ [mcp.servers.echo.env]
415
+ NODE_ENV = "production"
153
416
  ```
154
417
 
155
418
  ## Security boundaries
@@ -160,8 +423,8 @@ require_service_token = false # true = reject any task without a valid service t
160
423
  | What can be executed | Whitelisted agent kinds only; an unknown `agentType` is rejected locally. |
161
424
  | How it is executed | Argument arrays, no shell interpolation (Windows `.cmd` shims are quoted explicitly). |
162
425
  | 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. |
426
+ | Concurrency | `max_tasks` (default 30) run at once; the rest queue FIFO up to `max_queue` (default 60), then fail. `timeoutMs` counts from queueing. |
427
+ | Local control plane | `connect` starts the Web panel on `127.0.0.1:8787` by default (falls forward if occupied); loopback only, scoped Bearer required, no CORS headers. |
165
428
  | 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
429
  | 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
430
  | Where it runs | `cwd` must exist and be a directory; `allowed_cwd` (optional) confines it further. |
@@ -188,7 +451,7 @@ the loopback control plane, which is bound to `127.0.0.1` and never reaches the
188
451
  │ └─ config (~/.agent-…) │ optional: 127.0.0.1 callback │ │
189
452
  └──────────────────────────┘ (authorization only) └────────────────────────┘
190
453
  │
191
- └── spawns ──▶ claude / codex / dsh / gemini / … (the user's own CLI and credentials)
454
+ └── spawns ──▶ claude / codex / dsh / agy / … (the user's own CLI and credentials)
192
455
  ```
193
456
 
194
457
  | Module | Responsibility |
@@ -235,10 +498,14 @@ and the wire contract stay at the root. `src/cli.ts` contains **no business logi
235
498
 
236
499
  Protocol (JSON over one connection):
237
500
 
501
+ | Protocol | Handshake | Bridge release |
502
+ | --- | --- | --- |
503
+ | **v1** | `PROTOCOL_VERSION = 1` (`hello.protocolVersion = 1`); `deviceId` is a non-empty stable ID matching the WS URL query | **1.0.0** (Session/Turn gateway baseline) |
504
+
238
505
  | Direction | Messages |
239
506
  | ----------------- | ----------------------------------------------------------------------- |
240
- | bridge → platform | `hello`, `agent_list`, `scan_progress`, `scan_result`, `task_log`, `task_status`, `pong` |
241
- | platform → bridge | `run_task`, `cancel_task`, `scan`, `ping` |
507
+ | bridge → platform | `hello`, `agent_list`, `scan_progress`, `scan_result`, `task_log`, `task_status`, `task_step`, `task_message`, `task_artifact`, `task_snapshot`, `artifact_content`, `session_ack`, `message_ack`, `task_interaction_request`, `task_interaction_result`, `interaction_url`, `artifact_upload_ready`, `artifact_upload_chunk_ack`, `artifact_upload_result`, `artifact_download_ready`, `artifact_download_chunk`, `artifact_download_result`, `artifact_transfer_status`, `capacity_update`, `pong` |
508
+ | platform → bridge | `run_task`, `send_message`, `task_interaction_response`, `get_interaction_url`, `get_artifact`, `artifact_upload_start`, `artifact_upload_chunk`, `artifact_upload_complete`, `artifact_download_start`, `artifact_download_chunk_ack`, `artifact_transfer_status`, `artifact_transfer_abort`, `cancel_task`, `close_session`, `cancel_turn`, `get_task`, `scan`, `ping` |
242
509
 
243
510
  ### Capability negotiation (`hello.capabilities`)
244
511
 
@@ -252,6 +519,51 @@ should degrade on this list rather than guessing from a CLI version:
252
519
  | `queue` | Tasks beyond the concurrency limit queue instead of being rejected |
253
520
  | `scan-progress` | Streams `scan_progress` while probing |
254
521
  | `cloud-events` | Can wrap upstream messages in a CloudEvents 1.0 envelope (CNCF standard) |
522
+ | `capacity` | `hello.capacity` advertises the caps; `capacity_update` streams the water level on every scheduling change |
523
+ | `task-step` | Structured agents stream `task_step` (dynamic step flow; grading below) |
524
+ | `task-message` | Emits canonical final-answer `task_message` frames with eventSeq |
525
+ | `task-snapshot` | Supports `get_task` / `task_snapshot` replay by eventSeq |
526
+ | `session-control`| Supports `close_session` / `cancel_turn` with `session_ack` |
527
+ | `session-multi-turn` | Supports `send_message` / `message_ack`; conversation stays in waiting_user between turns |
528
+ | `session-feed` | `task_message` / `task_step` / `task_artifact` share one `eventSeq` feed across turns; `get_task` fills gaps and pages history — no need to parse `task_log` |
529
+ | `task-interaction` | Permission/Form/URL requests, responses, results and expiry |
530
+ | `elicitation-form` | Relays agent form requests (`session/request_form` and ACP `elicitation/create`) and returns the structured answer |
531
+ | `artifact-upload` | Inbound chunked upload with SHA-256, CAS and task_artifact |
532
+ | `artifact-download` | Chunked download from CAS (ready/chunk/ack/result) |
533
+ | `interaction-url` | `get_interaction_url`; URLs kept in process memory with a short TTL |
534
+ | `permission-mode` | `run_task.permissionMode` is understood (local `permission_policy` can still deny it) |
535
+ | `artifact-inline` | `get_artifact` can inline artifact content (over 1 MB returns `too_large`; use chunked download) |
536
+ | `approval-ledger` | Persistent approvals: an interactive "always allow" can be remembered (default mode, fingerprint match, expiry) and revoked with `agent-bridge approvals revoke` |
537
+
538
+ ### Step stream (`task_step`)
539
+
540
+ Agents with structured event output stream a **dynamic step flow** (`seq` increments, `ref` pairs
541
+ started/finished, `label` redacted and truncated). Steps are decided by the model at runtime — there
542
+ is no predefined total count; the platform renders "steps so far + current step". Capability is graded
543
+ per agent and reported honestly via `steps: true/false` in `agent_list`:
544
+
545
+ | Grade | Agents | Behaviour |
546
+ | --- | --- | --- |
547
+ | Structured (`steps: true`) | all 12 agents | Steps parsed from JSONL event streams (7 format families: claude-style ×5, opencode-style ×2, codex / agy / kimi / dsh / minimax) |
548
+ | Plain text (`steps: false`) | none | Kept for future agents without structured output |
549
+
550
+ ⚠️ Behaviour change: `task_log` for claude-code / codebuddy-cli / kimi-code / qoder-cli / trae-cli /
551
+ ds-harness / minimax-code switches from plain text to the **stream-json event stream** (richer;
552
+ `task_step` provides the structured view). codex / opencode / mimo-code / grok-cli / agy were
553
+ already JSONL.
554
+
555
+ **Rich `toolCall` (optional field)**: steps may carry a normalized tool-call subset —
556
+ `toolCallId` / `name` / `kind` (ACP's `read|edit|delete|move|search|execute|think|fetch|switch_mode|other`)
557
+ / `title` / `status` / `locations` (paths) / `content` (bounded `text|diff|terminal` blocks, 16 KB per
558
+ block, redacted at the upstream exit). `rawInput` / `rawOutput` are **never** shipped; adapters that
559
+ cannot extract a call reliably omit the field and keep the legacy ones. Sources today: ACP `tool_call`
560
+ updates (native fields) and the claude-style parser family (tool-name → kind mapping + `file_path`/`path`
561
+ locations + `tool_result` output as a terminal block).
562
+
563
+ **Intermediate agent messages**: assistant text blocks inside headless structured output become canonical
564
+ `task_message` events (`state: "complete"`, one per assistant message, CLI-native `messageId` where the
565
+ CLI provides one) instead of being buried in `task_log`. Thinking blocks stay out; streaming deltas keep
566
+ using the in-memory `partialMessages` channel.
255
567
 
256
568
  Evolution rule: a new optional field keeps the protocol version; a semantic change or a new required field bumps it.
257
569
 
@@ -273,6 +585,23 @@ Constraints: a non-git directory yields an empty diff **without an error**; text
273
585
  for the duration of the capture and `git reset -q`-ed right after — **nothing is committed, the worktree is
274
586
  untouched, and no intent-to-add entry is left behind**.
275
587
 
588
+ **Changed files become artifact metadata events (4.9).** When a `captureDiff` task settles, each changed file
589
+ that still exists (and passes the path-safety check below) is emitted as a `task_artifact` event with
590
+ `kind: "output"`, `source: "agent"`, `name`, `mimeType` and `size` (stat metadata only). The content is
591
+ **deliberately not read**: without an adapter-declared artifact event the bridge ships metadata only —
592
+ `sha256` is omitted and `contentUnavailableReason: "no_adapter_artifact_event"` says why. A `get_artifact`
593
+ for such an artifactId answers `artifact_not_found` honestly; credential paths, `..`, absolute paths,
594
+ directories and symlink escapes are not even named.
595
+
596
+ **Path safety for artifact reads** (applies whenever content is read, now and for future adapter-declared
597
+ artifact events): the read root is the **realpath subtree of the task's own cwd** (`allowed_cwd` only gates
598
+ task launch); after realpath resolution the target must still be inside the root — `..`, absolute paths,
599
+ directories and credential locations (`.ssh`, `.aws`, `.env`, `id_rsa`, …) are refused; the file is opened
600
+ once, sized via `fstat` on that same fd, and read from it while hashing SHA-256 (POSIX `O_NOFOLLOW` where
601
+ available; on Windows the realpath pre-check plus single-fd read is the equivalent). Within the inline cap
602
+ the content ships inline; above it only size/sha256 — large payloads go through the chunked artifact
603
+ transfer, never the message body. The workspace is never scanned.
604
+
276
605
  ### Service identity and scopes (P0-8)
277
606
 
278
607
  Any external system (orchestrator backend, CI, IDE plugin) can call the task capabilities with a scoped service
@@ -282,8 +611,12 @@ constant-time:
282
611
  | scope | Allows |
283
612
  | -------------- | --------------------------------- |
284
613
  | `task:create` | sending `run_task` |
285
- | `task:cancel` | sending `cancel_task` |
614
+ | `task:cancel` | sending `cancel_task` / `cancel_turn` / `close_session` |
286
615
  | `task:read` | reading task / scan results |
616
+ | `session:read` | reading sessions, events and interactions only (no task output, no diff) — the narrow scope for boards and approval UIs |
617
+ | `task:approve` | answering a `permission` interaction (`task_interaction_response`, `POST /v1/interactions/{id}:respond`) |
618
+ | `task:respond` | answering a `form` / `auth-url` interaction |
619
+ | `approval:persist` | letting that answer be written into the persistent approval ledger (affects future tasks, so it is separate) |
287
620
  | `device:read` | reading the local tool list (`scan`) |
288
621
 
289
622
  `run_task` / `cancel_task` may carry `requestedBy` (≤128 chars), `purpose` (≤64 chars) and `serviceToken`;
@@ -313,6 +646,13 @@ v1. **But if a message carries a token, it must verify** — there is no "presen
313
646
  | `device_busy` | Concurrency limit and queue both full |
314
647
  | `timeout` / `cancelled` | Timed out (including while queued) / cancelled |
315
648
  | `agent_error` | Non-zero CLI exit, or the process failed to start |
649
+ | `interaction_delivery_unknown` | Adapter delivery could not be confirmed; the interaction is failed, the turn is terminated, and retry is forbidden |
650
+ | `interaction_invalid_response` / `interaction_response_conflict` | Response failed validation / idempotency-key or resolved-response conflict |
651
+ | `interaction_timeout` | A pending interaction expired and the offered options did not include `reject_once`: the request was completed with a cancelled outcome and the turn ended |
652
+ | `interaction_denied` | A residual permission request under `full` (no `reject_once` offered): fail-closed — cancelled outcome, turn ended, never escalated to a human |
653
+ | `agent_protocol_error` | The agent ended a turn with an unresolved interaction or violated the execution protocol |
654
+ | `idempotency_conflict` | The same idempotency key was reused with a different request fingerprint |
655
+ | `session_not_continuable` | The tool has no way to continue a session (`executionModes[].continuation` is `single-turn`), so `sessionMode = conversation` is refused at creation |
316
656
  | `unauthorized` / `invalid_token` / `token_expired` / `insufficient_scope` | Service-token failures |
317
657
  | `protocol_incompatible` / `internal` | Version mismatch / bridge-side fault |
318
658
 
@@ -339,32 +679,50 @@ Prose drifts; contracts are checked in CI.
339
679
  `npm run contracts:check` verifies every wire type, capability, error code and platform endpoint in the code
340
680
  is actually documented — drift fails the build.
341
681
 
342
- ### Local control plane (optional, off by default)
682
+ ### Local control plane (connect starts it by default)
343
683
 
344
- `agent-bridge serve <platformUrl> [--port=8787]` is `connect` **plus** a loopback-only HTTP control plane.
684
+ `agent-bridge connect <platformUrl>` starts the local Web panel on `127.0.0.1:8787` by default and
685
+ falls forward when the port is occupied. `agent-bridge serve <platformUrl> [--port=8787]` still
686
+ lets you control it explicitly through config or flags.
345
687
  It exists for **other programs on this machine** — IDE extensions, scripts, MCP servers, CI runners.
346
688
  Remote platforms keep using the outbound WebSocket; this is a separate channel, not a replacement.
347
689
 
348
690
  | Rule | Value |
349
691
  | --- | --- |
350
692
  | 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 |
693
+ | Default | `connect` tries 8787..8806 and degrades only if all are taken; `serve` still follows `[control_plane]` / `--port` |
694
+ | Auth | scoped Bearer (`abs_<kid>_<secret>`, the same tokens as P0-8); `/v1/health` and the dashboard shell `/` are open; `?token=` is accepted for EventSource (loopback only — never share the URL). **Zero-setup dashboard**: `serve` mints a read-only in-memory token (`task:read`/`device:read`) at startup and embeds it in the printed dashboard URL; it dies with the process |
353
695
  | CORS | never sent — a browser script cannot call it silently |
696
+ | JWT | optional `[jwt] jwks_url = "..."`; verified principals scope `/v1/sessions`, `/v1/board`, `/v1/tasks*` and artifacts by `tenant_id`; cross-tenant task reads return 404 |
354
697
  | Scheduling | tasks go through the same `TaskSupervisor`, so `max_tasks` covers both channels |
355
698
  | Upstream | control-plane tasks report through the same `Emitter`, so the platform view never half-disappears |
699
+ | Dashboard | `GET /` serves an embedded Web task board (structured log event cards for all 7 event families, tool calls and results merged, raw JSON collapsed; agent todo plans + step timeline + result preview; vw/vh modals with fullscreen; bounded 600-event log cache, frame-batched SSE rendering, polling paused in background tabs); `GET /v1/board` is its data source (same registry as the terminal panel) |
356
700
 
357
701
  | Method | Path | Scope |
358
702
  | --- | --- | --- |
359
- | GET | `/v1/health` | — (liveness/readiness/version) |
703
+ | GET | `/` | — (Web dashboard shell; data flows through /v1/*) |
704
+ | GET | `/v1/health` | — (liveness/readiness/version; `?integrity=quick` also re-runs the state-DB check) |
705
+ | GET | `/v1/metrics` | `device:read` (Prometheus text) |
706
+ | GET | `/v1/whoami` | `device:read` (JWT principal / service identity) |
360
707
  | GET | `/v1/capabilities` | `device:read` |
361
708
  | GET | `/v1/agents` | `device:read` |
362
709
  | POST | `/v1/agents:scan` | `device:read` |
363
- | POST | `/v1/tasks` | `task:create` |
710
+ | GET | `/v1/board` | `task:read` (board aggregate: tasks + counts + capacity) |
711
+ | POST | `/v1/artifacts:gc` | `task:cancel` (explicit artifact TTL cleanup, dryRun supported) |
712
+ | GET | `/v1/sessions` | `session:read` or `task:read` (persistent sessions) |
713
+ | GET | `/v1/sessions/{id}` | `session:read` or `task:read` (session snapshot + eventSeq window) |
714
+ | GET | `/v1/sessions/{id}/events` | `session:read` or `task:read` (SSE: replay + live events) |
715
+ | GET | `/v1/sessions/{id}/artifacts/{artifactId}` | `task:read` (stream artifact download) |
716
+ | GET | `/v1/interactions?taskId=&state=&limit=` | `session:read` or `task:read` (bounded interaction list; `state=pending` is the common one) |
717
+ | GET | `/v1/interactions/{requestId}` | `session:read` or `task:read` (one interaction: pending request or settled result) |
718
+ | POST | `/v1/interactions/{requestId}:respond` | `task:approve` for permission, `task:respond` for form/auth-url (same rule and same code path as the WS `task_interaction_response`) |
719
+ | POST | `/v1/tasks` | `task:create` (body may carry `allowInteractive: true` to request interactions for that task; still requires `--interaction-enabled`) |
364
720
  | GET | `/v1/tasks` | `task:read` (cursor-paginated) |
365
721
  | GET | `/v1/tasks/{id}` | `task:read` |
366
722
  | POST | `/v1/tasks/{id}:cancel` | `task:cancel` (idempotent) |
367
- | GET | `/v1/tasks/{id}/events` | `task:read` (SSE: log + status) |
723
+ | GET | `/v1/tasks/{id}/events` | `task:read` (SSE: logs + status + steps) |
724
+ | GET | `/v1/tasks/{id}/steps` | `task:read` (step timeline + final answer) |
725
+ | GET | `/v1/tasks/{id}/file?path=` | `task:read` (artifact preview: confined to task cwd + allowed_cwd, ≤512KB) |
368
726
  | GET | `/v1/tasks/{id}/diff` | `task:read` (artifact only, task is not re-run) |
369
727
 
370
728
  ```bash
@@ -379,6 +737,138 @@ Errors are RFC 9457 `application/problem+json` carrying the same `code` enum as
379
737
  client branches on `code` instead of matching prose. `Idempotency-Key` makes a retried `POST /v1/tasks` return
380
738
  the same `taskId` instead of running twice. Contract: `contracts/openapi.control-plane.yaml`.
381
739
 
740
+ ### A2A / ACP gateway (optional, off by default)
741
+
742
+ A **standard protocol surface** for external orchestrators (A2A clients, ACP editors) instead of each of
743
+ them re-implementing the bridge's private wire. The gateway opens **no extra port**: it mounts on the
744
+ control-plane HTTP server (same loopback bind, tokens, and audit as `/v1/*`) and is a pure **adapter** —
745
+ it reuses `TaskSupervisor / SessionStore / Emitter` and duplicates neither scheduling nor persistence.
746
+ Enable with `[gateway] enabled = true` (or `AGENT_BRIDGE_GATEWAY=1` for a session); when disabled every
747
+ gateway route returns 404. The `a2a` / `acp` sub-flags turn individual surfaces off.
748
+
749
+ | Method | Path | Scope |
750
+ | --- | --- | --- |
751
+ | GET | `/.well-known/agent-card.json` | — (static description, no task data; capabilities declare only what is implemented) |
752
+ | POST | `/a2a` | per method: reads need `session:read`/`task:read`, send needs `task:create`, cancel needs `task:cancel` |
753
+ | POST | `/acp` | per method: handshake/session `device:read`, prompt `task:create`, cancel `task:cancel`, interaction answers `task:approve`/`task:respond` |
754
+
755
+ #### A2A surface
756
+
757
+ - **Version negotiation**: `A2A-Version` header (empty/absent means 0.3 per the spec; `1.0` selects the
758
+ `TASK_STATE_*` spelling family; anything else gets `-32009`). Both method spellings — `GetTask` and
759
+ `tasks/get` — are accepted.
760
+ - **`tasks/get` (read-only)**: SQLite snapshot → A2A Task (`history` holds only complete messages;
761
+ `task_log` never masquerades as a message/artifact — its endpoint is referenced from
762
+ `Task.metadata.bridge.taskLogEndpoint`; artifacts become file parts pointing at control-plane
763
+ download endpoints).
764
+ - **`message/send` (create a task)**: `message.parts` (text only) joined into the prompt; **bridge
765
+ extension fields live in `message.metadata`** — `agentType` (within the managed whitelist) and
766
+ `cwd` are required, `timeoutMs` optional. The `messageId` doubles as the idempotency key (resending
767
+ the same id returns the same task). **Returns immediately** — long-running tasks are followed via
768
+ get/subscribe. Uses the exact same orchestration as `POST /v1/tasks` (one source of truth for
769
+ concurrency limits, permission policy, and idempotency).
770
+ - **`tasks/cancel`**: same cancellation path as `:cancel` (SIGTERM → 2s → SIGKILL); terminal tasks
771
+ answer `-32002`.
772
+ - **`tasks/resubscribe` (SSE hole-filling)**: `eventSeq` cursor (`params.metadata.afterEventSeq`,
773
+ default 0); frame vocabulary `task`/`message`/`status`/`artifact` (each carrying eventSeq) plus
774
+ `log|step` debug extensions and `done`; terminal tasks answer `-32004` per the spec.
775
+ - **Status mapping**: queued→`SUBMITTED`, running→`WORKING`, waiting_interaction/waiting_user→`INPUT_REQUIRED`,
776
+ success→`COMPLETED`, failed/timeout→`FAILED` (true cause in `metadata.bridge.statusDetail`),
777
+ cancelled→`CANCELED`.
778
+ - **Isolation**: cross-tenant / missing tasks uniformly answer JSON-RPC `-32001` (never "exists but not
779
+ yours").
780
+
781
+ ##### A2A mapping details (6.4 / 6.8)
782
+
783
+ - **TaskStatusUpdateEvent** ↔ the SSE `status` frames on `tasks/resubscribe`: each carries
784
+ `state` + `eventSeq`; the **terminal frame closes the stream** (`done`) — there is no `final` field on
785
+ the Task object itself; finality is expressed by `status.state` reaching a terminal value
786
+ (`COMPLETED` / `FAILED` / `CANCELED`), per A2A v1.0.1.
787
+ - **Message / Part** ↔ `task_message`: only `state: "complete"` messages become A2A Message history
788
+ entries (text parts). Streaming **deltas never masquerade as A2A messages** — they are a bridge-internal
789
+ `partialMessages` concern (snapshot-only); `task_log` is debug output, referenced from
790
+ `Task.metadata.bridge.taskLogEndpoint`, never a message part.
791
+ - **Artifact** ↔ `task_artifact`: content-bearing artifacts (platform uploads) become **file parts**
792
+ pointing at the control-plane download endpoint; metadata-only task outputs (no adapter artifact
793
+ event — see the artifact section above) expose `name/mimeType/size` and are honestly marked
794
+ unavailable, never fabricating a downloadable part.
795
+ - **Permissions are not an A2A-native capability.** A waiting task surfaces as `INPUT_REQUIRED`, but the
796
+ approve/respond loop itself only exists on the bridge wire (`task_interaction_request/response`) and on
797
+ the ACP surface (`session/request_permission` / `elicitation/create`). An A2A client that wants to
798
+ answer an interaction must use one of those channels; the bridge will not invent A2A extensions for it.
799
+ Accordingly `message.metadata.allowInteractive: true` is **rejected outright** (`-32000` with
800
+ `data.code = "interaction_not_supported"`) and no task is created — silently running non-interactively
801
+ would let callers believe their permissions were auto-approved. Use ACP `session/new`
802
+ `_meta.allowInteractive` instead.
803
+ - **Bridge extension URIs** live under `message.metadata` / `Task.metadata.bridge.*` and are additive:
804
+
805
+ | Extension | Where | Meaning |
806
+ | --- | --- | --- |
807
+ | `agentType` | `message.metadata` | managed CLI whitelist entry (required) |
808
+ | `cwd` | `message.metadata` | task working directory (required) |
809
+ | `timeoutMs` / `captureDiff` / `permissionMode` | `message.metadata` | optional per-task overrides |
810
+ | `allowInteractive` | `message.metadata` | **unsupported**: A2A has no request-frame channel, `true` is rejected (`interaction_not_supported`) |
811
+ | `bridge.taskLogEndpoint` | `Task.metadata` | where debug logs live (not a message source) |
812
+ | `bridge.statusDetail` | `Task.metadata` | true cause when a state collapses several bridge statuses |
813
+ | `afterEventSeq` | resubscribe `params.metadata` | hole-filling cursor (eventSeq; absent = full replay) |
814
+ | `idempotentReplay` | send response `Task.metadata` | same `messageId` replayed → same task, no re-run |
815
+
816
+ #### MCP host (stdio, per-server config)
817
+
818
+ `[mcp.servers.<name>]` in config.toml starts local stdio MCP servers; the bridge acts as an MCP client
819
+ for `tools/list`, `tools/call` and **elicitation** (`McpElicitationClient`, transport-level tests cover
820
+ the elicitation surface including version-carrying differences — protocol negotiation is isolated in the
821
+ client and never leaks into the bridge wire). **Honest boundary**: elicitation handlers are injected by
822
+ the caller; wiring MCP questions into platform `task_interaction_request` is **not enabled yet** — the
823
+ host and client are ready and tested, and the integration will be declared only when it ships. MCP tool
824
+ calls are never auto-approved by model text.
825
+
826
+ #### ACP surface (ACP v1 over HTTP, vendor carrying)
827
+
828
+ ACP v1 still has no finalized HTTP transport upstream, but **this gateway's side is frozen and treated as
829
+ an external contract** (decided 2026-11-22: frame formats will not follow upstream RFD changes):
830
+ **requests go over `POST /acp`**, **prompt downstream + interaction requests flow over SSE**, and
831
+ **client answers arrive as response envelopes on another `POST /acp`**.
832
+
833
+ - **`initialize`**: declares only real capabilities — `loadSession: false` (sessions are not persisted
834
+ for resumption), text-only prompts, no fs/terminal client capabilities.
835
+ - **`session/new`**: pins `params.cwd` and `params._meta.agentType` (one of the 12 managed CLIs must be
836
+ chosen explicitly). Optional `params._meta.allowInteractive: true` requests interactions for that
837
+ session (booleans only). It is a **request**: unless the process runs with `--interaction-enabled`,
838
+ the session still runs non-interactively and the CLI's permission asks are declined locally.
839
+ - **`session/prompt` (conversation multi-turn, add-acp-session-memory)**: the first turn creates a
840
+ bridge conversation session (`run_task` semantics); subsequent turns use `send_message` on the
841
+ **same session** — CLI-native continuation (resume / ACP session / replay fallback across the
842
+ 12-adapter matrix), so **context lives in the CLI and only the delta travels over the wire**.
843
+ The response is an SSE stream: `event: prompt` (taskId + first/continue marker) → `event: update`
844
+ (`session/update` notifications, agent_message_chunk) → `event: request` when an interaction is
845
+ needed → `event: result` (turn completion: `{stopReason, content}` with `waiting_user → end_turn`;
846
+ a failed/timed-out turn becomes a JSON-RPC error and the session closes — later prompts are
847
+ honestly rejected with a `session/new` hint). Idle reaping reuses the conversation `idleTimeoutMs`.
848
+ After a bridge restart the ACP binding is lost (in-memory) — old sessions never pretend to be
849
+ continuable.
850
+ - **`session/cancel`**: cancels the active turn (`cancel_turn` orchestration, idempotent
851
+ operationId); with no active turn it succeeds silently.
852
+ - **Interaction loop**: **requires the session to declare `_meta.allowInteractive: true` at
853
+ `session/new`** (without it no request frame is ever produced — the default is non-interactive).
854
+ When a task enters `waiting_interaction`, the prompt stream injects an
855
+ `event: request` frame (`session/request_permission` or `elicitation/create` — permission uses the
856
+ standard options; form/auth-url use elicitation with form/url modes). The client answers via
857
+ `POST /acp` with a response envelope (no method, carrying the gateway-issued id + result); the
858
+ gateway converts it into `task_interaction_response` and runs the **same** dispatch path as
859
+ `POST /v1/interactions/{id}:respond` (double-checked permissions).
860
+ - End-to-end proof: `npm run e2e:gateway` (real bridge process + real service token + one real local
861
+ CLI run, covering A2A send/get/cancel, messageId idempotency, and the ACP prompt/cancel loop;
862
+ **multi-turn memory is asserted with a real two-round CLI dialogue**. If the CLIs' outbound proxy
863
+ differs from the system proxy, pass `E2E_PROXY=http://127.0.0.1:<port>`).
864
+ Without `E2E_AGENT` the script **auto-selects any ready CLI** on this machine, so a single tool's
865
+ subscription/login state can't be mistaken for a bridge regression; set `E2E_AGENT` to pin one.
866
+ When none is ready it exits `2`, and only `E2E_ALLOW_SKIP=1` turns that into a skip (clearly
867
+ reported as "nothing was verified"). The interaction loop (request frame → response envelope →
868
+ turn continues) needs a CLI that actually asks for permission — tools differ a lot (kimi-code asks,
869
+ opencode/minimax auto-allow), so it is off by default and enabled with `E2E_INTERACTION=1`.
870
+ - Full contract: the `a2a-gateway` tag in `contracts/openapi.control-plane.yaml`.
871
+
382
872
  ### Live scan progress and brand icons
383
873
 
384
874
  Probing 11 CLIs takes a few seconds, so results stream in instead of arriving as one batch: for every adapter
@@ -411,7 +901,7 @@ $ agent-bridge connect https://platform.example.com
411
901
  https://platform.example.com/bridge/authorize?code_challenge=…
412
902
  device bound: bd_9f1c… (credentials written to ~/.agent-bridge/config.toml)
413
903
  [agent-bridge] connected
414
- [agent-bridge] reported 11 tools, waiting for tasks…
904
+ [agent-bridge] reported 12 tools, waiting for tasks…
415
905
  ```
416
906
 
417
907
  **Scan without connecting** (useful when filing a support ticket)