@nathapp/nax-agent-acp 0.3.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 (56) hide show
  1. package/CHANGELOG.md +63 -0
  2. package/LICENSE +21 -0
  3. package/README.md +227 -0
  4. package/dist/client/backend.d.ts +30 -0
  5. package/dist/client/backend.js +238 -0
  6. package/dist/client/capabilities.d.ts +42 -0
  7. package/dist/client/capabilities.js +60 -0
  8. package/dist/client/connection.d.ts +31 -0
  9. package/dist/client/connection.js +32 -0
  10. package/dist/client/elicitation.d.ts +34 -0
  11. package/dist/client/elicitation.js +184 -0
  12. package/dist/client/env.d.ts +8 -0
  13. package/dist/client/env.js +21 -0
  14. package/dist/client/errors.d.ts +36 -0
  15. package/dist/client/errors.js +92 -0
  16. package/dist/client/events.d.ts +33 -0
  17. package/dist/client/events.js +96 -0
  18. package/dist/client/inbound.d.ts +40 -0
  19. package/dist/client/inbound.js +100 -0
  20. package/dist/client/index.d.ts +14 -0
  21. package/dist/client/index.js +12 -0
  22. package/dist/client/launch.d.ts +47 -0
  23. package/dist/client/launch.js +145 -0
  24. package/dist/client/open.d.ts +35 -0
  25. package/dist/client/open.js +154 -0
  26. package/dist/client/options.d.ts +46 -0
  27. package/dist/client/options.js +91 -0
  28. package/dist/client/permissions.d.ts +36 -0
  29. package/dist/client/permissions.js +92 -0
  30. package/dist/client/pre-approval.d.ts +24 -0
  31. package/dist/client/pre-approval.js +22 -0
  32. package/dist/client/race.d.ts +22 -0
  33. package/dist/client/race.js +20 -0
  34. package/dist/client/registry.d.ts +35 -0
  35. package/dist/client/registry.js +43 -0
  36. package/dist/client/resume.d.ts +37 -0
  37. package/dist/client/resume.js +93 -0
  38. package/dist/client/stream-scrub.d.ts +7 -0
  39. package/dist/client/stream-scrub.js +37 -0
  40. package/dist/client/text.d.ts +29 -0
  41. package/dist/client/text.js +62 -0
  42. package/dist/client/tool-calls.d.ts +42 -0
  43. package/dist/client/tool-calls.js +147 -0
  44. package/dist/client/tool-display.d.ts +23 -0
  45. package/dist/client/tool-display.js +90 -0
  46. package/dist/client/tool-events.d.ts +35 -0
  47. package/dist/client/tool-events.js +177 -0
  48. package/dist/client/tool-host.d.ts +25 -0
  49. package/dist/client/tool-host.js +178 -0
  50. package/dist/client/turn.d.ts +19 -0
  51. package/dist/client/turn.js +52 -0
  52. package/dist/client/usage.d.ts +36 -0
  53. package/dist/client/usage.js +65 -0
  54. package/dist/server/index.d.ts +5 -0
  55. package/dist/server/index.js +1 -0
  56. package/package.json +57 -0
