@nathapp/nax-agent-acp 0.3.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -3,6 +3,23 @@
3
3
  All notable changes to `@nathapp/nax-agent-acp` are recorded here. Versions move in
4
4
  step with `@nathapp/nax-agent`.
5
5
 
6
+ ## [0.3.1] - 2026-10-07
7
+
8
+ ### Added
9
+
10
+ - A rate-limited prompt (structured `data.errorKind: "rate_limit"`, as Claude's adapter sends) is `AGENT_SESSION_RATE_LIMITED`, classified from structured error data only. Needs `@nathapp/nax-agent` 0.3.1.
11
+ - `effort` option: sets the agent's reasoning effort after the model; skipped with a warning when not offered.
12
+ - `onProcess` option (`AcpProcessHooks`): `spawned(pid)` and `exited(pid)` for every agent process, including after a reconnect.
13
+ - `tool_result` events carry `resultBytes`: the UTF-8 byte length of the full result before the preview cap (0 for a call the turn never answered).
14
+ - `isAgentLaunchable` and `launchCandidateKind`: whether a registered agent's launcher resolves on PATH, and whether only the npx fallback does.
15
+ - The agent's heartbeats on a running tool surface as `tool_progress` turn events, at most one per call per 30 s; they are not session events.
16
+
17
+ ### Fixed
18
+
19
+ - An errored or cancelled turn's `turn_end` carries the usage, cost and `costSource` the turn had already reported, instead of zero (#2367). A cancelled turn whose agent answers within the grace period emits its `usage` event before `turn_end`. A turn that ends with no prompt response (killed after the grace, agent gone, or a JSON-RPC error) reports cost 0 with `costSource: "unpriced"`; any reading it saw is billed to the next priced turn. Needs `@nathapp/nax-agent` 0.3.1.
20
+ - Session instructions are no longer lost when the agent dies before it has the prompt. They count as delivered on the first turn-content update or the prompt's response; otherwise the next prompt, after the reconnect, carries them again (#2364).
21
+ - Profiles `none` and `read` on Claude no longer use plan mode, which wrote its plan file under `~/.claude/plans/` without a permission request. They run in `default` mode with `Write`, `Edit`, `MultiEdit`, `NotebookEdit` and `EnterPlanMode` removed, and load no Claude settings files, so settings allow rules, hooks and MCP servers cannot act outside the profile. Embedder tools no longer carry `readOnlyHint`. Resuming a 0.3.0 `none`/`read` session may rebuild Claude's agent session (#2366).
22
+
6
23
  ## [0.3.0] - 2026-10-06
7
24
 
8
25
  - Package scaffold: `./client` and `./server` entries, build, gates and release wiring.
package/README.md CHANGED
@@ -33,6 +33,15 @@ What to know:
33
33
  - **Instructions** are prepended to the first prompt only; ACP has no system prompt.
34
34
  - **Stop reasons.** A turn that stops for anything but `end_turn` ends `errored` with
35
35
  an `ACP_STOP_*` code (`ACP_STOP_CODES`).
36
+ - **Model and effort.** `model` and `effort` are set through `session/set_config_option`,
37
+ after the profile's mode: the model only when the agent offers it (else
38
+ `AGENT_SESSION_CAPABILITY_UNSUPPORTED`), the effort through the agent's `thought_level`
39
+ option (or its known effort option) and skipped with a warning when the value is not offered.
40
+ - **Agent processes.** `onProcess: { spawned(pid), exited(pid) }` is called for every agent
41
+ process, including a reconnect's; not when the spawn fails. A throwing hook is logged and ignored.
42
+ - **Rate limits.** A prompt the agent rejects with structured `data.errorKind: "rate_limit"`
43
+ (as Claude's adapter does) ends `AGENT_SESSION_RATE_LIMITED`. It is read from structured error
44
+ data only, never from message text; Claude's adapter sends no retry-after.
36
45
  - **Usage.** Each turn ends with one `usage` event: the tokens the agent reports for
37
46
  the turn, and the cost it reports (`costSource: "reported"`). An agent that reports
38
47
  no cost gives `costUsd: 0` with `costSource: "unpriced"`. Never sum `unpriced`
@@ -43,6 +52,14 @@ What to know:
43
52
  - **A crash between `session/new` and the first save** loses the agent's session
44
53
  id. The next `createAgentSession` with the same id starts fresh.
45
54
 
55
+ ## Is the agent installed?
56
+
57
+ `isAgentLaunchable(agent, env?)` is true when one of the agent's registry launch
58
+ candidates resolves on `PATH`, using the same resolution the backend uses at spawn.
59
+ `launchCandidateKind(agent, env?)` says which: `"local"` for the agent's own launcher,
60
+ `"npx"` when only the npx fallback resolves (the first open then downloads the
61
+ launcher), or `undefined`.
62
+
46
63
  ## Resume and reconnect
47
64
 
48
65
  ```ts
@@ -87,28 +104,29 @@ const session = await resumeAgentSession(sessionId, {
87
104
 
88
105
  ## Profiles on ACP
89
106
 
90
- ACP enforces a profile in two layers: the agent's own mode, and this client's
107
+ ACP enforces a profile in two layers: the agent's own setup, and this client's
91
108
  answer to each permission request the agent sends.
92
109
 
93
- | Profile | Agent mode (Claude) | Permission requests |
110
+ | Profile | Claude's setup | Permission requests |
94
111
  |---|---|---|
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"` |
112
+ | `none` | `default` mode, write tools removed, no settings files | rejected, recorded as `decidedBy: "profile"` |
113
+ | `read` | `default` mode, write tools removed, no settings files | rejected, recorded as `decidedBy: "profile"` |
114
+ | `ask` | `default` mode | `approval_requested`; you decide with `answer()` |
115
+ | `full` | `default` mode | allowed, recorded as `decidedBy: "profile"` |
99
116
 
100
- - **Only Claude supports `none` and `read`.** Other agents have no read-only mode,
117
+ - **Only Claude supports `none` and `read`.** Other agents have no read-only enforcement here yet,
101
118
  so those profiles fail with `AGENT_SESSION_CAPABILITY_UNSUPPORTED` before any prompt.
102
119
  - **The guarantees are narrower than the native backend's.** Only actions the agent
103
120
  routes through a permission request are decided here.
104
121
  - Under `none` and `read`, Claude may still run tools it does not ask about, such
105
122
  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.
123
+ - Under `none` and `read`, Claude has no `Write`, `Edit`, `MultiEdit`,
124
+ `NotebookEdit` or `EnterPlanMode` tool, and loads no user, project or local Claude
125
+ settings: their allow rules, hooks and MCP servers would act without asking. The
126
+ project's `CLAUDE.md` is not loaded either; pass what Claude needs as
127
+ `instructions`. A Bash command Claude does not treat as read-only asks first and
128
+ is refused. Changing these options changes what Claude's adapter compares on
129
+ resume, so resuming under another profile may rebuild the agent's session.
112
130
  - Under `ask`, actions Claude's `default` mode allows without asking (reads and
113
131
  other non-mutating tools) are not shown to you.
