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