package/CHANGELOG.md ADDED
@@ -0,0 +1,63 @@
1
+ # Changelog
2
+
3
+ All notable changes to `@nathapp/nax-agent-acp` are recorded here. Versions move in
4
+ step with `@nathapp/nax-agent`.
5
+
6
+ ## [0.3.0] - 2026-10-06
7
+
8
+ - Package scaffold: `./client` and `./server` entries, build, gates and release wiring.
9
+ - `acpBackend()` on `./client` (S4-2): launches the agent as a process-group leader,
10
+ initializes over `@agentclientprotocol/sdk`, checks capabilities, opens the session,
11
+ applies the profile's mode and the model, and runs text-only `full` turns with
12
+ cancel, crash and close handling. Exports `ACP_STOP_CODES` and the `AcpStopCode`,
13
+ `AcpAgentName`, `AcpAgentSpec` and `AcpBackendOptions` types.
14
+ - Profiles `none`, `read`, `ask` and `full` on `acpBackend()` (S4-3). The agent's
15
+ mode is set by profile, and each `session/request_permission` is decided by profile:
16
+ rejected under `none`/`read`, put to the caller through `approval_requested` and
17
+ `answer()` under `ask`, allowed under `full`. Only one-time options are chosen.
18
+ Auto-decisions are recorded with `decidedBy: "profile"`. Agent text in approval
19
+ events is stripped, redacted and capped; oversized or unmaskable text is withheld.
20
+ Pending approvals settle `cancelled` when the turn is cancelled, ends or loses its
21
+ agent process, and a request after `cancel()` is never allowed. Out-of-turn,
22
+ foreign-session and over-cap (16 concurrent) requests are rejected locally.
23
+ - Embedder tools on `acpBackend()` (S4-4). A per-session MCP server on `127.0.0.1`
24
+ (ephemeral port, path `/mcp`) serves the session's tools to the agent: bearer
25
+ token compared in constant time, `Host` and `Origin` checks, a 1 MiB body cap,
26
+ at most 8 concurrent calls, no CORS. Claude's adapter pre-approves each tool with
27
+ an exact `mcp__nax__<tool>` rule, so the tool's own `approval` is its only gate.
28
+ Calls run only during a turn, under the turn's signal, and are abandoned when it
29
+ stops. The token is redacted everywhere and never stored; the server stops on
30
+ close. Agents without HTTP MCP or pre-approval refuse tools after `initialize`.
31
+ - Turn events, usage and questions on `acpBackend()` (S4-5). Agent thoughts become
32
+ `thinking_delta`. Tool calls become `tool_call` / `tool_result`: sent when the
33
+ call is used, one result per call, calls still running at turn end closed as not
34
+ answered. Each turn ends with one `usage` event with the agent's per-turn tokens
35
+ and the turn's share of its cumulative reported cost (`costSource: "reported"`,
36
+ else `"unpriced"`). Session secret values, the tool host's token included, are
37
+ scrubbed from agent text, thinking and `turn_end.output`, also when split across
38
+ chunks. Form elicitations become `question` events under `ask` and `full`, one per
39
+ field (single- and multi-select, free text, Claude's "Other" box); other forms are
40
+ declined, and an unanswered or abandoned form is cancelled. Needs nax-agent's
41
+ `askQuestion(text, { signal })`.
42
+ - Resume and reconnect on `acpBackend()` (S4-6). `resumeAgentSession` restores the
43
+ agent's own session in a new process with `session/resume`, else `session/load`,
44
+ never as a fresh session. The stored record is checked before anything starts:
45
+ backend, agent, session id and directory. A lost session is
46
+ `AGENT_SESSION_NOT_FOUND`, and a different restored session is
47
+ `AGENT_SESSION_TURN_FAILED` (`detail: "identity"`). A `session/load` replay never
48
+ reaches the caller. The mode and model are re-applied, and the tool host restarts
49
+ with a new token. After a crash or kill, the next turn reconnects once the same
50
+ way; otherwise later turns end `AGENT_SESSION_CLOSED`. The cost baseline is saved
51
+ in the transcript (`acp.costUsd`), so the first turn after a resume costs only its
52
+ own share. `AgentSession.backend.capabilities.restoredWith` reports `"resume"` or
53
+ `"load"`.
54
+ - Packed-tarball smoke of both packages on Node 22 and 24, and the S4 acceptance
55
+ procedure with its live Claude and initialize-only fixtures (`RELEASING.md`).
56
+ - Embedder tools are listed with the MCP annotation `readOnlyHint: true` (#2365).
57
+ Claude's plan mode, used by the `none` and `read` profiles, asked before any MCP
58
+ tool not marked read-only, ahead of the `mcp__nax__<tool>` pre-approval, so the
59
+ profile then denied the session's own tools.
60
+ - Under `none` and `read`, Claude sessions disallow `ExitPlanMode` (#2365). Asked
61
+ to change something, Claude asked to leave plan mode, the profile refused, and the
62
+ adapter turned that refusal into an interrupt, so the turn ended
63
+ `ACP_STOP_CANCELLED`. The `_meta` is now sent even when the session has no tools.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025-2026 William Khoo
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,227 @@
1
+ # @nathapp/nax-agent-acp
2
+
3
+ ACP (Agent Client Protocol) backend for `@nathapp/nax-agent` sessions. It lets the
4
+ nax-agent session API (`createAgentSession`, `send()`, `answer()`, `cancel()`, `close()`)
5
+ drive external coding agents such as Claude Code over ACP.
6
+
7
+ **Status: pre-release (0.3.0, not yet published).** `acpBackend()` serves sessions
8
+ under all four profiles, with thinking, tool and usage events, questions from the
9
+ agent, embedder tools on Claude, resume across processes and reconnect after a
10
+ crash. `./server` is reserved for a later ACP server.
11
+
12
+ ```ts
13
+ import { createAgentSession, createMemoryTranscriptStore } from "@nathapp/nax-agent";
14
+ import { acpBackend } from "@nathapp/nax-agent-acp/client";
15
+
16
+ const session = await createAgentSession({
17
+ backend: acpBackend({ agent: "claude", allowUnsandboxed: true }),
18
+ profile: "full",
19
+ workdir: "/path/to/repo",
20
+ transcriptStore: createMemoryTranscriptStore(),
21
+ });
22
+ for await (const event of session.send("Summarise this repository")) {
23
+ if (event.type === "text_delta") process.stdout.write(event.text);
24
+ }
25
+ await session.close();
26
+ ```
27
+
28
+ What to know:
29
+ - **The agent runs unsandboxed on the host.** That is why `allowUnsandboxed: true` is required.
30
+ - **Environment.** The agent gets an allowlist: `PATH`, `HOME`, `USER`, `SHELL`,
31
+ `TMPDIR`, `LANG`, `LC_*`, `TERM`, the agent's auth variables, and `env`.
32
+ `inheritEnv: true` hands it your whole environment instead, credentials included.
33
+ - **Instructions** are prepended to the first prompt only; ACP has no system prompt.
34
+ - **Stop reasons.** A turn that stops for anything but `end_turn` ends `errored` with
35
+ an `ACP_STOP_*` code (`ACP_STOP_CODES`).
36
+ - **Usage.** Each turn ends with one `usage` event: the tokens the agent reports for
37
+ the turn, and the cost it reports (`costSource: "reported"`). An agent that reports
38
+ no cost gives `costUsd: 0` with `costSource: "unpriced"`. Never sum `unpriced`
39
+ rows as a cost. See "Events and usage on ACP".
40
+ - **A crashed or killed agent is reconnected once.** The next turn starts a new agent
41
+ process and restores the session in it. See "Resume and reconnect". A cancel the
42
+ agent ignores for `cancelGraceMs` kills it.
43
+ - **A crash between `session/new` and the first save** loses the agent's session
44
+ id. The next `createAgentSession` with the same id starts fresh.
45
+
46
+ ## Resume and reconnect
47
+
48
+ ```ts
49
+ const store = createFileTranscriptStore("/path/to/transcripts");
50
+ const session = await resumeAgentSession(sessionId, {
51
+ backend: acpBackend({ agent: "claude", allowUnsandboxed: true }),
52
+ profile: "full",
53
+ workdir: "/path/to/repo", // the directory the session was created in
54
+ transcriptStore: store,
55
+ });
56
+ ```
57
+
58
+ - **The agent keeps the history.** The transcript document holds the agent's
59
+ session id, its directory and the cost baseline, not the messages. A resume asks
60
+ the agent to restore its own session: `session/resume` when it supports it, else
61
+ `session/load`. It never starts a fresh session in its place.
62
+ - **What can fail:**
63
+ - The agent supports neither: `AGENT_SESSION_CAPABILITY_UNSUPPORTED` (`capability: "resume"`).
64
+ - The agent no longer has the session: `AGENT_SESSION_NOT_FOUND`.
65
+ - It restores a different one: `AGENT_SESSION_TURN_FAILED` (`detail: "identity"`).
66
+ - The document was written by another backend: `AGENT_SESSION_BACKEND_MISMATCH`.
67
+ - Its ACP record is damaged: `TRANSCRIPT_CORRUPT`.
68
+ - **Same directory.** `workdir` must be the directory the session was created in.
69
+ Another spelling of it (a symlink, a trailing slash) is fine. A `none` session
70
+ created without `workdir` cannot be resumed, so pass a `workdir` if you will
71
+ resume it.
72
+ - **`session.backend.capabilities.restoredWith`** is `"resume"` or `"load"` for a
73
+ restored agent process.
74
+ - **History is not replayed into your events.** A `session/load` replay never
75
+ reaches `send()`, and requests the agent makes during it are refused.
76
+ - **Instructions** are sent again only when the session never ran a turn.
77
+ - **Cost after a resume.** The baseline is saved in the document after each priced
78
+ turn, so the first turn after a resume costs only its own share, even when the
79
+ agent's running total includes the earlier turns.
80
+ - **Reconnect.** When the agent process dies (a crash, or a kill after an ignored
81
+ cancel), the turn that was running ends `errored`. The next `send()` starts a new
82
+ process and restores the session once:
83
+ - The tool host gets a new token.
84
+ - A cancel or `close()` while it starts stops the attempt; the next `send()` tries again.
85
+ - If the agent supports neither resume nor load, or the reconnect fails, later
86
+ turns end `AGENT_SESSION_CLOSED`.
87
+
88
+ ## Profiles on ACP
89
+
90
+ ACP enforces a profile in two layers: the agent's own mode, and this client's
91
+ answer to each permission request the agent sends.
92
+
93
+ | Profile | Agent mode (Claude) | Permission requests |
94
+ |---|---|---|
95
+ | `none` | `plan` | rejected, recorded as `decidedBy: "profile"` |
96
+ | `read` | `plan` | rejected, recorded as `decidedBy: "profile"` |
97
+ | `ask` | `default` | `approval_requested`; you decide with `answer()` |
98
+ | `full` | `default` | allowed, recorded as `decidedBy: "profile"` |
99
+
100
+ - **Only Claude supports `none` and `read`.** Other agents have no read-only mode,
101
+ so those profiles fail with `AGENT_SESSION_CAPABILITY_UNSUPPORTED` before any prompt.
102
+ - **The guarantees are narrower than the native backend's.** Only actions the agent
103
+ routes through a permission request are decided here.
104
+ - Under `none` and `read`, Claude may still run tools it does not ask about, such
105
+ as reads and search. `none` means no permitted side effects, not no reads.
106
+ - Under `none` and `read`, Claude cannot call `ExitPlanMode`. Left available, its
107
+ refused plan would end the turn as cancelled. The `_meta` that blocks it is part
108
+ of what Claude's adapter compares on resume, so resuming under another profile
109
+ may rebuild the agent's session.
110
+ - Plan mode lets Claude write its own plan file under `~/.claude/plans/` without
111
+ asking, so `none` and `read` do not stop that write.
112
+ - Under `ask`, actions Claude's `default` mode allows without asking (reads and
113
+ other non-mutating tools) are not shown to you.
114
+ - **Only one-time options are chosen.** "Always allow" is never chosen, because it
115
+ would outlive the session. An agent that offers no allow-once option is denied.
116
+ - **Expiry and failure deny.** An unanswered approval expires to a deny after
117
+ `approvalTimeoutMs`. A cancelled turn or a dead agent process answers `cancelled`.
118
+ - **What you see is display data.** The request's title, command and paths come from
119
+ the agent. They are redacted and capped, and they never decide anything.
120
+ - **Some requests are denied without being shown under `ask`.** This happens when a
121
+ secret cannot be masked safely next to shell syntax, or the agent's text is too large
122
+ to check. Some legitimate commands are caught too, for example `FOO_TOKEN=x; cmd`.
123
+ - **A cancelled turn starts nothing new.** A permission request that arrives after
124
+ `cancel()`, while the agent is still stopping, is answered `cancelled` under every
125
+ profile, `full` included.
126
+ - **The agent process is unsandboxed** under every profile.
127
+
128
+ nax-agent-acp and `@nathapp/nax-agent` share one version and are released together.
129
+
130
+ ## Embedder tools on ACP
131
+
132
+ Tools you pass as `createAgentSession({ tools })` reach the agent through a small
133
+ MCP server this client runs for the session.
134
+
135
+ - **Claude only.** The agent needs HTTP MCP support and a way to pre-approve the
136
+ tools. Other agents fail with `AGENT_SESSION_CAPABILITY_UNSUPPORTED`
137
+ (`capability: "tools"`) after `initialize`.
138
+ - **Loopback only.** The server listens on `127.0.0.1` on a random port. Every
139
+ request needs the session's bearer token; requests with another `Host`, any
140
+ `Origin`, or a body over 1 MiB are refused, so browser pages cannot reach it. It
141
+ stops when the session closes.
142
+ - **The token is not a secret from your own processes.** Claude's adapter hands
143
+ the server's headers to the Claude CLI on its command line, so any process
144
+ running as your user (including the agent's own shell) can read the token from
145
+ the process table. Treat your tools' `approval` as their real gate.
146
+ - **Where the token is redacted.** Errors, the agent's stderr, approval displays,
147
+ tool summaries, tool events, and the agent's own text and thinking. It is never
148
+ stored in the transcript.
149
+ - **The name `nax` is reserved.** If your Claude user or project settings define an
150
+ MCP server named `nax`, it can collide with this one. Rename yours.
151
+ - **Pre-approved at the agent.** Claude is told to allow exactly `mcp__nax__<tool>`
152
+ for each of your tools, so it never asks permission for them. Your tool's own
153
+ `approval` is the only gate: `"always"` asks you through `approval_requested` and
154
+ `answer()` under every profile; `"never"` runs under every profile.
155
+ - **Listed as read-only.** Every tool carries the MCP annotation
156
+ `readOnlyHint: true`. The `none` and `read` profiles put Claude in plan mode, which
157
+ asks before any MCP tool not marked read-only, ahead of the pre-approval. The hint
158
+ loosens nothing: your tool's `approval` stays the gate, and Claude's own write
159
+ tools are still refused under `none` and `read`.
160
+ - **Calls run inside a turn.** A call outside a running turn gets an error and the
161
+ tool does not run. When the turn is cancelled, times out, ends or loses the agent
162
+ process, the call's signal aborts and the agent is told the call was abandoned.
163
+ At most 8 calls run at once.
164
+ - **Tool input is not validated** against your `inputSchema`, as on the native
165
+ backend. Check it in `run`.
166
+ - **A permission request that names one of your tools is not trusted as such.** The
167
+ agent's tool title is display data. If an agent asks permission for an MCP tool
168
+ anyway, it is decided by profile like any other request.
169
+
170
+ ## Events and usage on ACP
171
+
172
+ A turn on ACP emits the same event types as on the native backend, with these
173
+ differences.
174
+
175
+ - **Text and thinking** arrive as `text_delta` and `thinking_delta`, always with
176
+ `round: 0`. `stream_reset` and `compaction` never occur.
177
+ - **Your secrets are scrubbed from the agent's text.** The values of `env` keys
178
+ named like `KEY`, `TOKEN`, `SECRET` or `PASSWORD` (8 characters or more) and the
179
+ tool host's token show as `[REDACTED]` in `text_delta`, `thinking_delta` and
180
+ `turn_end.output`, also when a value arrives split across two chunks. To catch
181
+ that, up to one such value's length of text is held back until the next chunk;
182
+ without such values nothing is held. Other secrets are not pattern-redacted in
183
+ text, as on the native backend.
184
+ - **Tool calls.** `tool_call` is sent when the agent uses the call: it asks
185
+ permission for it, reports progress, or finishes. It is not sent when the call is
186
+ first mentioned, because Claude fills in a call's input after mentioning it.
187
+ `name` is the agent's tool name (with Claude: `Read`, `Bash`, `mcp__nax__<tool>`).
188
+ Every `tool_call` is followed by exactly one `tool_result`. A call still running
189
+ when the turn ends gets `isError: true` and `"Not answered: the turn ended."`. A
190
+ call the agent mentions but never uses produces no events.
191
+ - **Inputs and previews** are capped and redacted best-effort, as on the native
192
+ backend. A file edit shows as `edit <path> (+added -removed)` lines.
193
+ - **Usage.** One `usage` event per turn, after the turn's last delta and tool
194
+ result, also when the turn stops for a reason other than `end_turn`.
195
+ - Tokens are the agent's numbers for the turn. Output tokens include thinking
196
+ tokens. Cache fields appear only when the agent reports them.
197
+ - Cost: the agent reports a running total for the session, and each turn's cost
198
+ is the difference. Spend between turns, or in a turn that ends without the
199
+ agent's final answer (cancel, crash), is counted in the next turn that reports
200
+ a cost.
201
+ - A turn that ends `errored` has zero `usage` in `turn_end`; read its `usage`
202
+ event instead.
203
+
204
+ ## Questions from the agent
205
+
206
+ Under `ask` and `full` this client tells the agent it can show forms. Claude uses
207
+ forms for its AskUserQuestion tool and for some model-fallback prompts. Under `none`
208
+ and `read` forms are not offered, and one that arrives anyway is declined.
209
+
210
+ - **Each form field is one `question` event.** Answer it with
211
+ `answer(requestId, { text })`.
212
+ - Choices are numbered. Reply with a number or the choice's text, in any case.
213
+ - A multi-select takes a comma-separated list.
214
+ - Claude's "Other" box: a reply that is not one of the choices becomes your own
215
+ answer.
216
+ - An empty reply skips an optional field.
217
+ - **Declined forms.** Forms with number, boolean or other field types, more than 16
218
+ fields or more than 32 choices, and requests to open a URL are declined. You see
219
+ an informational `question` that starts with `declined:`; `answer()` on it
220
+ returns `"cancelled"`. A reply that matches no choice (when there is no "Other"
221
+ box, or the field is required) and an empty reply to a required field also
222
+ decline the form, with a note.
223
+ - **No answer cancels.** An unanswered question after `approvalTimeoutMs`, a
224
+ cancelled turn, the turn ending or the agent process dying cancels the whole form,
225
+ and later fields are not asked. `answer()` on that question returns `"cancelled"`.
226
+ - **Question text comes from the agent.** Control characters are stripped, your
227
+ secrets scrubbed, and it is capped at 4 KiB.
@@ -0,0 +1,30 @@
1
+ /**
2
+ * acpBackend(): nax-agent's SessionBackend over ACP (S4 spec §6). It serves all
3
+ * four profiles: the agent's mode is set at open (§6.4 layer 1), and each
4
+ * session/request_permission is decided by profile (layer 2, permissions.ts),
5
+ * through the caller under `ask`. Embedder tools are served by a per-session MCP
6
+ * tool host (§6.6, tool-host.ts) and pre-approved at the adapter (R12); the
7
+ * host's token joins the session's redaction set before the agent starts (D4-i).
8
+ * The agent's updates become turn events with per-turn usage priced by one cost
9
+ * meter per agent process (§6.7, events.ts, usage.ts), and its form elicitations
10
+ * become questions under `ask` and `full` (§6.8, elicitation.ts). A turn's
11
+ * permission decisions, questions and tool calls are cancelled when the turn is
12
+ * cancelled, times out, ends or loses its process (D3-d, D4-f, D5-j).
13
+ *
14
+ * A stored session is restored with session/resume, else session/load, never as
15
+ * a fresh one (§6.9, resume.ts). A crashed or killed agent leaves the session
16
+ * disconnected; the next turn reconnects once the same way, with a new process,
17
+ * router and tool host token, and the cost baseline carried over (§6.3 step 5,
18
+ * S4-6 D6-a, D6-g). An agent that can do neither, or a reconnect that fails,
19
+ * leaves the session closed: later turns end AGENT_SESSION_CLOSED. The baseline
20
+ * is written to the transcript document after each priced turn, so a resume in a
21
+ * new process prices its first turn from it (D6-a).
22
+ */
23
+ import { type SessionBackend } from "@nathapp/nax-agent";
24
+ import { type LaunchFn } from "#src/client/launch";
25
+ import { type AcpBackendOptions } from "#src/client/options";
26
+ /** Test seam: the process launcher. Production always uses launchAgent. */
27
+ export declare const _acpBackendDeps: {
28
+ launch: LaunchFn;
29
+ };
30
+ export declare function acpBackend(input: AcpBackendOptions): SessionBackend;
@@ -0,0 +1,238 @@
1
+ /**
2
+ * acpBackend(): nax-agent's SessionBackend over ACP (S4 spec §6). It serves all
3
+ * four profiles: the agent's mode is set at open (§6.4 layer 1), and each
4
+ * session/request_permission is decided by profile (layer 2, permissions.ts),
5
+ * through the caller under `ask`. Embedder tools are served by a per-session MCP
6
+ * tool host (§6.6, tool-host.ts) and pre-approved at the adapter (R12); the
7
+ * host's token joins the session's redaction set before the agent starts (D4-i).
8
+ * The agent's updates become turn events with per-turn usage priced by one cost
9
+ * meter per agent process (§6.7, events.ts, usage.ts), and its form elicitations
10
+ * become questions under `ask` and `full` (§6.8, elicitation.ts). A turn's
11
+ * permission decisions, questions and tool calls are cancelled when the turn is
12
+ * cancelled, times out, ends or loses its process (D3-d, D4-f, D5-j).
13
+ *
14
+ * A stored session is restored with session/resume, else session/load, never as
15
+ * a fresh one (§6.9, resume.ts). A crashed or killed agent leaves the session
16
+ * disconnected; the next turn reconnects once the same way, with a new process,
17
+ * router and tool host token, and the cost baseline carried over (§6.3 step 5,
18
+ * S4-6 D6-a, D6-g). An agent that can do neither, or a reconnect that fails,
19
+ * leaves the session closed: later turns end AGENT_SESSION_CLOSED. The baseline
20
+ * is written to the transcript document after each priced turn, so a resume in a
21
+ * new process prices its first turn from it (D6-a).
22
+ */
23
+ import { getLogger, NO_OP_INTERACTION_HANDLER, } from "@nathapp/nax-agent";
24
+ import { answerElicitation } from "#src/client/elicitation";
25
+ import { sessionLost } from "#src/client/errors";
26
+ import { createTurnCollector } from "#src/client/events";
27
+ import { createInboundRouter } from "#src/client/inbound";
28
+ import { launchAgent } from "#src/client/launch";
29
+ import { openAcpSession } from "#src/client/open";
30
+ import { resolveAcpOptions } from "#src/client/options";
31
+ import { decidePermission } from "#src/client/permissions";
32
+ import { race } from "#src/client/race";
33
+ import { canRestore, storedSessionOf } from "#src/client/resume";
34
+ import { createToolCalls } from "#src/client/tool-calls";
35
+ import { createToolHost, newToolHostToken } from "#src/client/tool-host";
36
+ import { runPromptTurn } from "#src/client/turn";
37
+ import { createCostMeter } from "#src/client/usage";
38
+ /** Test seam: the process launcher. Production always uses launchAgent. */
39
+ export const _acpBackendDeps = { launch: launchAgent };
40
+ export function acpBackend(input) {
41
+ const options = resolveAcpOptions(input);
42
+ return Object.freeze({ kind: options.kind, open: (ctx) => openBackend(options, ctx) });
43
+ }
44
+ /** The process's options: the session's tool host tokens join the redaction set (D4-i, D6-g). */
45
+ function withTokens(options, tokens) {
46
+ if (tokens.length === 0)
47
+ return options;
48
+ return Object.freeze({ ...options, secrets: Object.freeze([...options.secrets, ...tokens]) });
49
+ }
50
+ function toolHostFor(ctx, router, secrets, token) {
51
+ if (token === undefined)
52
+ return undefined;
53
+ const calls = createToolCalls({
54
+ sessionId: ctx.sessionId,
55
+ tools: ctx.tools,
56
+ asks: ctx.asks,
57
+ currentTurnId: ctx.currentTurnId,
58
+ turnSignal: () => router.activeSignal(),
59
+ secrets,
60
+ });
61
+ return createToolHost(calls, token);
62
+ }
63
+ /** Permission requests and elicitations, decided by profile with the session's redaction set. */
64
+ function routerFor(ctx, secrets) {
65
+ const base = { profile: ctx.profile, asks: ctx.asks, secrets };
66
+ return createInboundRouter((request, signal) => decidePermission(request, { ...base, signal }), (request, signal) => answerElicitation(request, { ...base, signal }));
67
+ }
68
+ /** One agent process: a new agent session, or `restore` restored in it (§6.3 step 1, §6.9). */
69
+ async function connect(base, ctx, restore, retiredTokens) {
70
+ const token = ctx.tools.length > 0 ? newToolHostToken() : undefined;
71
+ const tokens = token === undefined ? retiredTokens : [...retiredTokens, token];
72
+ const options = withTokens(base, tokens);
73
+ const gone = new AbortController();
74
+ const router = routerFor(ctx, options.secrets);
75
+ const host = toolHostFor(ctx, router, options.secrets, token);
76
+ const acp = await openAcpSession(options, ctx, router.handlers, _acpBackendDeps.launch, host, restore).catch(async (err) => {
77
+ await host?.stop();
78
+ throw err;
79
+ });
80
+ const status = { disconnected: false };
81
+ void acp.launched.exited.then(() => {
82
+ status.disconnected = true;
83
+ gone.abort();
84
+ });
85
+ const state = {
86
+ link: acp.link,
87
+ launched: acp.launched,
88
+ agentSessionId: acp.agentSessionId,
89
+ cancelGraceMs: options.cancelGraceMs,
90
+ secrets: options.secrets,
91
+ disconnect: () => {
92
+ status.disconnected = true;
93
+ },
94
+ };
95
+ const meter = createCostMeter(restore?.costUsd ?? 0);
96
+ return { options, acp, router, state, gone, host, meter, tokens, status };
97
+ }
98
+ async function openBackend(base, ctx) {
99
+ // §6.9 step 1 runs before anything is spawned.
100
+ const restore = ctx.resume === undefined ? undefined : storedSessionOf(ctx.resume.doc, ctx, base);
101
+ const live = await connect(base, ctx, restore, []);
102
+ return assemble({
103
+ base,
104
+ ctx,
105
+ live,
106
+ closing: undefined,
107
+ // A restored agent already holds the instructions once a turn has run (D6-f).
108
+ instructionsSent: ctx.resume?.doc.turn !== undefined,
109
+ lost: false,
110
+ savedBaseline: restore?.costUsd ?? 0,
111
+ });
112
+ }
113
+ /** D6-h: the live process's capability record; a restored process adds restoredWith. */
114
+ function infoOf(s) {
115
+ const { record, restoredWith } = s.live.acp;
116
+ const capabilities = restoredWith === undefined ? { ...record } : { ...record, restoredWith };
117
+ return Object.freeze({ kind: s.base.kind, capabilities: Object.freeze(capabilities) });
118
+ }
119
+ function assemble(s) {
120
+ const handle = Object.freeze({ id: s.ctx.sessionId, agentName: s.base.kind });
121
+ const adapter = {
122
+ openSession: async () => handle,
123
+ sendTurn: (_handle, prompt, opts) => sendTurn(s, prompt, opts),
124
+ // The agent session closes in OpenedBackend.close(), within the §6.3 step 4 bound (D-j).
125
+ closeSession: async () => { },
126
+ };
127
+ return {
128
+ adapter,
129
+ handle,
130
+ // Read at access: a reconnect replaces the process and its capability record (D6-h).
131
+ get info() {
132
+ return infoOf(s);
133
+ },
134
+ turnOpts: () => ({ interactionHandler: NO_OP_INTERACTION_HANDLER }),
135
+ close: () => {
136
+ s.closing ??= shutdown(s);
137
+ return s.closing;
138
+ },
139
+ };
140
+ }
141
+ /** The process a turn runs on: reconnects once after a crash or kill (§6.3 step 5). */
142
+ async function liveFor(s, signal) {
143
+ if (s.closing !== undefined || s.lost) {
144
+ throw sessionLost(s.ctx.sessionId, "its agent process is gone and cannot be reconnected");
145
+ }
146
+ if (!s.live.status.disconnected)
147
+ return s.live;
148
+ if (!canRestore(s.live.acp.record)) {
149
+ s.lost = true;
150
+ throw sessionLost(s.ctx.sessionId, "its agent process is gone and the agent supports neither session/resume nor session/load");
151
+ }
152
+ return reconnect(s, signal);
153
+ }
154
+ /** D6-g: a new process restores the session; a stopped attempt may be retried, a failed one ends the session. */
155
+ async function reconnect(s, signal) {
156
+ const old = s.live;
157
+ old.acp.launched.kill();
158
+ old.acp.link.close();
159
+ // The old tool host stops and its token is revoked (§6.6).
160
+ await old.host?.stop();
161
+ const restore = {
162
+ agentSessionId: old.acp.agentSessionId,
163
+ cwd: old.acp.cwd,
164
+ costUsd: old.meter.baseline(),
165
+ };
166
+ // close() aborts openSignal; cancel() and the turn timeout abort the turn signal.
167
+ const ctx = { ...s.ctx, openSignal: AbortSignal.any([s.ctx.openSignal, signal]) };
168
+ try {
169
+ s.live = await connect(s.base, ctx, restore, old.tokens);
170
+ return s.live;
171
+ }
172
+ catch (err) {
173
+ if (!signal.aborted && !s.ctx.openSignal.aborted)
174
+ s.lost = true;
175
+ throw err;
176
+ }
177
+ }
178
+ async function sendTurn(s, prompt, opts) {
179
+ const signal = opts.signal ?? s.ctx.turnSignal();
180
+ const live = await liveFor(s, signal);
181
+ const instructions = s.instructionsSent ? undefined : s.ctx.instructions;
182
+ s.instructionsSent = true;
183
+ const text = instructions === undefined || instructions === "" ? prompt : `${instructions}\n\n${prompt}`;
184
+ const collector = createTurnCollector(opts.onTurnEvent, { secrets: live.options.secrets, meter: live.meter });
185
+ const release = live.router.attach(live.acp.agentSessionId, collector, AbortSignal.any([signal, live.gone.signal]));
186
+ try {
187
+ return await runPromptTurn(live.state, { text, signal, collector });
188
+ }
189
+ finally {
190
+ await release();
191
+ // The release aborted this turn's tool calls; wait for their answers (D4-f).
192
+ await live.host?.drain();
193
+ // Held text and calls left without a result go out before turn_end (D5-e, D5-g).
194
+ collector.finish();
195
+ await saveBaseline(s, live.meter.baseline());
196
+ }
197
+ }
198
+ /** D6-a: load-merge the baseline into the document. Best effort: a failure is logged, never fatal. */
199
+ async function saveBaseline(s, baseline) {
200
+ if (baseline === s.savedBaseline)
201
+ return;
202
+ const { transcriptStore: store, sessionId } = s.ctx;
203
+ try {
204
+ const doc = await store.load(sessionId);
205
+ if (doc?.acp === undefined)
206
+ return;
207
+ await store.save(sessionId, { ...doc, acp: { ...doc.acp, costUsd: baseline } });
208
+ s.savedBaseline = baseline;
209
+ }
210
+ catch {
211
+ warn("Could not save the ACP cost baseline", sessionId);
212
+ }
213
+ }
214
+ function warn(message, sessionId) {
215
+ try {
216
+ getLogger().warn("acp", message, { sessionId });
217
+ }
218
+ catch {
219
+ // A throwing host logger must not fail the turn.
220
+ }
221
+ }
222
+ async function shutdown(s) {
223
+ const { acp, options, status, host } = s.live;
224
+ if (!status.disconnected && acp.record.close) {
225
+ await race(acp.link.closeSession(acp.agentSessionId), { timeoutMs: options.cancelGraceMs });
226
+ }
227
+ await acp.launched.terminate(options.cancelGraceMs);
228
+ acp.link.close();
229
+ // §6.3 close step 4: stop the tool host and revoke its token.
230
+ await host?.stop();
231
+ await saveFinal(s.ctx.transcriptStore, s.ctx.sessionId);
232
+ }
233
+ /** §6.3 step 4.5: the document with its final savedAt. Load-merge keeps the facade's turn marker and the baseline. */
234
+ async function saveFinal(store, sessionId) {
235
+ const doc = await store.load(sessionId);
236
+ if (doc !== null)
237
+ await store.save(sessionId, { ...doc, savedAt: new Date().toISOString() });
238
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * What an ACP agent can do (S4 spec §6.3 step 2, §6.4, §6.10): the capability
3
+ * record from initialize plus registry data, and the requirement checks that run
4
+ * before any prompt. The record is authoritative at runtime and only narrows what
5
+ * the registry allows; custom agents have no registry data and fail closed. It is
6
+ * reported as AgentSession.backend.capabilities, so it stays JSON-safe.
7
+ */
8
+ import type { InitializeResponse, SessionConfigOption } from "@agentclientprotocol/sdk";
9
+ import type { AgentSessionProfile } from "@nathapp/nax-agent";
10
+ import type { AgentRegistryEntry, ModeSetting } from "#src/client/registry";
11
+ export type CapabilityRecord = {
12
+ readonly protocolVersion: number;
13
+ readonly agentName?: string;
14
+ readonly agentVersion?: string;
15
+ readonly loadSession: boolean;
16
+ readonly resume: boolean;
17
+ readonly close: boolean;
18
+ readonly mcpHttp: boolean;
19
+ /** The registry has a read-only mode for profiles none/read. */
20
+ readonly readOnlyMode: boolean;
21
+ /** The registry knows how to pre-approve embedder tools at the adapter (R12). */
22
+ readonly preApproval: boolean;
23
+ };
24
+ export interface Requirements {
25
+ readonly profile: AgentSessionProfile;
26
+ readonly toolCount: number;
27
+ readonly resume: boolean;
28
+ }
29
+ export interface UnmetRequirement {
30
+ readonly capability: "profile" | "tools" | "resume";
31
+ readonly reason: string;
32
+ }
33
+ export declare function buildCapabilityRecord(init: InitializeResponse, entry: AgentRegistryEntry | undefined): CapabilityRecord;
34
+ /** The first requirement this agent cannot meet, or undefined. The model is checked after session/new. */
35
+ export declare function unmetRequirement(record: CapabilityRecord, req: Requirements): UnmetRequirement | undefined;
36
+ /** The value ids a select option offers, groups flattened; none for a boolean option. */
37
+ export declare function selectValues(option: SessionConfigOption): readonly string[];
38
+ export declare function offersValue(options: readonly SessionConfigOption[], configId: string, value: string): boolean;
39
+ /** The id of the agent's model option (category "model") that offers `model`. */
40
+ export declare function modelOptionId(options: readonly SessionConfigOption[], model: string): string | undefined;
41
+ /** The mode a profile selects (§6.4 layer 1): read-only for none/read, the default mode otherwise. */
42
+ export declare function modeFor(profile: AgentSessionProfile, entry: AgentRegistryEntry | undefined): ModeSetting | undefined;