114
132
  - **Only one-time options are chosen.** "Always allow" is never chosen, because it
@@ -152,11 +170,6 @@ MCP server this client runs for the session.
152
170
  for each of your tools, so it never asks permission for them. Your tool's own
153
171
  `approval` is the only gate: `"always"` asks you through `approval_requested` and
154
172
  `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
173
  - **Calls run inside a turn.** A call outside a running turn gets an error and the
161
174
  tool does not run. When the turn is cancelled, times out, ends or loses the agent
162
175
  process, the call's signal aborts and the agent is told the call was abandoned.
@@ -179,9 +179,18 @@ async function sendTurn(s, prompt, opts) {
179
179
  const signal = opts.signal ?? s.ctx.turnSignal();
180
180
  const live = await liveFor(s, signal);
181
181
  const instructions = s.instructionsSent ? undefined : s.ctx.instructions;
182
- s.instructionsSent = true;
183
182
  const text = instructions === undefined || instructions === "" ? prompt : `${instructions}\n\n${prompt}`;
184
- const collector = createTurnCollector(opts.onTurnEvent, { secrets: live.options.secrets, meter: live.meter });
183
+ // #2364: delivered once the agent shows it has the prompt, not when it is sent.
184
+ const onReceipt = instructions === undefined
185
+ ? undefined
186
+ : () => {
187
+ s.instructionsSent = true;
188
+ };
189
+ const collector = createTurnCollector(opts.onTurnEvent, {
190
+ secrets: live.options.secrets,
191
+ meter: live.meter,
192
+ ...(onReceipt === undefined ? {} : { onReceipt }),
193
+ });
185
194
  const release = live.router.attach(live.acp.agentSessionId, collector, AbortSignal.any([signal, live.gone.signal]));
186
195
  try {
187
196
  return await runPromptTurn(live.state, { text, signal, collector });
@@ -7,7 +7,7 @@
7
7
  */
8
8
  import type { InitializeResponse, SessionConfigOption } from "@agentclientprotocol/sdk";
9
9
  import type { AgentSessionProfile } from "@nathapp/nax-agent";
10
- import type { AgentRegistryEntry, ModeSetting } from "#src/client/registry";
10
+ import type { AgentRegistryEntry, ModeSetting, ReadOnlyEnforcement } from "#src/client/registry";
11
11
  export type CapabilityRecord = {
12
12
  readonly protocolVersion: number;
13
13
  readonly agentName?: string;
@@ -16,7 +16,7 @@ export type CapabilityRecord = {
16
16
  readonly resume: boolean;
17
17
  readonly close: boolean;
18
18
  readonly mcpHttp: boolean;
19
- /** The registry has a read-only mode for profiles none/read. */
19
+ /** The registry can enforce profiles none/read on this agent. */
20
20
  readonly readOnlyMode: boolean;
21
21
  /** The registry knows how to pre-approve embedder tools at the adapter (R12). */
22
22
  readonly preApproval: boolean;
@@ -38,5 +38,11 @@ export declare function selectValues(option: SessionConfigOption): readonly stri
38
38
  export declare function offersValue(options: readonly SessionConfigOption[], configId: string, value: string): boolean;
39
39
  /** The id of the agent's model option (category "model") that offers `model`. */
40
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. */
41
+ /** Per-agent effort option ids, tried when no option has category "thought_level" (nax's EFFORT_OPTION_BY_AGENT). */
42
+ export declare const EFFORT_FALLBACK_IDS: Readonly<Record<string, string>>;
43
+ /** The option that sets `effort`: a "thought_level" option offering it, else the agent's fallback id offering it. */
44
+ export declare function effortOptionId(options: readonly SessionConfigOption[], agentName: string, effort: string): string | undefined;
45
+ /** The read-only enforcement a profile uses: the entry's for none/read, none otherwise. */
46
+ export declare function readOnlyFor(profile: AgentSessionProfile, entry: AgentRegistryEntry | undefined): ReadOnlyEnforcement | undefined;
47
+ /** The mode a profile selects (§6.4 layer 1): the read-only entry's for none/read, the default mode otherwise. */
42
48
  export declare function modeFor(profile: AgentSessionProfile, entry: AgentRegistryEntry | undefined): ModeSetting | undefined;
@@ -21,16 +21,17 @@ export function buildCapabilityRecord(init, entry) {
21
21
  resume: isObject(caps.sessionCapabilities?.resume),
22
22
  close: isObject(caps.sessionCapabilities?.close),
23
23
  mcpHttp: caps.mcpCapabilities?.http === true,
24
- readOnlyMode: entry?.readOnlyMode !== undefined,
24
+ readOnlyMode: entry?.readOnly !== undefined,
25
25
  preApproval: entry?.preApproval !== undefined,
26
26
  });
27
27
  }
28
+ const isReadOnlyProfile = (profile) => profile === "none" || profile === "read";
28
29
  /** The first requirement this agent cannot meet, or undefined. The model is checked after session/new. */
29
30
  export function unmetRequirement(record, req) {
30
- if ((req.profile === "none" || req.profile === "read") && !record.readOnlyMode) {
31
+ if (isReadOnlyProfile(req.profile) && !record.readOnlyMode) {
31
32
  return {
32
33
  capability: "profile",
33
- reason: `profile "${req.profile}" needs a read-only agent mode; this agent has none`,
34
+ reason: `profile "${req.profile}" needs read-only enforcement; this agent has none`,
34
35
  };
35
36
  }
36
37
  if (req.toolCount > 0 && !(record.mcpHttp && record.preApproval)) {
@@ -54,7 +55,27 @@ export function offersValue(options, configId, value) {
54
55
  export function modelOptionId(options, model) {
55
56
  return options.find((option) => option.category === "model" && selectValues(option).includes(model))?.id;
56
57
  }
57
- /** The mode a profile selects (§6.4 layer 1): read-only for none/read, the default mode otherwise. */
58
+ /** Per-agent effort option ids, tried when no option has category "thought_level" (nax's EFFORT_OPTION_BY_AGENT). */
59
+ export const EFFORT_FALLBACK_IDS = Object.freeze({
60
+ claude: "effort",
61
+ codex: "reasoning_effort",
62
+ opencode: "effort",
63
+ pi: "thought_level",
64
+ });
65
+ /** The option that sets `effort`: a "thought_level" option offering it, else the agent's fallback id offering it. */
66
+ export function effortOptionId(options, agentName, effort) {
67
+ const offering = options.filter((option) => selectValues(option).includes(effort));
68
+ const byCategory = offering.find((option) => option.category === "thought_level");
69
+ if (byCategory !== undefined)
70
+ return byCategory.id;
71
+ const fallback = Object.hasOwn(EFFORT_FALLBACK_IDS, agentName) ? EFFORT_FALLBACK_IDS[agentName] : undefined;
72
+ return fallback === undefined ? undefined : offering.find((option) => option.id === fallback)?.id;
73
+ }
74
+ /** The read-only enforcement a profile uses: the entry's for none/read, none otherwise. */
75
+ export function readOnlyFor(profile, entry) {
76
+ return isReadOnlyProfile(profile) ? entry?.readOnly : undefined;
77
+ }
78
+ /** The mode a profile selects (§6.4 layer 1): the read-only entry's for none/read, the default mode otherwise. */
58
79
  export function modeFor(profile, entry) {
59
- return profile === "none" || profile === "read" ? entry?.readOnlyMode : entry?.defaultMode;
80
+ return isReadOnlyProfile(profile) ? entry?.readOnly?.mode : entry?.defaultMode;
60
81
  }
@@ -30,6 +30,14 @@ export declare function rpcErrorOf(err: unknown): RequestError | undefined;
30
30
  * message; only the redacted excerpt escapes (§7).
31
31
  */
32
32
  export declare function openRequestError(step: string, err: RequestError, secrets: readonly string[]): AgentSessionError;
33
+ /**
34
+ * A rate limit, read from structured JSON-RPC error data only (S4b spec §8); never
35
+ * from message text. claude-agent-acp sends `data.errorKind: "rate_limit"` and no
36
+ * retry-after (S4b-0 finding a).
37
+ */
38
+ export declare function rateLimitOf(data: unknown): {
39
+ readonly retryAfterSeconds?: number;
40
+ } | undefined;
33
41
  /** A rejected session/prompt (§7: a JSON-RPC error on prompt is AGENT_SESSION_TURN_FAILED). */
34
42
  export declare function promptRequestError(err: RequestError, secrets: readonly string[]): NaxError;
35
43
  /** A stop reason other than end_turn. Own keys only: "__proto__" or "toString" is unknown, not a code. */
@@ -68,6 +68,16 @@ export function openRequestError(step, err, secrets) {
68
68
  }
69
69
  return backendUnavailable(`${step} failed: ${excerpt}`, { step, rpcCode: err.code });
70
70
  }
71
+ /**
72
+ * A rate limit, read from structured JSON-RPC error data only (S4b spec §8); never
73
+ * from message text. claude-agent-acp sends `data.errorKind: "rate_limit"` and no
74
+ * retry-after (S4b-0 finding a).
75
+ */
76
+ export function rateLimitOf(data) {
77
+ if (typeof data !== "object" || data === null || Array.isArray(data))
78
+ return undefined;
79
+ return "errorKind" in data && data.errorKind === "rate_limit" ? {} : undefined;
80
+ }
71
81
  /** A rejected session/prompt (§7: a JSON-RPC error on prompt is AGENT_SESSION_TURN_FAILED). */
72
82
  export function promptRequestError(err, secrets) {
73
83
  const excerpt = agentTextExcerpt(err.message, secrets);
@@ -76,6 +86,13 @@ export function promptRequestError(err, secrets) {
76
86
  step: "session/prompt",
77
87
  });
78
88
  }
89
+ const limit = rateLimitOf(err.data);
90
+ if (limit !== undefined) {
91
+ return new AgentSessionError(`The ACP agent was rate-limited: ${excerpt}`, "AGENT_SESSION_RATE_LIMITED", {
92
+ step: "session/prompt",
93
+ ...limit,
94
+ });
95
+ }
79
96
  return new NaxError(`The ACP prompt failed: ${excerpt}`, "AGENT_SESSION_TURN_FAILED", {
80
97
  stage: "acp",
81
98
  rpcCode: err.code,
@@ -7,7 +7,9 @@
7
7
  * usage_update costs feed the session's cost meter (D5-b). User chunks, plans, mode,
8
8
  * config and command updates, and anything unknown are dropped. finish() flushes
9
9
  * held text and answers unanswered tool calls; settle(response) does that and then
10
- * emits the turn's one usage event (D5-h). Nothing is emitted after finish(). The
10
+ * emits the turn's one usage event (D5-h). onReceipt fires once, on the first
11
+ * turn-content update or the settle, so the backend knows its instructions arrived
12
+ * (#2364). Nothing is emitted after finish(). The
11
13
  * sink is the facade's; a throw from it is contained.
12
14
  */
13
15
  import type { PromptResponse, SessionUpdate } from "@agentclientprotocol/sdk";
@@ -18,6 +20,8 @@ export interface CollectorOptions {
18
20
  readonly secrets?: readonly string[];
19
21
  /** The session's cost meter; a fresh one when absent. */
20
22
  readonly meter?: CostMeter;
23
+ /** Called once, when the turn first shows the agent has the prompt: a turn-content update or the prompt's response (#2364). */
24
+ readonly onReceipt?: () => void;
21
25
  }
22
26
  export interface TurnCollector {
23
27
  onUpdate(update: SessionUpdate): void;
@@ -30,6 +30,19 @@ function containedSink(emit) {
30
30
  }
31
31
  };
32
32
  }
33
+ /**
34
+ * Update kinds that prove the agent is working on the prompt (#2364). An allowlist:
35
+ * session-level updates (commands, mode, config, session info) and replayed history
36
+ * can arrive after attach but before the agent reads the prompt.
37
+ */
38
+ const RECEIPT_KINDS = new Set([
39
+ "agent_message_chunk",
40
+ "agent_thought_chunk",
41
+ "tool_call",
42
+ "tool_call_update",
43
+ "usage_update",
44
+ "plan",
45
+ ]);
33
46
  export function createTurnCollector(emit, options = {}) {
34
47
  const secrets = options.secrets ?? [];
35
48
  const meter = options.meter ?? createCostMeter();
@@ -43,6 +56,18 @@ export function createTurnCollector(emit, options = {}) {
43
56
  const parts = [];
44
57
  let done = false;
45
58
  let spend;
59
+ let received = false;
60
+ const receipt = () => {
61
+ if (received)
62
+ return;
63
+ received = true;
64
+ try {
65
+ options.onReceipt?.();
66
+ }
67
+ catch {
68
+ // The backend's bookkeeping must not break the turn.
69
+ }
70
+ };
46
71
  const route = (update) => {
47
72
  switch (update.sessionUpdate) {
48
73
  case "agent_message_chunk":
@@ -75,8 +100,11 @@ export function createTurnCollector(emit, options = {}) {
75
100
  };
76
101
  return {
77
102
  onUpdate(update) {
78
- if (!done)
79
- route(update);
103
+ if (done)
104
+ return;
105
+ if (RECEIPT_KINDS.has(update.sessionUpdate))
106
+ receipt();
107
+ route(update);
80
108
  },
81
109
  announce(toolCall) {
82
110
  if (!done)
@@ -85,6 +113,7 @@ export function createTurnCollector(emit, options = {}) {
85
113
  finish,
86
114
  settle(response) {
87
115
  finish();
116
+ receipt();
88
117
  if (spend === undefined) {
89
118
  spend = turnSpend(response, meter);
90
119
  send(usageEvent(spend));
@@ -10,5 +10,6 @@
10
10
  */
11
11
  export { acpBackend } from "#src/client/backend";
12
12
  export { ACP_STOP_CODES, type AcpStopCode } from "#src/client/errors";
13
- export type { AcpAgentSpec, AcpBackendOptions } from "#src/client/options";
13
+ export { isAgentLaunchable, type LaunchCandidateKind, launchCandidateKind } from "#src/client/launchable";
14
+ export type { AcpAgentSpec, AcpBackendOptions, AcpProcessHooks } from "#src/client/options";
14
15
  export type { AcpAgentName } from "#src/client/registry";
@@ -10,3 +10,4 @@
10
10
  */
11
11
  export { acpBackend } from "#src/client/backend";
12
12
  export { ACP_STOP_CODES } from "#src/client/errors";
13
+ export { isAgentLaunchable, launchCandidateKind } from "#src/client/launchable";
@@ -0,0 +1,4 @@
1
+ import { type AcpAgentName } from "#src/client/registry";
2
+ export type LaunchCandidateKind = "local" | "npx";
3
+ export declare function launchCandidateKind(agent: AcpAgentName, env?: Readonly<Record<string, string | undefined>>): LaunchCandidateKind | undefined;
4
+ export declare function isAgentLaunchable(agent: AcpAgentName, env?: Readonly<Record<string, string | undefined>>): boolean;
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Whether a registered agent can be launched on this machine (S4b spec §6.8):
3
+ * the same candidate resolution the backend uses at spawn (§6.10), exposed so an
4
+ * embedder's "is installed" check never duplicates the candidate list. "npx"
5
+ * means only the npx fallback resolves: the first open downloads the launcher.
6
+ */
7
+ import { pickCandidate } from "#src/client/launch";
8
+ import { registryEntry } from "#src/client/registry";
9
+ export function launchCandidateKind(agent, env = process.env) {
10
+ const found = pickCandidate(registryEntry(agent)?.launch ?? [], env.PATH);
11
+ if (found === undefined)
12
+ return undefined;
13
+ return found.command === "npx" ? "npx" : "local";
14
+ }
15
+ export function isAgentLaunchable(agent, env = process.env) {
16
+ return launchCandidateKind(agent, env) !== undefined;
17
+ }
@@ -12,8 +12,8 @@
12
12
  * rejects AGENT_SESSION_CLOSED.
13
13
  */
14
14
  import { PROTOCOL_VERSION } from "@agentclientprotocol/sdk";
15
- import { NaxError } from "@nathapp/nax-agent";
16
- import { buildCapabilityRecord, modeFor, modelOptionId, offersValue, unmetRequirement, } from "#src/client/capabilities";
15
+ import { getLogger, NaxError, } from "@nathapp/nax-agent";
16
+ import { buildCapabilityRecord, effortOptionId, modeFor, modelOptionId, offersValue, readOnlyFor, unmetRequirement, } from "#src/client/capabilities";
17
17
  import { openConnection } from "#src/client/connection";
18
18
  import { backendUnavailable, capabilityUnsupported, closedDuringOpen, EXCERPT_BYTES, openRequestError, rpcErrorOf, } from "#src/client/errors";
19
19
  import { agentGoneError, pickCandidate } from "#src/client/launch";
@@ -37,6 +37,7 @@ export async function openAcpSession(options, ctx, handlers, launch, host, resto
37
37
  throw closedDuringOpen(ctx.sessionId);
38
38
  const candidate = chooseLaunch(options);
39
39
  const launched = launch({ command: candidate.command, args: candidate.args, cwd: ctx.workdir, env: options.env });
40
+ watchProcess(options.onProcess, launched);
40
41
  const link = openConnection(launched.target, handlers);
41
42
  void launched.exited.then(() => link.close(new NaxError("The ACP agent process exited", "ACP_AGENT_EXITED", { stage: "acp" })));
42
43
  try {
@@ -48,6 +49,30 @@ export async function openAcpSession(options, ctx, handlers, launch, host, resto
48
49
  throw err;
49
50
  }
50
51
  }
52
+ /** S4b spec §8: report the agent process to the embedder; a throwing hook is logged, never propagated. */
53
+ function watchProcess(hooks, launched) {
54
+ const pid = launched.pid;
55
+ if (hooks === undefined || pid === undefined)
56
+ return;
57
+ const ignored = (name) => (err) => {
58
+ getLogger().warn("acp", `onProcess.${name} threw; ignored`, {
59
+ error: err instanceof Error ? err.message : String(err),
60
+ });
61
+ };
62
+ const call = (name) => {
63
+ try {
64
+ // An async hook's rejection is caught too; the hook is typed void, but async functions satisfy it.
65
+ const result = hooks[name]?.(pid);
66
+ if (result instanceof Promise)
67
+ result.catch(ignored(name));
68
+ }
69
+ catch (err) {
70
+ ignored(name)(err);
71
+ }
72
+ };
73
+ call("spawned");
74
+ void launched.exited.then(() => call("exited"));
75
+ }
51
76
  async function step(o, label, request) {
52
77
  const result = await race(request, { timeoutMs: o.options.initializeTimeoutMs, signal: o.ctx.openSignal });
53
78
  switch (result.kind) {
@@ -111,7 +136,7 @@ async function newSession(o, setup) {
111
136
  /** §6.3 step 3: start the tool host when the session has tools; its entry and Claude's `_meta` (§6.6, #2365). */
112
137
  async function sessionSetup(o) {
113
138
  const kind = o.options.entry?.preApproval;
114
- const meta = claudeSessionMeta(kind, o.ctx.tools.map((tool) => tool.name), o.ctx.profile);
139
+ const meta = claudeSessionMeta(kind, o.ctx.tools.map((tool) => tool.name), readOnlyFor(o.ctx.profile, o.options.entry));
115
140
  if (o.host === undefined)
116
141
  return meta === undefined ? { mcpServers: [] } : { mcpServers: [], _meta: { ...meta } };
117
142
  if (meta === undefined)
@@ -121,23 +146,46 @@ async function sessionSetup(o) {
121
146
  });
122
147
  return { mcpServers: [server], _meta: { ...meta } };
123
148
  }
124
- /** §6.3 step 5: the profile's mode, then the model. Only values the agent offered are set. */
149
+ /** §6.3 step 5: the profile's mode, then the model, then the effort (S4b). Only values the agent offered are set. */
125
150
  async function applyConfig(o, sessionId, offered) {
151
+ const afterMode = await applyMode(o, sessionId, offered);
152
+ const afterModel = await applyModel(o, sessionId, afterMode);
153
+ await applyEffort(o, sessionId, afterModel);
154
+ }
155
+ async function applyMode(o, sessionId, offered) {
126
156
  const mode = modeFor(o.ctx.profile, o.options.entry);
127
- if (mode !== undefined && !offersValue(offered, mode.configId, mode.value)) {
157
+ if (mode === undefined)
158
+ return offered;
159
+ if (!offersValue(offered, mode.configId, mode.value)) {
128
160
  throw capabilityUnsupported("profile", `the agent does not offer ${mode.configId} "${mode.value}"`);
129
161
  }
130
- const afterMode = mode === undefined
131
- ? offered
132
- : ((await step(o, "session/set_config_option", o.link.setConfigOption({ sessionId, ...mode }))).configOptions ??
133
- offered);
162
+ const set = await step(o, "session/set_config_option", o.link.setConfigOption({ sessionId, ...mode }));
163
+ return set.configOptions ?? offered;
164
+ }
165
+ async function applyModel(o, sessionId, offered) {
134
166
  const model = o.options.model;
135
167
  if (model === undefined)
136
- return;
137
- const configId = modelOptionId(afterMode, model);
168
+ return offered;
169
+ const configId = modelOptionId(offered, model);
138
170
  if (configId === undefined)
139
171
  throw capabilityUnsupported("model", `the agent offers no model option "${model}"`);
140
- await step(o, "session/set_config_option", o.link.setConfigOption({ sessionId, configId, value: model }));
172
+ const set = await step(o, "session/set_config_option", o.link.setConfigOption({ sessionId, configId, value: model }));
173
+ return set.configOptions ?? offered;
174
+ }
175
+ /** S4b spec §6.7: an effort the agent does not offer is skipped with a warning, as acpx does. */
176
+ async function applyEffort(o, sessionId, offered) {
177
+ const effort = o.options.effort;
178
+ if (effort === undefined)
179
+ return;
180
+ const configId = effortOptionId(offered, o.options.agentName, effort);
181
+ if (configId === undefined) {
182
+ getLogger().warn("acp", "The agent offers no effort option for this value; effort skipped", {
183
+ agent: o.options.agentName,
184
+ effort,
185
+ });
186
+ return;
187
+ }
188
+ await step(o, "session/set_config_option", o.link.setConfigOption({ sessionId, configId, value: effort }));
141
189
  }
142
190
  function initialDoc(o, record, agentSessionId) {
143
191
  return {
@@ -6,12 +6,19 @@ export type AcpAgentSpec = AcpAgentName | {
6
6
  readonly command: string;
7
7
  readonly args?: readonly string[];
8
8
  };
9
+ /** Called for every agent process the backend spawns, including a reconnect's (S4b spec §8). Errors are logged and ignored. */
10
+ export interface AcpProcessHooks {
11
+ spawned?(pid: number): void;
12
+ exited?(pid: number): void;
13
+ }
9
14
  export interface AcpBackendOptions {
10
15
  readonly agent: AcpAgentSpec;
11
16
  /** Required: the agent process runs on the host, unsandboxed (R7). */
12
17
  readonly allowUnsandboxed: true;
13
18
  /** Applied via session/set_config_option (category "model") before open returns. */
14
19
  readonly model?: string;
20
+ /** Reasoning effort, set via session/set_config_option after the model (S4b spec 8). Skipped when not offered. */
21
+ readonly effort?: string;
15
22
  /** Added to the agent's environment. */
16
23
  readonly env?: Readonly<Record<string, string>>;
17
24
  /** Default false: the allowlist only. true hands the whole process.env to the agent. */
@@ -21,6 +28,8 @@ export interface AcpBackendOptions {
21
28
  readonly args?: readonly string[];
22
29
  readonly cancelGraceMs?: number;
23
30
  readonly initializeTimeoutMs?: number;
31
+ /** Called with the pid of every agent process, including after a reconnect. Not called when the spawn fails. */
32
+ readonly onProcess?: AcpProcessHooks;
24
33
  }
25
34
  export type AcpLaunch = {
26
35
  readonly kind: "explicit";
@@ -37,10 +46,12 @@ export interface ResolvedAcpOptions {
37
46
  readonly entry: AgentRegistryEntry | undefined;
38
47
  readonly launch: AcpLaunch;
39
48
  readonly model: string | undefined;
49
+ readonly effort: string | undefined;
40
50
  readonly env: Readonly<Record<string, string>>;
41
51
  /** Values redacted from every agent excerpt (D-g). */
42
52
  readonly secrets: readonly string[];
43
53
  readonly cancelGraceMs: number;
44
54
  readonly initializeTimeoutMs: number;
55
+ readonly onProcess: AcpProcessHooks | undefined;
45
56
  }
46
57
  export declare function resolveAcpOptions(input: unknown, source?: Readonly<Record<string, string | undefined>>): ResolvedAcpOptions;
@@ -30,6 +30,7 @@ const SCHEMA = z
30
30
  agent: z.union([z.enum(["claude", "codex", "gemini", "opencode", "pi"]), customAgent]),
31
31
  allowUnsandboxed: z.literal(true),
32
32
  model: z.string().min(1).optional(),
33
+ effort: z.string().min(1).optional(),
33
34
  env: z.record(z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/), plain).optional(),
34
35
  inheritEnv: z.boolean().optional(),
35
36
  command: command.optional(),
@@ -56,7 +57,13 @@ function launchOf(data, entry) {
56
57
  }
57
58
  return { kind: "registry", candidates: entry?.launch ?? [] };
58
59
  }
59
- function resolved(data, source) {
60
+ function isProcessHooks(value) {
61
+ if (!isRecord(value))
62
+ return false;
63
+ const fnOrAbsent = (v) => v === undefined || typeof v === "function";
64
+ return fnOrAbsent(value.spawned) && fnOrAbsent(value.exited);
65
+ }
66
+ function resolved(data, source, onProcess) {
60
67
  const agentName = typeof data.agent === "string" ? data.agent : data.agent.name;
61
68
  const entry = typeof data.agent === "string" ? registryEntry(data.agent) : undefined;
62
69
  const env = buildAgentEnv({
@@ -71,21 +78,28 @@ function resolved(data, source) {
71
78
  entry,
72
79
  launch: launchOf(data, entry),
73
80
  model: data.model,
81
+ effort: data.effort,
74
82
  env: Object.freeze(env),
75
83
  secrets: Object.freeze([...secretValues(env)]),
76
84
  cancelGraceMs: data.cancelGraceMs ?? DEFAULT_CANCEL_GRACE_MS,
77
85
  initializeTimeoutMs: data.initializeTimeoutMs ?? DEFAULT_INITIALIZE_TIMEOUT_MS,
86
+ onProcess,
78
87
  });
79
88
  }
80
89
  export function resolveAcpOptions(input, source = process.env) {
81
90
  if (!isRecord(input) || input.allowUnsandboxed !== true) {
82
91
  throw new AgentSessionError("acpBackend requires allowUnsandboxed: true: the agent process runs on the host, unsandboxed", "AGENT_SESSION_SANDBOX_UNAVAILABLE", { path: "allowUnsandboxed" });
83
92
  }
84
- const parsed = SCHEMA.safeParse(input);
93
+ // Functions are checked by hand: the zod schema validates plain data only.
94
+ const { onProcess, ...rest } = input;
95
+ if (onProcess !== undefined && !isProcessHooks(onProcess)) {
96
+ throw new AgentSessionError("Invalid acpBackend options: onProcess: spawned and exited must be functions", "AGENT_SESSION_INVALID_OPTIONS", { path: "onProcess" });
97
+ }
98
+ const parsed = SCHEMA.safeParse(rest);
85
99
  if (!parsed.success) {
86
100
  const issue = parsed.error.issues[0];
87
101
  const path = issue === undefined ? "" : issue.path.map(String).join(".");
88
102
  throw new AgentSessionError(`Invalid acpBackend options: ${path === "" ? "(options)" : path}: ${issue?.message ?? "invalid"}`, "AGENT_SESSION_INVALID_OPTIONS", { path });
89
103
  }
90
- return resolved(parsed.data, source);
104
+ return resolved(parsed.data, source, onProcess);
91
105
  }
@@ -5,8 +5,8 @@
5
5
  * and only the *_once kinds: allow_always would outlive the session. Auto-decisions
6
6
  * are recorded with decidedBy "profile". Fail closed: a deny or deadline answers
7
7
  * reject_once; a turn abort, process death or ask-port failure answers
8
- * `cancelled`. Embedder tools are pre-approved at the adapter (S4-4) and listed
9
- * read-only for plan mode (#2365), so they are normally never asked about; if an agent asks anyway, the request is decided
8
+ * `cancelled`. Embedder tools are pre-approved at the adapter (S4-4), so they are
9
+ * normally never asked about; if an agent asks anyway, the request is decided
10
10
  * like any other, because its title is display data (S4-4 D4-c).
11
11
  */
12
12
  import type { RequestPermissionRequest, RequestPermissionResponse } from "@agentclientprotocol/sdk";
@@ -5,20 +5,12 @@
5
5
  * `allowedTools` rules allow a tool without a permission request. One exact rule
6
6
  * per tool, `mcp__nax__<tool>`, so only the session's own tools are allowed. Tool
7
7
  * names are already restricted by the facade, so a rule never needs escaping.
8
- * Plan mode (profiles none/read) asks before any MCP tool not marked read-only,
9
- * ahead of these rules; tool-calls.ts lists every tool with readOnlyHint (#2365).
8
+ * Under none/read the entry's read-only enforcement adds the removed tools and its
9
+ * session options (#2366).
10
10
  */
11
- import type { AgentSessionProfile } from "@nathapp/nax-agent";
12
- import type { AgentRegistryEntry } from "#src/client/registry";
11
+ import type { AgentRegistryEntry, ReadOnlyEnforcement } from "#src/client/registry";
13
12
  /** The ACP MCP server name; the agent sees the tools as `mcp__nax__<tool>`. */
14
13
  export declare const TOOL_HOST_SERVER_NAME = "nax";
15
14
  export declare function mcpToolRule(toolName: string): string;
16
- /**
17
- * Claude tools a session under `none` or `read` never gets (#2365). Asked to change
18
- * something in plan mode, Claude calls ExitPlanMode; the adapter turns its reject into
19
- * an interrupt, so the turn ended ACP_STOP_CANCELLED instead of meeting the profile's
20
- * refusal. Without it Claude reaches for Write or Edit, which layer 2 rejects.
21
- */
22
- export declare const READ_ONLY_DISALLOWED_TOOLS: readonly string[];
23
- /** The session/new, resume and load `_meta` for Claude: tool rules and the read-only lock; undefined when empty. */
24
- export declare function claudeSessionMeta(kind: AgentRegistryEntry["preApproval"], toolNames: readonly string[], profile: AgentSessionProfile): Readonly<Record<string, unknown>> | undefined;
15
+ /** The session/new, resume and load `_meta` for Claude: tool rules and the read-only enforcement; undefined when empty. */
16
+ export declare function claudeSessionMeta(kind: AgentRegistryEntry["preApproval"], toolNames: readonly string[], readOnly: ReadOnlyEnforcement | undefined): Readonly<Record<string, unknown>> | undefined;
@@ -3,20 +3,13 @@ export const TOOL_HOST_SERVER_NAME = "nax";
3
3
  export function mcpToolRule(toolName) {
4
4
  return `mcp__${TOOL_HOST_SERVER_NAME}__${toolName}`;
5
5
  }
6
- /**
7
- * Claude tools a session under `none` or `read` never gets (#2365). Asked to change
8
- * something in plan mode, Claude calls ExitPlanMode; the adapter turns its reject into
9
- * an interrupt, so the turn ended ACP_STOP_CANCELLED instead of meeting the profile's
10
- * refusal. Without it Claude reaches for Write or Edit, which layer 2 rejects.
11
- */
12
- export const READ_ONLY_DISALLOWED_TOOLS = Object.freeze(["ExitPlanMode"]);
13
- /** The session/new, resume and load `_meta` for Claude: tool rules and the read-only lock; undefined when empty. */
14
- export function claudeSessionMeta(kind, toolNames, profile) {
6
+ /** The session/new, resume and load `_meta` for Claude: tool rules and the read-only enforcement; undefined when empty. */
7
+ export function claudeSessionMeta(kind, toolNames, readOnly) {
15
8
  if (kind !== "claudeCode.allowedTools")
16
9
  return undefined;
17
10
  const options = {
18
11
  ...(toolNames.length === 0 ? {} : { allowedTools: toolNames.map(mcpToolRule) }),
19
- ...(profile === "none" || profile === "read" ? { disallowedTools: [...READ_ONLY_DISALLOWED_TOOLS] } : {}),
12
+ ...(readOnly === undefined ? {} : { disallowedTools: [...readOnly.disallowedTools], ...readOnly.sessionOptions }),
20
13
  };
21
14
  return Object.keys(options).length === 0 ? undefined : { claudeCode: { options } };
22
15
  }
@@ -16,12 +16,25 @@ export interface ModeSetting {
16
16
  readonly configId: string;
17
17
  readonly value: string;
18
18
  }
19
+ /**
20
+ * How profiles none and read are enforced on this agent (§6.4 layer 1, as revised
21
+ * by the 2026-10-07 fix bundle). Applied through the agent's pre-approval channel,
22
+ * so only an agent with one may declare it.
23
+ */
24
+ export interface ReadOnlyEnforcement {
25
+ /** The mode set for none/read. */
26
+ readonly mode: ModeSetting;
27
+ /** Agent tools removed from the session under none/read. */
28
+ readonly disallowedTools: readonly string[];
29
+ /** Extra agent options under none/read, merged into the pre-approval channel's options. */
30
+ readonly sessionOptions: Readonly<Record<string, unknown>>;
31
+ }
19
32
  export interface AgentRegistryEntry {
20
33
  readonly name: AcpAgentName;
21
34
  /** Tried in order; the first command found wins (S4-2 launch). */
22
35
  readonly launch: readonly LaunchCandidate[];
23
- /** Mode for profiles `none` and `read`; undefined means those profiles are unsupported (§6.4). */
24
- readonly readOnlyMode: ModeSetting | undefined;
36
+ /** How profiles `none` and `read` are enforced; undefined means those profiles are unsupported (§6.4). */
37
+ readonly readOnly: ReadOnlyEnforcement | undefined;
25
38
  /** Mode for profiles `ask` and `full`; undefined means the agent's own default is kept. */
26
39
  readonly defaultMode: ModeSetting | undefined;
27
40
  /** How embedder tools are pre-approved at the adapter (R12); undefined means tools are unsupported. */
@@ -8,11 +8,24 @@
8
8
  */
9
9
  const local = (command, ...args) => ({ command, args });
10
10
  const npx = (spec) => ({ command: "npx", args: ["-y", spec] });
11
+ function freezeReadOnly(readOnly) {
12
+ if (readOnly === undefined)
13
+ return undefined;
14
+ const options = Object.entries(readOnly.sessionOptions).map(([key, value]) => [
15
+ key,
16
+ Array.isArray(value) ? Object.freeze([...value]) : value,
17
+ ]);
18
+ return Object.freeze({
19
+ mode: Object.freeze({ ...readOnly.mode }),
20
+ disallowedTools: Object.freeze([...readOnly.disallowedTools]),
21
+ sessionOptions: Object.freeze(Object.fromEntries(options)),
22
+ });
23
+ }
11
24
  function entry(name, launch, authEnv, claude) {
12
25
  return Object.freeze({
13
26
  name,
14
27
  launch: Object.freeze(launch.map((c) => Object.freeze({ command: c.command, args: Object.freeze([...c.args]) }))),
15
- readOnlyMode: claude?.readOnlyMode === undefined ? undefined : Object.freeze({ ...claude.readOnlyMode }),
28
+ readOnly: freezeReadOnly(claude?.readOnly),
16
29
  defaultMode: claude?.defaultMode === undefined ? undefined : Object.freeze({ ...claude.defaultMode }),
17
30
  preApproval: claude?.preApproval,
18
31
  authEnv: Object.freeze([...authEnv]),
@@ -22,7 +35,14 @@ const REGISTRY = new Map([
22
35
  [
23
36
  "claude",
24
37
  entry("claude", [local("claude-agent-acp"), npx("@agentclientprotocol/claude-agent-acp@~0.85.1")], ["ANTHROPIC_API_KEY", "CLAUDE_CODE_OAUTH_TOKEN"], {
25
- readOnlyMode: { configId: "mode", value: "plan" },
38
+ // #2366: no plan mode (it wrote its plan file without asking). The write tools are
39
+ // removed instead, and no Claude settings file loads: their allow rules, hooks and
40
+ // MCP servers act without a permission request.
41
+ readOnly: {
42
+ mode: { configId: "mode", value: "default" },
43
+ disallowedTools: ["Write", "Edit", "MultiEdit", "NotebookEdit", "EnterPlanMode"],
44
+ sessionOptions: { settingSources: [], allowDangerouslySkipPermissions: false },
45
+ },
26
46
  defaultMode: { configId: "mode", value: "default" },
27
47
  preApproval: "claudeCode.allowedTools",
28
48
  }),
@@ -116,10 +116,6 @@ export function createToolCalls(deps) {
116
116
  name: tool.name,
117
117
  description: tool.description,
118
118
  inputSchema: { ...tool.inputSchema, type: "object" },
119
- // #2365: this host is the tools' only approval point. Claude's plan mode
120
- // (profiles none/read) asks before any MCP tool not marked read-only,
121
- // ahead of the mcp__nax__<tool> pre-approval.
122
- annotations: { readOnlyHint: true },
123
119
  })),
124
120
  async call(name, args, requestSignal) {
125
121
  const tool = byName.get(name);
@@ -32,4 +32,11 @@ export declare function previewOf(call: {
32
32
  readonly content?: unknown;
33
33
  readonly rawOutput?: unknown;
34
34
  }, secrets: readonly string[]): string;
35
- export declare function createToolEvents(emit: (event: TurnEvent) => void, secrets: readonly string[]): ToolEvents;
35
+ /** UTF-8 byte length of the full result text, before any cap (S4b spec §7.4). */
36
+ export declare function resultBytesOf(call: {
37
+ readonly content?: unknown;
38
+ readonly rawOutput?: unknown;
39
+ }): number;
40
+ /** At most one tool_progress per call per this interval (S4b-0 finding f). */
41
+ export declare const TOOL_PROGRESS_MIN_INTERVAL_MS = 30000;
42
+ export declare function createToolEvents(emit: (event: TurnEvent) => void, secrets: readonly string[], now?: () => number): ToolEvents;
@@ -120,11 +120,34 @@ export function previewOf(call, secrets) {
120
120
  const visible = stripInvisible(stripControl(capBytes(raw, REDACTION_SCAN_BYTES)));
121
121
  return capBytes(redactSecrets(scrubSecrets(visible, secrets)), TOOL_RESULT_PREVIEW_BYTES);
122
122
  }
123
+ const UTF8 = new TextEncoder();
124
+ /** UTF-8 byte length of the full result text, before any cap (S4b spec §7.4). */
125
+ export function resultBytesOf(call) {
126
+ const fromContent = contentText(call.content);
127
+ const raw = fromContent !== "" ? fromContent : typeof call.rawOutput === "string" ? call.rawOutput : "";
128
+ return UTF8.encode(raw).byteLength;
129
+ }
130
+ /** At most one tool_progress per call per this interval (S4b-0 finding f). */
131
+ export const TOOL_PROGRESS_MIN_INTERVAL_MS = 30_000;
123
132
  function isStarted(status) {
124
133
  return status === "in_progress" || status === "completed" || status === "failed";
125
134
  }
126
- export function createToolEvents(emit, secrets) {
135
+ export function createToolEvents(emit, secrets, now = Date.now) {
127
136
  const calls = new Map();
137
+ const lastBeat = new Map();
138
+ /** Calls whose tool has started (their first in_progress); only these send liveness beats. */
139
+ const running = new Set();
140
+ /** A non-terminal update on a running call: a throttled liveness beat (the agent's heartbeat). */
141
+ const beat = (state) => {
142
+ if (!running.has(state.id) || state.resolved)
143
+ return;
144
+ const at = now();
145
+ const last = lastBeat.get(state.id);
146
+ if (last !== undefined && at - last < TOOL_PROGRESS_MIN_INTERVAL_MS)
147
+ return;
148
+ lastBeat.set(state.id, at);
149
+ emit({ type: "tool_progress", callId: state.id });
150
+ };
128
151
  const merge = (update) => {
129
152
  if (!isRecord(update))
130
153
  return undefined;
@@ -146,21 +169,31 @@ export function createToolEvents(emit, secrets) {
146
169
  emit({ type: "tool_call", callId: state.id, name: nameOf(state), input: inputOf(state.rawInput, secrets) });
147
170
  return next;
148
171
  };
149
- const resolve = (state, isError, preview) => {
172
+ const resolve = (state, isError, preview, resultBytes) => {
150
173
  if (state.resolved)
151
174
  return;
152
175
  calls.set(state.id, { ...state, resolved: true });
153
- emit({ type: "tool_result", callId: state.id, isError, preview });
176
+ lastBeat.delete(state.id);
177
+ running.delete(state.id);
178
+ emit({ type: "tool_result", callId: state.id, isError, preview, resultBytes });
154
179
  };
155
180
  return {
156
181
  onUpdate(update) {
157
182
  const state = merge(update);
158
183
  const status = isRecord(update) ? update.status : undefined;
159
- if (state === undefined || !isStarted(status))
184
+ if (state === undefined)
185
+ return;
186
+ if (status === undefined || (status === "in_progress" && running.has(state.id))) {
187
+ beat(state);
188
+ return;
189
+ }
190
+ if (!isStarted(status))
160
191
  return;
192
+ if (status === "in_progress")
193
+ running.add(state.id);
161
194
  const shown = announce(state);
162
195
  if (status !== "in_progress")
163
- resolve(shown, status === "failed", previewOf(shown, secrets));
196
+ resolve(shown, status === "failed", previewOf(shown, secrets), resultBytesOf(shown));
164
197
  },
165
198
  announce(toolCall) {
166
199
  const state = merge(toolCall);
@@ -170,7 +203,7 @@ export function createToolEvents(emit, secrets) {
170
203
  flush() {
171
204
  for (const state of [...calls.values()]) {
172
205
  if (state.announced)
173
- resolve(state, true, UNANSWERED_PREVIEW);
206
+ resolve(state, true, UNANSWERED_PREVIEW, 0);
174
207
  }
175
208
  },
176
209
  };
@@ -1,7 +1,13 @@
1
- import { NaxError } from "@nathapp/nax-agent";
1
+ import { attachTurnSpend, NaxError } from "@nathapp/nax-agent";
2
2
  import { promptRequestError, rpcErrorOf, stopReasonError } from "#src/client/errors";
3
3
  import { agentGoneError } from "#src/client/launch";
4
4
  import { race } from "#src/client/race";
5
+ /** A turn that ended with no prompt response reports nothing it can price; its reading moves to the next turn. */
6
+ const NO_RESPONSE_SPEND = Object.freeze({
7
+ tokenUsage: Object.freeze({ inputTokens: 0, outputTokens: 0 }),
8
+ costUsd: 0,
9
+ costSource: "unpriced",
10
+ });
5
11
  export async function runPromptTurn(state, input) {
6
12
  const pending = state.link.prompt({
7
13
  sessionId: state.agentSessionId,
@@ -11,17 +17,27 @@ export async function runPromptTurn(state, input) {
11
17
  switch (outcome.kind) {
12
18
  case "ok":
13
19
  return resultOf(outcome.value, input.collector);
14
- case "failed":
15
- throw await promptFailure(state, outcome.error);
16
- default:
17
- await cancelTurn(state, pending);
18
- throw abortReason(input.signal);
20
+ case "failed": {
21
+ const error = await promptFailure(state, outcome.error);
22
+ attachTurnSpend(error, NO_RESPONSE_SPEND);
23
+ throw error;
24
+ }
25
+ default: {
26
+ const response = await cancelTurn(state, pending);
27
+ const reason = abortReason(input.signal);
28
+ // #2367: an answer inside the grace still reports what the turn spent.
29
+ attachTurnSpend(reason, response === undefined ? NO_RESPONSE_SPEND : input.collector.settle(response));
30
+ throw reason;
31
+ }
19
32
  }
20
33
  }
21
34
  function resultOf(response, collector) {
22
35
  const spend = collector.settle(response);
23
- if (response.stopReason !== "end_turn")
24
- throw stopReasonError(String(response.stopReason));
36
+ if (response.stopReason !== "end_turn") {
37
+ const error = stopReasonError(String(response.stopReason));
38
+ attachTurnSpend(error, spend);
39
+ throw error;
40
+ }
25
41
  return {
26
42
  output: collector.output(),
27
43
  tokenUsage: spend.tokenUsage,
@@ -37,13 +53,17 @@ async function promptFailure(state, error) {
37
53
  state.disconnect();
38
54
  return agentGoneError("session/prompt", state.launched, state.secrets);
39
55
  }
56
+ /** session/cancel, then cancelGraceMs for the prompt to answer; past that the process is killed. */
40
57
  async function cancelTurn(state, pending) {
41
58
  await state.link.cancel(state.agentSessionId).catch(() => undefined);
42
59
  const settled = await race(pending, { timeoutMs: state.cancelGraceMs });
60
+ if (settled.kind === "ok")
61
+ return settled.value;
43
62
  if (settled.kind === "timeout") {
44
63
  state.launched.kill();
45
64
  state.disconnect();
46
65
  }
66
+ return undefined;
47
67
  }
48
68
  function abortReason(signal) {
49
69
  return signal.reason instanceof Error
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nathapp/nax-agent-acp",
3
- "version": "0.3.0",
3
+ "version": "0.3.1",
4
4
  "description": "ACP (Agent Client Protocol) backend for @nathapp/nax-agent sessions: drive Claude Code and other ACP agents through the nax-agent session API.",
5
5
  "license": "MIT",
6
6
  "author": "William Khoo",
@@ -46,12 +46,12 @@
46
46
  "zod": "^4.3.6"
47
47
  },
48
48
  "peerDependencies": {
49
- "@nathapp/nax-agent": "^0.3.0"
49
+ "@nathapp/nax-agent": "^0.3.1"
50
50
  },
51
51
  "publishConfig": {
52
52
  "access": "public",
53
53
  "registry": "https://registry.npmjs.org/",
54
- "provenance": false,
54
+ "provenance": true,
55
55
  "tag": "latest"
56
56
  }
57
57
  }