@nathapp/nax-agent-acp 0.91.7-canary.8 → 0.91.7

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,26 @@
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.91.7] - 2026-11-01
7
+
8
+ - No changes in this package. Released in lockstep with the other nax packages.
9
+
10
+ ## [0.91.7-canary.12] - 2026-11-01
11
+
12
+ - No changes in this package. Released in lockstep with the other nax packages.
13
+
14
+ ## [0.91.7-canary.11] - 2026-10-31
15
+
16
+ - No changes in this package. Released in lockstep with the other nax packages.
17
+
18
+ ## [0.91.7-canary.10] - 2026-10-30
19
+
20
+ - No changes in this package. Released in lockstep with the other nax packages.
21
+
22
+ ## [0.91.7-canary.9] - 2026-10-30
23
+
24
+ - No changes in this package. Released in lockstep with the other nax packages.
25
+
6
26
  ## [0.91.7-canary.8] - 2026-10-29
7
27
 
8
28
  - No changes in this package. Released in lockstep with the other nax packages.
package/README.md CHANGED
@@ -167,7 +167,7 @@ MCP server this client runs for the session.
167
167
  stored in the transcript.
168
168
  - **The name `nax` is reserved.** If your Claude user or project settings define an
169
169
  MCP server named `nax`, it can collide with this one. Rename yours.
170
- - **Pre-approved at the agent.** Claude is told to allow exactly `mcp__nax__<tool>`
170
+ - **Pre-approved at the agent.** Claude is told to allow exactly `mcp__nax-<8 hex>__<tool>`
171
171
  for each of your tools, so it never asks permission for them. Your tool's own
172
172
  `approval` is the only gate: `"always"` asks you through `approval_requested` and
173
173
  `answer()` under every profile; `"never"` runs under every profile.
@@ -198,7 +198,7 @@ differences.
198
198
  - **Tool calls.** `tool_call` is sent when the agent uses the call: it asks
199
199
  permission for it, reports progress, or finishes. It is not sent when the call is
200
200
  first mentioned, because Claude fills in a call's input after mentioning it.
201
- `name` is the agent's tool name (with Claude: `Read`, `Bash`, `mcp__nax__<tool>`).
201
+ `name` is the agent's tool name (with Claude: `Read`, `Bash`, `mcp__nax-<8 hex>__<tool>`).
202
202
  Every `tool_call` is followed by exactly one `tool_result`. A call still running
203
203
  when the turn ends gets `isError: true` and `"Not answered: the turn ended."`. A
204
204
  call the agent mentions but never uses produces no events.
@@ -25,11 +25,12 @@ import { type InboundRouter } from "#src/client/inbound";
25
25
  import { type LaunchFn } from "#src/client/launch";
26
26
  import { type AcpBackendOptions } from "#src/client/options";
27
27
  import { createToolHost, type ToolHost } from "#src/client/tool-host";
28
- /** Test seam: the process launcher and the tool host factory. Production always uses launchAgent and createToolHost. */
28
+ /** Test seam: the process launcher, the tool host factory and its server name. Production always uses launchAgent, createToolHost and newToolHostServerName. */
29
29
  export declare const _acpBackendDeps: {
30
30
  launch: LaunchFn;
31
31
  createToolHost: typeof createToolHost;
32
+ newToolHostServerName: () => string;
32
33
  };
33
34
  export declare function acpBackend(input: AcpBackendOptions): SessionBackend;
34
35
  /** Exported for its unit test; `./client` does not re-export it. */
35
- export declare function toolHostFor(ctx: BackendOpenContext, router: InboundRouter, secrets: readonly string[], token: string | undefined): ToolHost | undefined;
36
+ export declare function toolHostFor(ctx: BackendOpenContext, router: InboundRouter, secrets: readonly string[], token: string | undefined, serverName?: string): ToolHost | undefined;
@@ -20,7 +20,7 @@
20
20
  * is written to the transcript document after each priced turn, so a resume in a
21
21
  * new process prices its first turn from it (D6-a).
22
22
  */
23
- import { getLogger, NO_OP_INTERACTION_HANDLER, } from "@nathapp/nax-agent";
23
+ import { getLogger, NaxError, NO_OP_INTERACTION_HANDLER, } from "@nathapp/nax-agent";
24
24
  import { answerElicitation } from "#src/client/elicitation";
25
25
  import { sessionLost } from "#src/client/errors";
26
26
  import { createTurnCollector } from "#src/client/events";
@@ -28,18 +28,21 @@ import { createInboundRouter } from "#src/client/inbound";
28
28
  import { launchAgent } from "#src/client/launch";
29
29
  import { openAcpSession } from "#src/client/open";
30
30
  import { resolveAcpOptions } from "#src/client/options";
31
+ import { createOwnToolLedger } from "#src/client/own-tool-calls";
31
32
  import { decidePermission } from "#src/client/permissions";
32
33
  import { race } from "#src/client/race";
33
34
  import { canRestore, storedSessionOf } from "#src/client/resume";
35
+ import { configureAcpSession } from "#src/client/session-configure";
34
36
  import { shellSandboxPlan } from "#src/client/shell-sandbox";
35
37
  import { createToolCalls } from "#src/client/tool-calls";
36
- import { createToolHost, newToolHostToken } from "#src/client/tool-host";
38
+ import { createToolHost, newToolHostServerName, newToolHostToken } from "#src/client/tool-host";
37
39
  import { runPromptTurn } from "#src/client/turn";
38
40
  import { createCostMeter } from "#src/client/usage";
39
- /** Test seam: the process launcher and the tool host factory. Production always uses launchAgent and createToolHost. */
41
+ /** Test seam: the process launcher, the tool host factory and its server name. Production always uses launchAgent, createToolHost and newToolHostServerName. */
40
42
  export const _acpBackendDeps = {
41
43
  launch: launchAgent,
42
44
  createToolHost,
45
+ newToolHostServerName,
43
46
  };
44
47
  export function acpBackend(input) {
45
48
  const options = resolveAcpOptions(input);
@@ -61,7 +64,7 @@ function toolHostOptions(ctx) {
61
64
  return instructions === undefined || instructions === "" ? undefined : { instructions };
62
65
  }
63
66
  /** Exported for its unit test; `./client` does not re-export it. */
64
- export function toolHostFor(ctx, router, secrets, token) {
67
+ export function toolHostFor(ctx, router, secrets, token, serverName) {
65
68
  if (token === undefined)
66
69
  return undefined;
67
70
  const calls = createToolCalls({
@@ -72,7 +75,8 @@ export function toolHostFor(ctx, router, secrets, token) {
72
75
  turnSignal: () => router.activeSignal(),
73
76
  secrets,
74
77
  });
75
- return _acpBackendDeps.createToolHost(calls, token, toolHostOptions(ctx));
78
+ const options = serverName === undefined ? toolHostOptions(ctx) : { ...(toolHostOptions(ctx) ?? {}), serverName };
79
+ return _acpBackendDeps.createToolHost(calls, token, options);
76
80
  }
77
81
  /**
78
82
  * Permission requests and elicitations, decided by profile with the session's
@@ -81,8 +85,10 @@ export function toolHostFor(ctx, router, secrets, token) {
81
85
  * other, a policy there would approve an escalation the agent never sandboxed.
82
86
  * US-003: the agent's name (which raw field carries a shell command) and the
83
87
  * session's rules join it too, so review with no sandbox can adjudicate a command.
88
+ * US-004: an agent that reports MCP calls in structured fields (Codex, Cursor) gets a
89
+ * per-turn own-tool ledger, so a proven call to the session's own tool host is allowed once.
84
90
  */
85
- function routerFor(ctx, options) {
91
+ function routerFor(ctx, options, serverName) {
86
92
  const entry = options.entry;
87
93
  const sandbox = entry?.preApproval !== undefined && ctx.sandbox?.kind === "policy" ? ctx.sandbox.policy : undefined;
88
94
  const base = {
@@ -110,18 +116,23 @@ function routerFor(ctx, options) {
110
116
  },
111
117
  }),
112
118
  };
113
- return createInboundRouter((request, signal) => decidePermission(request, { ...base, signal }), (request, signal) => answerElicitation(request, { ...base, signal }));
119
+ const identityKind = entry?.mcpCallIdentity;
120
+ const toolNames = ctx.tools.map((t) => t.name);
121
+ const ownTools = identityKind === undefined || serverName === undefined || toolNames.length === 0
122
+ ? undefined
123
+ : () => createOwnToolLedger({ kind: identityKind, serverName, toolNames });
124
+ return createInboundRouter((request, signal, isOwnToolCall) => decidePermission(request, { ...base, signal, ...(isOwnToolCall === undefined ? {} : { isOwnToolCall }) }), (request, signal) => answerElicitation(request, { ...base, signal }), ownTools);
114
125
  }
115
126
  /** One agent process: a new agent session, or `restore` restored in it (§6.3 step 1, §6.9). */
116
- async function connect(base, ctx, restore, retiredTokens) {
127
+ async function connect(base, ctx, restore, retiredTokens, serverName) {
117
128
  const token = ctx.tools.length > 0 ? newToolHostToken() : undefined;
118
129
  const tokens = token === undefined ? retiredTokens : [...retiredTokens, token];
119
130
  const tokenOptions = withTokens(base, tokens);
120
131
  const plan = await shellSandboxPlan(ctx.profile, tokenOptions, ctx.sandbox, ctx.workdir);
121
132
  const options = Object.freeze({ ...tokenOptions, ...(plan === undefined ? {} : { shellSandboxPlan: plan }) });
122
133
  const gone = new AbortController();
123
- const router = routerFor(ctx, options);
124
- const host = toolHostFor(ctx, router, options.secrets, token);
134
+ const router = routerFor(ctx, options, serverName);
135
+ const host = toolHostFor(ctx, router, options.secrets, token, serverName);
125
136
  const acp = await openAcpSession(options, ctx, router.handlers, _acpBackendDeps.launch, host, restore).catch(async (err) => {
126
137
  await host?.stop();
127
138
  throw err;
@@ -147,10 +158,13 @@ async function connect(base, ctx, restore, retiredTokens) {
147
158
  async function openBackend(base, ctx) {
148
159
  // §6.9 step 1 runs before anything is spawned.
149
160
  const restore = ctx.resume === undefined ? undefined : storedSessionOf(ctx.resume.doc, ctx, base);
150
- const live = await connect(base, ctx, restore, []);
161
+ const serverName = ctx.tools.length > 0 ? _acpBackendDeps.newToolHostServerName() : undefined;
162
+ const live = await connect(base, ctx, restore, [], serverName);
151
163
  return assemble({
152
164
  base,
165
+ configOptions: live.acp.configOptions,
153
166
  ctx,
167
+ serverName,
154
168
  live,
155
169
  closing: undefined,
156
170
  // A restored agent already holds the instructions once a turn has run (D6-f).
@@ -161,8 +175,13 @@ async function openBackend(base, ctx) {
161
175
  }
162
176
  /** D6-h: the live process's capability record; a restored process adds restoredWith. */
163
177
  function infoOf(s) {
164
- const { record, restoredWith } = s.live.acp;
165
- const capabilities = restoredWith === undefined ? { ...record } : { ...record, restoredWith };
178
+ const { record, restoredWith, offered } = s.live.acp;
179
+ const capabilities = {
180
+ ...record,
181
+ offeredModels: offered.models,
182
+ offeredEfforts: offered.efforts,
183
+ ...(restoredWith === undefined ? {} : { restoredWith }),
184
+ };
166
185
  return Object.freeze({ kind: s.base.kind, capabilities: Object.freeze(capabilities) });
167
186
  }
168
187
  function assemble(s) {
@@ -181,6 +200,8 @@ function assemble(s) {
181
200
  return infoOf(s);
182
201
  },
183
202
  turnOpts: () => ({ interactionHandler: NO_OP_INTERACTION_HANDLER }),
203
+ acceptsImages: async () => s.live.acp.record.image,
204
+ configure: (change) => configure(s, change),
184
205
  close: () => {
185
206
  s.closing ??= shutdown(s);
186
207
  return s.closing;
@@ -215,7 +236,8 @@ async function reconnect(s, signal) {
215
236
  // close() aborts openSignal; cancel() and the turn timeout abort the turn signal.
216
237
  const ctx = { ...s.ctx, openSignal: AbortSignal.any([s.ctx.openSignal, signal]) };
217
238
  try {
218
- s.live = await connect(s.base, ctx, restore, old.tokens);
239
+ s.live = await connect(s.base, ctx, restore, old.tokens, s.serverName);
240
+ s.configOptions = s.live.acp.configOptions;
219
241
  return s.live;
220
242
  }
221
243
  catch (err) {
@@ -224,9 +246,30 @@ async function reconnect(s, signal) {
224
246
  throw err;
225
247
  }
226
248
  }
249
+ /** US-002: model and effort set on the live process; each accepted part is recorded for a reconnect. */
250
+ async function configure(s, change) {
251
+ const live = await liveFor(s, s.ctx.openSignal);
252
+ await configureAcpSession({
253
+ link: live.acp.link,
254
+ agentSessionId: live.acp.agentSessionId,
255
+ agentName: s.base.agentName,
256
+ secrets: live.options.secrets,
257
+ timeoutMs: s.base.initializeTimeoutMs,
258
+ signal: s.ctx.openSignal,
259
+ sessionId: s.ctx.sessionId,
260
+ configOptions: s.configOptions,
261
+ change,
262
+ }, (part, configOptions) => {
263
+ s.base = Object.freeze({ ...s.base, ...part });
264
+ s.configOptions = configOptions;
265
+ });
266
+ }
227
267
  async function sendTurn(s, prompt, opts) {
228
268
  const signal = opts.signal ?? s.ctx.turnSignal();
229
269
  const live = await liveFor(s, signal);
270
+ if (opts.images?.length && !live.acp.record.image) {
271
+ throw new NaxError("[acp] The agent does not support image input", "ACP_IMAGE_INPUT_UNSUPPORTED", { stage: "acp" });
272
+ }
230
273
  const instructions = s.instructionsSent ? undefined : s.ctx.instructions;
231
274
  const text = instructions === undefined || instructions === "" ? prompt : `${instructions}\n\n${prompt}`;
232
275
  // #2364: delivered once the agent shows it has the prompt, not when it is sent.
@@ -243,7 +286,12 @@ async function sendTurn(s, prompt, opts) {
243
286
  });
244
287
  const release = live.router.attach(live.acp.agentSessionId, collector, AbortSignal.any([signal, live.gone.signal]));
245
288
  try {
246
- return await runPromptTurn(live.state, { text, signal, collector });
289
+ return await runPromptTurn(live.state, {
290
+ text,
291
+ signal,
292
+ collector,
293
+ ...(opts.images === undefined ? {} : { images: opts.images }),
294
+ });
247
295
  }
248
296
  finally {
249
297
  await release();
@@ -17,10 +17,13 @@ export type CapabilityRecord = {
17
17
  readonly resume: boolean;
18
18
  readonly close: boolean;
19
19
  readonly mcpHttp: boolean;
20
+ readonly image: boolean;
20
21
  /** The registry can enforce profiles none/read on this agent. */
21
22
  readonly readOnlyMode: boolean;
22
23
  /** The registry knows how to pre-approve embedder tools at the adapter (R12). */
23
24
  readonly preApproval: boolean;
25
+ /** The registry knows the structured shape this agent reports MCP tool calls in. */
26
+ readonly ownToolCalls: boolean;
24
27
  };
25
28
  export interface Requirements {
26
29
  readonly profile: AgentSessionProfile;
@@ -23,8 +23,10 @@ export function buildCapabilityRecord(init, entry) {
23
23
  resume: isObject(caps.sessionCapabilities?.resume),
24
24
  close: isObject(caps.sessionCapabilities?.close),
25
25
  mcpHttp: caps.mcpCapabilities?.http === true,
26
+ image: caps.promptCapabilities?.image === true,
26
27
  readOnlyMode: entry?.readOnly !== undefined,
27
28
  preApproval: entry?.preApproval !== undefined,
29
+ ownToolCalls: entry?.mcpCallIdentity !== undefined,
28
30
  });
29
31
  }
30
32
  /** none, read and review (nax#2500) run with the agent's own write tools removed. */
@@ -39,8 +41,11 @@ export function unmetRequirement(record, req) {
39
41
  reason: `profile "${req.profile}" needs read-only enforcement; this agent has none`,
40
42
  };
41
43
  }
42
- if (req.toolCount > 0 && !(record.mcpHttp && record.preApproval)) {
43
- return { capability: "tools", reason: "embedder tools need HTTP MCP support and adapter pre-approval" };
44
+ if (req.toolCount > 0 && !(record.mcpHttp && (record.preApproval || record.ownToolCalls))) {
45
+ return {
46
+ capability: "tools",
47
+ reason: "embedder tools need HTTP MCP support and adapter pre-approval or a known MCP call identity",
48
+ };
44
49
  }
45
50
  if (req.resume && !(record.resume || record.loadSession)) {
46
51
  return { capability: "resume", reason: "the agent supports neither session/resume nor session/load" };
@@ -18,9 +18,12 @@
18
18
  import type { CreateElicitationRequest, CreateElicitationResponse, RequestPermissionRequest, RequestPermissionResponse } from "@agentclientprotocol/sdk";
19
19
  import type { InboundHandlers } from "#src/client/connection";
20
20
  import type { TurnCollector } from "#src/client/events";
21
+ import type { OwnToolLedger } from "#src/client/own-tool-calls";
21
22
  /** Concurrent permission requests and elicitations one turn may hold; further ones are answered locally. */
22
23
  export declare const MAX_PENDING_DECISIONS = 16;
23
- export type PermissionDecider = (request: RequestPermissionRequest, signal: AbortSignal) => Promise<RequestPermissionResponse>;
24
+ export type PermissionDecider = (request: RequestPermissionRequest, signal: AbortSignal,
25
+ /** True for a tool call id this turn's own-tool ledger proved is the session's own tool host's. */
26
+ isOwnToolCall?: (toolCallId: string) => boolean) => Promise<RequestPermissionResponse>;
24
27
  export type ElicitationHandler = (request: CreateElicitationRequest, signal: AbortSignal) => Promise<CreateElicitationResponse>;
25
28
  export interface InboundRouter {
26
29
  readonly handlers: InboundHandlers;
@@ -38,4 +41,4 @@ export interface InboundRouter {
38
41
  */
39
42
  activeSignal(): AbortSignal | undefined;
40
43
  }
41
- export declare function createInboundRouter(decide: PermissionDecider, elicit?: ElicitationHandler): InboundRouter;
44
+ export declare function createInboundRouter(decide: PermissionDecider, elicit?: ElicitationHandler, ownTools?: () => OwnToolLedger): InboundRouter;
@@ -23,7 +23,7 @@ async function track(binding, answer) {
23
23
  function sessionOf(request) {
24
24
  return isRecord(request) && typeof request.sessionId === "string" ? request.sessionId : undefined;
25
25
  }
26
- export function createInboundRouter(decide, elicit = cancelElicitation) {
26
+ export function createInboundRouter(decide, elicit = cancelElicitation, ownTools) {
27
27
  let active;
28
28
  const logged = new Set();
29
29
  const log = (kind, reason) => {
@@ -53,6 +53,7 @@ export function createInboundRouter(decide, elicit = cancelElicitation) {
53
53
  handlers: {
54
54
  onUpdate(notification) {
55
55
  if (active !== undefined && notification.sessionId === active.sessionId) {
56
+ active.ledger?.observe(notification.update);
56
57
  active.collector.onUpdate(notification.update);
57
58
  }
58
59
  },
@@ -67,7 +68,9 @@ export function createInboundRouter(decide, elicit = cancelElicitation) {
67
68
  if (!admitted.signal.aborted)
68
69
  admitted.collector.announce(request.toolCall);
69
70
  let decided = true;
70
- const answer = await track(admitted, decide(request, admitted.signal).catch(() => {
71
+ const ledger = admitted.ledger;
72
+ const isOwnToolCall = (toolCallId) => ledger?.isOwn(toolCallId) ?? false;
73
+ const answer = await track(admitted, decide(request, admitted.signal, isOwnToolCall).catch(() => {
71
74
  decided = false;
72
75
  return cancelled();
73
76
  }));
@@ -96,6 +99,7 @@ export function createInboundRouter(decide, elicit = cancelElicitation) {
96
99
  scope,
97
100
  signal: AbortSignal.any([scope.signal, turnSignal]),
98
101
  pending: new Set(),
102
+ ledger: ownTools?.(),
99
103
  };
100
104
  active = binding;
101
105
  return async () => {
@@ -12,7 +12,7 @@ export { acpBackend } from "#src/client/backend";
12
12
  export { ACP_STOP_CODES, type AcpStopCode } from "#src/client/errors";
13
13
  export { isAgentLaunchable, type LaunchCandidateKind, launchCandidateKind } from "#src/client/launchable";
14
14
  export type { AcpAgentSpec, AcpBackendOptions, AcpProcessHooks } from "#src/client/options";
15
- export { TOOL_HOST_SERVER_NAME } from "#src/client/pre-approval";
15
+ export { parseToolHostToolName, TOOL_HOST_SERVER_NAME } from "#src/client/pre-approval";
16
16
  export type { AcpAgentName, AgentRegistryEntry } from "#src/client/registry";
17
17
  export { registryEntry } from "#src/client/registry";
18
18
  export type { AcpPermissionRules, AcpRule } from "#src/client/rule-policy";
@@ -11,5 +11,5 @@
11
11
  export { acpBackend } from "#src/client/backend";
12
12
  export { ACP_STOP_CODES } from "#src/client/errors";
13
13
  export { isAgentLaunchable, launchCandidateKind } from "#src/client/launchable";
14
- export { TOOL_HOST_SERVER_NAME } from "#src/client/pre-approval";
14
+ export { parseToolHostToolName, TOOL_HOST_SERVER_NAME } from "#src/client/pre-approval";
15
15
  export { registryEntry } from "#src/client/registry";
@@ -0,0 +1,8 @@
1
+ import type { SessionOffers } from "#src/client/session-offers";
2
+ export interface OfferedChoices {
3
+ readonly models: readonly string[];
4
+ readonly efforts: readonly string[];
5
+ }
6
+ /** At most this many ids per list. */
7
+ export declare const MAX_OFFERED_CHOICES = 50;
8
+ export declare function offeredChoices(offers: SessionOffers, agentName: string, secrets: readonly string[]): OfferedChoices;
@@ -0,0 +1,52 @@
1
+ /**
2
+ * The models and efforts a live ACP agent offers, as plain ids the embedder can show
3
+ * and pass back (chat-acp-brain US-001). Reported in the capability record, so nax
4
+ * never starts an agent just to list them. The ids are agent data: each one that
5
+ * cleanLabel would change (control characters, whitespace runs, a session secret, more
6
+ * than MODEL_ID_MAX_CHARS characters) is dropped rather than shown altered, so an id
7
+ * reported here is exactly the id the agent offered.
8
+ */
9
+ import { EFFORT_FALLBACK_IDS, MODEL_ID_MAX_CHARS, selectValues } from "#src/client/capabilities";
10
+ import { cleanLabel } from "#src/client/text";
11
+ /** At most this many ids per list. */
12
+ export const MAX_OFFERED_CHOICES = 50;
13
+ /** Duplicates dropped (first kept), then every id cleanLabel would alter, then the cap. */
14
+ function sanitized(ids, secrets) {
15
+ const seen = new Set();
16
+ const kept = [];
17
+ for (const id of ids) {
18
+ if (seen.has(id))
19
+ continue;
20
+ seen.add(id);
21
+ if (cleanLabel(id, secrets, MODEL_ID_MAX_CHARS) !== id)
22
+ continue;
23
+ kept.push(id);
24
+ if (kept.length === MAX_OFFERED_CHOICES)
25
+ break;
26
+ }
27
+ return Object.freeze(kept);
28
+ }
29
+ /** Every category "model" option's values in offer order, then the legacy models block's ids. */
30
+ function modelIds(offers) {
31
+ const fromOptions = offers.configOptions
32
+ .filter((option) => option.category === "model")
33
+ .flatMap((option) => selectValues(option));
34
+ return [...fromOptions, ...offers.modelIds];
35
+ }
36
+ /** The first "thought_level" option's values, else those of the agent's fallback option id, else none. */
37
+ function effortIds(offers, agentName) {
38
+ const byCategory = offers.configOptions.find((option) => option.category === "thought_level");
39
+ if (byCategory !== undefined)
40
+ return selectValues(byCategory);
41
+ const fallbackId = Object.hasOwn(EFFORT_FALLBACK_IDS, agentName) ? EFFORT_FALLBACK_IDS[agentName] : undefined;
42
+ if (fallbackId === undefined)
43
+ return [];
44
+ const option = offers.configOptions.find((candidate) => candidate.id === fallbackId);
45
+ return option === undefined ? [] : selectValues(option);
46
+ }
47
+ export function offeredChoices(offers, agentName, secrets) {
48
+ return Object.freeze({
49
+ models: sanitized(modelIds(offers), secrets),
50
+ efforts: sanitized(effortIds(offers, agentName), secrets),
51
+ });
52
+ }
@@ -11,11 +11,12 @@
11
11
  * bounded by initializeTimeoutMs (D-c) and by openSignal: close() during open
12
12
  * rejects AGENT_SESSION_CLOSED.
13
13
  */
14
- import { type ClientCapabilities } from "@agentclientprotocol/sdk";
14
+ import { type ClientCapabilities, type SessionConfigOption } from "@agentclientprotocol/sdk";
15
15
  import { type AgentSessionProfile, type BackendOpenContext } from "@nathapp/nax-agent";
16
16
  import { type CapabilityRecord } from "#src/client/capabilities";
17
17
  import { type AcpLink, type InboundHandlers } from "#src/client/connection";
18
18
  import { type LaunchedAgent, type LaunchFn } from "#src/client/launch";
19
+ import { type OfferedChoices } from "#src/client/offered-choices";
19
20
  import type { ResolvedAcpOptions } from "#src/client/options";
20
21
  import { type Restore, type RestoredWith } from "#src/client/resume";
21
22
  import type { ToolHost } from "#src/client/tool-host";
@@ -30,8 +31,17 @@ export interface OpenedAcp {
30
31
  readonly restoredWith?: RestoredWith;
31
32
  /** The startup banner session/new announced (nax#2591); turns drop it from their output. */
32
33
  readonly startupBanner?: string;
34
+ /** The models and efforts the agent offered once the mode and model were applied. */
35
+ readonly offered: OfferedChoices;
36
+ /**
37
+ * The config options the agent last reported: the answer to the last config request open
38
+ * sent, else the session/new or restore answer's. `configure` resolves against them.
39
+ */
40
+ readonly configOptions: readonly SessionConfigOption[];
33
41
  }
34
42
  /** `restore`: restore that stored agent session instead of creating one (§6.9). */
35
43
  export declare function openAcpSession(options: ResolvedAcpOptions, ctx: BackendOpenContext, handlers: InboundHandlers, launch: LaunchFn, host?: ToolHost, restore?: Restore): Promise<OpenedAcp>;
36
44
  /** §6.3 step 1.1: no fs and no terminal (R11); form elicitation under ask and full (§6.8, D5-l). */
37
45
  export declare function clientCapabilitiesFor(profile: AgentSessionProfile): ClientCapabilities;
46
+ /** The model ids the config options offer, raw: category "model" values in offer order. */
47
+ export declare function configModelIds(options: readonly SessionConfigOption[]): string[];
@@ -17,6 +17,7 @@ import { buildCapabilityRecord, effortOptionId, MODEL_ID_MAX_CHARS, modeFor, mod
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";
20
+ import { offeredChoices } from "#src/client/offered-choices";
20
21
  import { claudeSessionMeta } from "#src/client/pre-approval";
21
22
  import { race } from "#src/client/race";
22
23
  import { isUsableSessionId, restoreSession, } from "#src/client/resume";
@@ -124,7 +125,7 @@ async function establish(o) {
124
125
  const session = o.restore === undefined
125
126
  ? await newSession(o, setup)
126
127
  : await restoreSession(o.restore, record, setup, o.link, (label, request) => step(o, label, request));
127
- await applyConfig(o, session.agentSessionId, session.offers);
128
+ const applied = await applyConfig(o, session.agentSessionId, session.offers);
128
129
  if (o.restore === undefined) {
129
130
  await o.ctx.transcriptStore.save(o.ctx.sessionId, initialDoc(o, record, session.agentSessionId));
130
131
  }
@@ -134,6 +135,8 @@ async function establish(o) {
134
135
  record,
135
136
  agentSessionId: session.agentSessionId,
136
137
  cwd: session.cwd,
138
+ offered: offeredChoices(applied.offers, o.options.agentName, o.options.secrets),
139
+ configOptions: applied.configOptions,
137
140
  ...(session.restoredWith === undefined ? {} : { restoredWith: session.restoredWith }),
138
141
  ...(session.startupBanner === undefined ? {} : { startupBanner: session.startupBanner }),
139
142
  };
@@ -171,24 +174,30 @@ function sandboxFor(ctx, entry) {
171
174
  /** §6.3 step 3: start the tool host when the session has tools; its entry and Claude's `_meta` (§6.6, #2365). */
172
175
  async function sessionSetup(o, sandbox) {
173
176
  const kind = o.options.entry?.preApproval;
174
- const meta = claudeSessionMeta(kind, o.ctx.tools.map((tool) => tool.name), readOnlyFor(o.ctx.profile, o.options.entry), {
177
+ const meta = claudeSessionMeta(kind, o.host?.serverName ?? "", o.ctx.tools.map((tool) => tool.name), readOnlyFor(o.ctx.profile, o.options.entry), {
175
178
  ...(sandbox === undefined ? {} : { sandbox }),
176
179
  ...(o.ctx.profile === "full" ? { lockSkipPermissions: true } : {}),
177
180
  });
178
181
  if (o.host === undefined)
179
182
  return meta === undefined ? { mcpServers: [] } : { mcpServers: [], _meta: { ...meta } };
180
- if (meta === undefined)
183
+ // An agent with no pre-approval channel but a known MCP call identity (codex, cursor) gets the
184
+ // host entry alone: nax recognises its calls by their shape, not by an adapter-side allow rule.
185
+ if (meta === undefined && o.options.entry?.mcpCallIdentity === undefined) {
181
186
  throw capabilityUnsupported("tools", "the agent has no way to pre-approve embedder tools");
187
+ }
182
188
  const server = await o.host.start().catch((err) => {
183
189
  throw backendUnavailable(`the tool host could not start: ${err instanceof Error ? err.message : String(err)}`);
184
190
  });
191
+ if (meta === undefined)
192
+ return { mcpServers: [server] };
185
193
  return { mcpServers: [server], _meta: { ...meta } };
186
194
  }
187
195
  /** §6.3 step 5: the profile's mode, then the model, then the effort (S4b). Only values the agent offered are set. */
188
196
  async function applyConfig(o, sessionId, offers) {
189
197
  const afterMode = await applyMode(o, sessionId, offers);
190
198
  const afterModel = await applyModel(o, sessionId, afterMode);
191
- await applyEffort(o, sessionId, afterModel);
199
+ const afterEffort = await applyEffort(o, sessionId, afterModel);
200
+ return { offers: afterModel, configOptions: afterEffort.configOptions };
192
201
  }
193
202
  /**
194
203
  * The profile's mode. A config option offering the value is used first (the ACP 1.x
@@ -213,12 +222,12 @@ async function applyMode(o, sessionId, offers) {
213
222
  /** At most this many offered ids, each cleaned and capped, go into a model refusal (agent-supplied text). */
214
223
  const MAX_OFFERED_MODELS = 50;
215
224
  /** The model ids the config options offer, raw: category "model" values in offer order. */
216
- function configModelIds(offers) {
217
- return offers.configOptions.filter((option) => option.category === "model").flatMap((option) => selectValues(option));
225
+ export function configModelIds(options) {
226
+ return options.filter((option) => option.category === "model").flatMap((option) => selectValues(option));
218
227
  }
219
228
  /** The model ids a refusal names: the config options' ids first, then the legacy `models` block's, capped. */
220
229
  function offeredModels(offers, secrets) {
221
- return [...configModelIds(offers), ...offers.modelIds]
230
+ return [...configModelIds(offers.configOptions), ...offers.modelIds]
222
231
  .slice(0, MAX_OFFERED_MODELS)
223
232
  .map((id) => cleanLabel(id, secrets, MODEL_ID_MAX_CHARS) ?? "")
224
233
  .filter((id) => id !== "");
@@ -235,7 +244,7 @@ async function applyModel(o, sessionId, offers) {
235
244
  const requested = o.options.model;
236
245
  if (requested === undefined)
237
246
  return offers;
238
- const fromOptions = configModelIds(offers);
247
+ const fromOptions = configModelIds(offers.configOptions);
239
248
  const model = resolveModelValue(o.options.agentName, fromOptions.length > 0 ? fromOptions : offers.modelIds, requested, o.options.secrets);
240
249
  const configId = modelOptionId(offers.configOptions, model);
241
250
  if (configId !== undefined) {
@@ -253,16 +262,17 @@ async function applyModel(o, sessionId, offers) {
253
262
  async function applyEffort(o, sessionId, offers) {
254
263
  const effort = o.options.effort;
255
264
  if (effort === undefined)
256
- return;
265
+ return offers;
257
266
  const configId = effortOptionId(offers.configOptions, o.options.agentName, effort);
258
267
  if (configId === undefined) {
259
268
  getLogger().warn("acp", "The agent offers no effort option for this value; effort skipped", {
260
269
  agent: o.options.agentName,
261
270
  effort,
262
271
  });
263
- return;
272
+ return offers;
264
273
  }
265
- await step(o, "session/set_config_option", o.link.setConfigOption({ sessionId, configId, value: effort }));
274
+ const set = await step(o, "session/set_config_option", o.link.setConfigOption({ sessionId, configId, value: effort }));
275
+ return { ...offers, configOptions: set.configOptions ?? offers.configOptions };
266
276
  }
267
277
  function initialDoc(o, record, agentSessionId) {
268
278
  return {
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Which tool calls are the session's own embedder tools, read from the agent's
3
+ * structured MCP fields (never a title or display name). Codex reports
4
+ * `rawInput: { server, tool }`, Cursor `rawInput: { providerIdentifier, toolName }`,
5
+ * on a tool_call or a tool_call_update alike. This is authorization evidence, kept
6
+ * apart from tool-events.ts's scrubbed and capped presentation state. The ledger is
7
+ * built for one turn and dropped with it.
8
+ */
9
+ import type { SessionUpdate } from "@agentclientprotocol/sdk";
10
+ export type McpCallIdentityKind = "codex" | "cursor";
11
+ export interface McpCallIdentity {
12
+ readonly toolCallId: string;
13
+ readonly server: string;
14
+ readonly tool: string;
15
+ }
16
+ /**
17
+ * The identity a tool_call / tool_call_update reports in its structured rawInput:
18
+ * codex `{ server, tool }`, cursor `{ providerIdentifier, toolName }` (both string).
19
+ * Never reads the title. Undefined for any other update or shape.
20
+ */
21
+ export declare function mcpCallIdentityOf(kind: McpCallIdentityKind, update: SessionUpdate): McpCallIdentity | undefined;
22
+ export interface OwnToolLedger {
23
+ observe(update: SessionUpdate): void;
24
+ /** True only when every identity seen for this id names serverName and a tool in toolNames. */
25
+ isOwn(toolCallId: string): boolean;
26
+ }
27
+ /** At most this many distinct tool call ids are tracked per turn (the ledger lives for one turn). */
28
+ export declare const MAX_OWN_TOOL_CALLS = 512;
29
+ /** An id longer than this is never tracked, so never own. */
30
+ export declare const MAX_OWN_TOOL_CALL_ID_CHARS = 256;
31
+ /** A server or tool name longer than this is stored as a conflict (never own), not kept. */
32
+ export declare const MAX_OWN_TOOL_FIELD_CHARS = 256;
33
+ export declare function createOwnToolLedger(input: {
34
+ readonly kind: McpCallIdentityKind;
35
+ readonly serverName: string;
36
+ readonly toolNames: readonly string[];
37
+ }): OwnToolLedger;
@@ -0,0 +1,62 @@
1
+ import { isRecord } from "#src/client/text";
2
+ const FIELDS = {
3
+ codex: { server: "server", tool: "tool" },
4
+ cursor: { server: "providerIdentifier", tool: "toolName" },
5
+ };
6
+ const nonEmpty = (value) => typeof value === "string" && value !== "";
7
+ /**
8
+ * The identity a tool_call / tool_call_update reports in its structured rawInput:
9
+ * codex `{ server, tool }`, cursor `{ providerIdentifier, toolName }` (both string).
10
+ * Never reads the title. Undefined for any other update or shape.
11
+ */
12
+ export function mcpCallIdentityOf(kind, update) {
13
+ const record = update;
14
+ if (!isRecord(record))
15
+ return undefined;
16
+ if (record.sessionUpdate !== "tool_call" && record.sessionUpdate !== "tool_call_update")
17
+ return undefined;
18
+ const raw = record.rawInput;
19
+ if (!nonEmpty(record.toolCallId) || !isRecord(raw))
20
+ return undefined;
21
+ const fields = FIELDS[kind];
22
+ const server = raw[fields.server];
23
+ const tool = raw[fields.tool];
24
+ if (!nonEmpty(server) || !nonEmpty(tool))
25
+ return undefined;
26
+ return { toolCallId: record.toolCallId, server, tool };
27
+ }
28
+ /** At most this many distinct tool call ids are tracked per turn (the ledger lives for one turn). */
29
+ export const MAX_OWN_TOOL_CALLS = 512;
30
+ /** An id longer than this is never tracked, so never own. */
31
+ export const MAX_OWN_TOOL_CALL_ID_CHARS = 256;
32
+ /** A server or tool name longer than this is stored as a conflict (never own), not kept. */
33
+ export const MAX_OWN_TOOL_FIELD_CHARS = 256;
34
+ export function createOwnToolLedger(input) {
35
+ const tools = new Set(input.toolNames);
36
+ const seen = new Map();
37
+ return {
38
+ observe(update) {
39
+ const identity = mcpCallIdentityOf(input.kind, update);
40
+ if (identity === undefined)
41
+ return;
42
+ const known = seen.get(identity.toolCallId);
43
+ if (known === undefined) {
44
+ // Fail closed at the bounds: an id never stored is never own.
45
+ if (seen.size >= MAX_OWN_TOOL_CALLS || identity.toolCallId.length > MAX_OWN_TOOL_CALL_ID_CHARS)
46
+ return;
47
+ const oversized = identity.server.length > MAX_OWN_TOOL_FIELD_CHARS || identity.tool.length > MAX_OWN_TOOL_FIELD_CHARS;
48
+ seen.set(identity.toolCallId, oversized ? "conflict" : { server: identity.server, tool: identity.tool });
49
+ }
50
+ else if (known !== "conflict" && (known.server !== identity.server || known.tool !== identity.tool)) {
51
+ seen.set(identity.toolCallId, "conflict");
52
+ }
53
+ },
54
+ isOwn(toolCallId) {
55
+ const evidence = seen.get(toolCallId);
56
+ return (evidence !== undefined &&
57
+ evidence !== "conflict" &&
58
+ evidence.server === input.serverName &&
59
+ tools.has(evidence.tool));
60
+ },
61
+ };
62
+ }
@@ -10,13 +10,17 @@
10
10
  * are recorded with decidedBy "profile". Fail closed: a deny or deadline answers
11
11
  * reject_once; a turn abort, process death or ask-port failure answers
12
12
  * `cancelled`. Embedder tools are pre-approved at the adapter (S4-4), so they are
13
- * normally never asked about; if an agent asks anyway, the request is decided
13
+ * normally never asked about; an agent with no pre-approval channel (Codex, Cursor) is
14
+ * answered allow-once for a call its structured report proved is the session's own
15
+ * tool host's (US-004, before the profile decides); if an agent asks anyway, the request is decided
14
16
  * like any other, because its title is display data (S4-4 D4-c).
15
17
  */
16
18
  import type { RequestPermissionRequest, RequestPermissionResponse } from "@agentclientprotocol/sdk";
17
19
  import type { AgentSessionProfile, SandboxPolicy, SessionAskPort } from "@nathapp/nax-agent";
18
20
  import { type AcpPermissionRules } from "#src/client/rule-policy";
19
21
  import { type ToolCallDisplay } from "#src/client/tool-display";
22
+ /** US-004: the request names a call the turn's ledger proved is the session's own tool host's. */
23
+ export declare const OWN_TOOL_REASON = "nax's own tool host call";
20
24
  export declare const NO_ALLOW_ONCE_REASON = "agent offered no allow-once option";
21
25
  export declare const UNSHOWABLE_REASON = "the request could not be shown safely";
22
26
  export declare const ASK_REASON = "the ACP agent asks permission";
@@ -54,6 +58,11 @@ export interface PermissionContext {
54
58
  verify: boolean;
55
59
  onUnwrapped: "rules" | "deny";
56
60
  };
61
+ /**
62
+ * True for a tool call id the turn's own-tool ledger proved is a call to this session's
63
+ * tool host (US-004). Bound to the admitted turn's ledger; absent: nothing is own.
64
+ */
65
+ readonly isOwnToolCall?: (toolCallId: string) => boolean;
57
66
  }
58
67
  export interface OfferedOptions {
59
68
  readonly allowOnce?: string;
@@ -4,6 +4,8 @@ import { SHELL_RULE_REASON, shellCommandOf, shellRuleBlocks, shellRuleVerdict }
4
4
  import { isSandboxWrapped } from "#src/client/shell-sandbox";
5
5
  import { isRecord } from "#src/client/text";
6
6
  import { describeToolCall } from "#src/client/tool-display";
7
+ /** US-004: the request names a call the turn's ledger proved is the session's own tool host's. */
8
+ export const OWN_TOOL_REASON = "nax's own tool host call";
7
9
  export const NO_ALLOW_ONCE_REASON = "agent offered no allow-once option";
8
10
  export const UNSHOWABLE_REASON = "the request could not be shown safely";
9
11
  export const ASK_REASON = "the ACP agent asks permission";
@@ -72,6 +74,11 @@ export async function decidePermission(request, ctx) {
72
74
  const offered = offeredOptions(request);
73
75
  const display = describeToolCall(request.toolCall, ctx.secrets);
74
76
  const auto = (reason, decision) => ctx.asks.recordAutoDecision({ ...eventFields(display), reason }, decision);
77
+ // US-004: a proven call to the session's own tool host is allowed once, in every profile.
78
+ if (offered.allowOnce !== undefined && ctx.isOwnToolCall?.(request.toolCall.toolCallId) === true) {
79
+ auto(OWN_TOOL_REASON, "allow");
80
+ return selected(offered.allowOnce);
81
+ }
75
82
  if ((ctx.profile === "review" || ctx.profile === "full") &&
76
83
  ctx.sandbox !== undefined &&
77
84
  isNetworkRequest(request.toolCall)) {
@@ -3,16 +3,22 @@
3
3
  * adapter (claude-agent-acp 0.85.1) keys an ACP MCP server by its `name` and
4
4
  * passes `_meta.claudeCode.options` through to the Claude Agent SDK, whose
5
5
  * `allowedTools` rules allow a tool without a permission request. One exact rule
6
- * per tool, `mcp__nax__<tool>`, so only the session's own tools are allowed. Tool
6
+ * per tool, `mcp__<serverName>__<tool>` (the session's `nax-<8 hex>` name), 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
8
  * Under none/read the entry's read-only enforcement adds the removed tools and its
9
9
  * session options (#2366).
10
10
  */
11
11
  import type { SandboxPolicy } from "@nathapp/nax-agent";
12
12
  import type { AgentRegistryEntry, ReadOnlyEnforcement } from "#src/client/registry";
13
- /** The ACP MCP server name; the agent sees the tools as `mcp__nax__<tool>`. */
13
+ /**
14
+ * The prefix of the ACP MCP server name. Each session's name is `nax-<8 hex>`
15
+ * (`newToolHostServerName`), so the agent sees its tools as
16
+ * `mcp__nax-<8 hex>__<tool>`; the MCP `initialize` `serverInfo` name stays `nax`.
17
+ */
14
18
  export declare const TOOL_HOST_SERVER_NAME = "nax";
15
- export declare function mcpToolRule(toolName: string): string;
19
+ export declare function mcpToolRule(serverName: string, toolName: string): string;
20
+ /** The tool name behind an agent-visible `mcp__nax-<8 hex>__<tool>`; undefined for any other name. */
21
+ export declare function parseToolHostToolName(name: string): string | undefined;
16
22
  export interface ClaudeMetaExtras {
17
23
  /** nax#2500: the session sandbox (profiles review and full). */
18
24
  readonly sandbox?: SandboxPolicy;
@@ -20,4 +26,4 @@ export interface ClaudeMetaExtras {
20
26
  readonly lockSkipPermissions?: boolean;
21
27
  }
22
28
  /** The session/new, resume and load `_meta` for Claude: tool rules and the read-only enforcement; undefined when empty. */
23
- export declare function claudeSessionMeta(kind: AgentRegistryEntry["preApproval"], toolNames: readonly string[], readOnly: ReadOnlyEnforcement | undefined, extras?: ClaudeMetaExtras): Readonly<Record<string, unknown>> | undefined;
29
+ export declare function claudeSessionMeta(kind: AgentRegistryEntry["preApproval"], serverName: string, toolNames: readonly string[], readOnly: ReadOnlyEnforcement | undefined, extras?: ClaudeMetaExtras): Readonly<Record<string, unknown>> | undefined;
@@ -1,15 +1,24 @@
1
1
  import { claudeSandboxOptions } from "#src/client/claude-sandbox";
2
- /** The ACP MCP server name; the agent sees the tools as `mcp__nax__<tool>`. */
2
+ /**
3
+ * The prefix of the ACP MCP server name. Each session's name is `nax-<8 hex>`
4
+ * (`newToolHostServerName`), so the agent sees its tools as
5
+ * `mcp__nax-<8 hex>__<tool>`; the MCP `initialize` `serverInfo` name stays `nax`.
6
+ */
3
7
  export const TOOL_HOST_SERVER_NAME = "nax";
4
- export function mcpToolRule(toolName) {
5
- return `mcp__${TOOL_HOST_SERVER_NAME}__${toolName}`;
8
+ const AGENT_TOOL_NAME = /^mcp__nax-[0-9a-f]{8}__(.+)$/s;
9
+ export function mcpToolRule(serverName, toolName) {
10
+ return `mcp__${serverName}__${toolName}`;
11
+ }
12
+ /** The tool name behind an agent-visible `mcp__nax-<8 hex>__<tool>`; undefined for any other name. */
13
+ export function parseToolHostToolName(name) {
14
+ return AGENT_TOOL_NAME.exec(name)?.[1];
6
15
  }
7
16
  /** The session/new, resume and load `_meta` for Claude: tool rules and the read-only enforcement; undefined when empty. */
8
- export function claudeSessionMeta(kind, toolNames, readOnly, extras = {}) {
17
+ export function claudeSessionMeta(kind, serverName, toolNames, readOnly, extras = {}) {
9
18
  if (kind !== "claudeCode.allowedTools")
10
19
  return undefined;
11
20
  const options = {
12
- ...(toolNames.length === 0 ? {} : { allowedTools: toolNames.map(mcpToolRule) }),
21
+ ...(toolNames.length === 0 ? {} : { allowedTools: toolNames.map((tool) => mcpToolRule(serverName, tool)) }),
13
22
  ...(readOnly === undefined ? {} : { disallowedTools: [...readOnly.disallowedTools], ...readOnly.sessionOptions }),
14
23
  ...(extras.sandbox === undefined ? {} : { sandbox: claudeSandboxOptions(extras.sandbox) }),
15
24
  ...(extras.lockSkipPermissions === true ? { allowDangerouslySkipPermissions: false } : {}),
@@ -57,6 +57,11 @@ export interface AgentRegistryEntry {
57
57
  readonly defaultMode: ModeSetting | undefined;
58
58
  /** How embedder tools are pre-approved at the adapter (R12); undefined means tools are unsupported. */
59
59
  readonly preApproval: "claudeCode.allowedTools" | undefined;
60
+ /**
61
+ * The structured `rawInput` shape this agent reports MCP tool calls in, so nax can
62
+ * recognise its own tool host's calls (acp-tools-codex-cursor). Undefined: no known shape.
63
+ */
64
+ readonly mcpCallIdentity: "codex" | "cursor" | undefined;
60
65
  /** Variables passed through the env allowlist so the adapter can authenticate itself (§6.2). */
61
66
  readonly authEnv: readonly string[];
62
67
  }
@@ -50,6 +50,7 @@ function entry(name, launch, authEnv, policy) {
50
50
  readOnly: freezeReadOnly(policy?.readOnly),
51
51
  defaultMode: policy?.defaultMode === undefined ? undefined : Object.freeze({ ...policy.defaultMode }),
52
52
  preApproval: policy?.preApproval,
53
+ mcpCallIdentity: policy?.mcpCallIdentity,
53
54
  authEnv: Object.freeze([...authEnv]),
54
55
  });
55
56
  }
@@ -69,6 +70,7 @@ const REGISTRY = new Map([
69
70
  },
70
71
  defaultMode: { configId: "mode", value: "default" },
71
72
  preApproval: "claudeCode.allowedTools",
73
+ mcpCallIdentity: undefined,
72
74
  }),
73
75
  ],
74
76
  [
@@ -87,6 +89,7 @@ const REGISTRY = new Map([
87
89
  },
88
90
  defaultMode: undefined,
89
91
  preApproval: undefined,
92
+ mcpCallIdentity: "codex",
90
93
  }),
91
94
  ],
92
95
  // nax#2372: cursor's own modes do not enforce anything (probed: mode `ask` let a forced
@@ -109,6 +112,7 @@ const REGISTRY = new Map([
109
112
  },
110
113
  defaultMode: undefined,
111
114
  preApproval: undefined,
115
+ mcpCallIdentity: "cursor",
112
116
  }),
113
117
  ],
114
118
  // nax#2372: gemini's `plan` mode is its read-only mode (read tools only, no shell
@@ -126,6 +130,7 @@ const REGISTRY = new Map([
126
130
  },
127
131
  defaultMode: undefined,
128
132
  preApproval: undefined,
133
+ mcpCallIdentity: undefined,
129
134
  }),
130
135
  ],
131
136
  // nax#2372: opencode has no read-only mode (its `plan` agent still runs shell and web
@@ -151,6 +156,7 @@ const REGISTRY = new Map([
151
156
  },
152
157
  defaultMode: undefined,
153
158
  preApproval: undefined,
159
+ mcpCallIdentity: undefined,
154
160
  }),
155
161
  ],
156
162
  // Exact pin: a tilde range does not pin 0.0.x.
@@ -171,6 +177,7 @@ const REGISTRY = new Map([
171
177
  },
172
178
  defaultMode: undefined,
173
179
  preApproval: undefined,
180
+ mcpCallIdentity: undefined,
174
181
  }),
175
182
  ],
176
183
  ]);
@@ -0,0 +1,38 @@
1
+ /**
2
+ * OpenedBackend.configure over ACP (chat-acp-switch-and-replay US-002): the model and
3
+ * the effort are set on the live agent session with session/set_config_option, the
4
+ * same request open sends (open.ts applyModel / applyEffort). The model goes first;
5
+ * the effort option is then looked up in the options the model response returned, so
6
+ * an agent whose effort choices depend on the model is handled. An unoffered model or
7
+ * effort refuses before any request (open skips an unoffered effort instead). Each
8
+ * request is bounded by `timeoutMs` and the session's open signal, as an open step is,
9
+ * and a JSON-RPC error is classified by openRequestError. `onApplied` hears each part
10
+ * the moment its request succeeds, so a later failure never hides what the live agent
11
+ * already holds. Only config options are used: the legacy session/set_model is not.
12
+ */
13
+ import type { SessionConfigOption } from "@agentclientprotocol/sdk";
14
+ import type { SessionConfigureInput } from "@nathapp/nax-agent";
15
+ import type { AcpLink } from "#src/client/connection";
16
+ /** One part of a configure that the agent has accepted. `model` is the value sent (resolved). */
17
+ export type AppliedPart = {
18
+ readonly model: string;
19
+ } | {
20
+ readonly effort: string;
21
+ };
22
+ export interface ConfigureAcpInput {
23
+ readonly link: AcpLink;
24
+ readonly agentSessionId: string;
25
+ readonly agentName: string;
26
+ readonly secrets: readonly string[];
27
+ readonly timeoutMs: number;
28
+ readonly signal: AbortSignal;
29
+ readonly sessionId: string;
30
+ /** The session's current config options. */
31
+ readonly configOptions: readonly SessionConfigOption[];
32
+ readonly change: SessionConfigureInput;
33
+ }
34
+ /**
35
+ * Applies `change`; resolves with the config options after the last request sent (the
36
+ * input's when none was). `onApplied(part, configOptions)` runs right after each request succeeds.
37
+ */
38
+ export declare function configureAcpSession(input: ConfigureAcpInput, onApplied?: (part: AppliedPart, configOptions: readonly SessionConfigOption[]) => void): Promise<readonly SessionConfigOption[]>;
@@ -0,0 +1,65 @@
1
+ import { effortOptionId, MODEL_ID_MAX_CHARS, modelOptionId, resolveModelValue } from "#src/client/capabilities";
2
+ import { agentTextExcerpt, backendUnavailable, capabilityUnsupported, closedDuringOpen, openRequestError, rpcErrorOf, } from "#src/client/errors";
3
+ import { configModelIds } from "#src/client/open";
4
+ import { race } from "#src/client/race";
5
+ import { cleanLabel } from "#src/client/text";
6
+ const STEP = "session/set_config_option";
7
+ /** At most this many offered ids go into a model refusal (agent-supplied text). */
8
+ const MAX_OFFERED_MODELS = 50;
9
+ /**
10
+ * Applies `change`; resolves with the config options after the last request sent (the
11
+ * input's when none was). `onApplied(part, configOptions)` runs right after each request succeeds.
12
+ */
13
+ export async function configureAcpSession(input, onApplied = () => { }) {
14
+ let options = input.configOptions;
15
+ const { model, effort } = input.change;
16
+ if (model !== undefined) {
17
+ const value = resolveModel(input, options, model);
18
+ const configId = modelOptionId(options, value);
19
+ if (configId === undefined)
20
+ throw modelRefusal(input, options, value);
21
+ options = await setOption(input, options, configId, value);
22
+ onApplied({ model: value }, options);
23
+ }
24
+ if (effort !== undefined) {
25
+ const configId = effortOptionId(options, input.agentName, effort);
26
+ if (configId === undefined) {
27
+ throw capabilityUnsupported("effort", `the agent offers no effort option "${effort}"`);
28
+ }
29
+ options = await setOption(input, options, configId, effort);
30
+ onApplied({ effort }, options);
31
+ }
32
+ return options;
33
+ }
34
+ function resolveModel(input, options, model) {
35
+ return resolveModelValue(input.agentName, configModelIds(options), model, input.secrets);
36
+ }
37
+ function modelRefusal(input, options, model) {
38
+ const ids = configModelIds(options)
39
+ .slice(0, MAX_OFFERED_MODELS)
40
+ .map((id) => cleanLabel(id, input.secrets, MODEL_ID_MAX_CHARS) ?? "")
41
+ .filter((id) => id !== "");
42
+ return capabilityUnsupported("model", `the agent offers no model option "${model}"; offered: ${ids.length === 0 ? "(none)" : ids.join(", ")}`, { offered: ids });
43
+ }
44
+ /** One bounded session/set_config_option; the options its answer carries, else the ones it was sent against. */
45
+ async function setOption(input, current, configId, value) {
46
+ const result = await race(input.link.setConfigOption({ sessionId: input.agentSessionId, configId, value }), {
47
+ timeoutMs: input.timeoutMs,
48
+ signal: input.signal,
49
+ });
50
+ switch (result.kind) {
51
+ case "ok":
52
+ return result.value.configOptions ?? current;
53
+ case "aborted":
54
+ throw closedDuringOpen(input.sessionId);
55
+ case "timeout":
56
+ throw backendUnavailable(`${STEP} timed out after ${input.timeoutMs} ms`, { during: STEP });
57
+ case "failed": {
58
+ const rpc = rpcErrorOf(result.error);
59
+ if (rpc !== undefined)
60
+ throw openRequestError(STEP, rpc, input.secrets);
61
+ const message = result.error instanceof Error ? result.error.message : String(result.error);
62
+ throw backendUnavailable(`${STEP} failed: ${agentTextExcerpt(message, input.secrets)}`, { step: STEP });
63
+ }
64
+ }
65
+ }
@@ -15,10 +15,14 @@ export interface ToolHostOptions {
15
15
  * backend before it gets here.
16
16
  */
17
17
  readonly instructions?: string;
18
+ /** The ACP MCP server name; absent draws a fresh `newToolHostServerName()`. */
19
+ readonly serverName?: string;
18
20
  }
19
21
  export interface ToolHost {
20
22
  /** Known before start(), so every redaction set can include it. */
21
23
  readonly token: string;
24
+ /** The session/new entry's name, `nax-<8 hex>`; the agent calls tools as `mcp__<serverName>__<tool>`. */
25
+ readonly serverName: string;
22
26
  /** Listens on 127.0.0.1, an ephemeral port; returns the session/new server entry. */
23
27
  start(): Promise<HttpMcpServer>;
24
28
  /** Resolves once every call in flight has answered. */
@@ -31,6 +35,8 @@ export interface ToolHost {
31
35
  stop(): Promise<void>;
32
36
  }
33
37
  export declare function newToolHostToken(): string;
38
+ /** `nax-` and 8 lowercase hex: routes a loopback tool call to its session, since the request title is agent-controlled. */
39
+ export declare function newToolHostServerName(): string;
34
40
  /**
35
41
  * `opts.instructions` (nax#2517) rides every MCP `initialize` this host answers:
36
42
  * the agent's MCP client reads it there, not from the prompt.
@@ -31,6 +31,10 @@ const SERVER_INFO = { name: TOOL_HOST_SERVER_NAME, version: "1.0.0" };
31
31
  export function newToolHostToken() {
32
32
  return randomBytes(32).toString("base64url");
33
33
  }
34
+ /** `nax-` and 8 lowercase hex: routes a loopback tool call to its session, since the request title is agent-controlled. */
35
+ export function newToolHostServerName() {
36
+ return `nax-${randomBytes(4).toString("hex")}`;
37
+ }
34
38
  const digest = (value) => createHash("sha256").update(value).digest();
35
39
  /** Constant time: both sides are hashed to the same length first. */
36
40
  function tokenMatches(header, token) {
@@ -157,6 +161,7 @@ async function close(http) {
157
161
  * the agent's MCP client reads it there, not from the prompt.
158
162
  */
159
163
  export function createToolHost(calls, token = newToolHostToken(), opts = {}) {
164
+ const serverName = opts.serverName ?? newToolHostServerName();
160
165
  const state = {
161
166
  token,
162
167
  calls,
@@ -170,6 +175,7 @@ export function createToolHost(calls, token = newToolHostToken(), opts = {}) {
170
175
  let stopping;
171
176
  return {
172
177
  token,
178
+ serverName,
173
179
  async start() {
174
180
  if (state.stopped.signal.aborted) {
175
181
  throw new NaxError("The MCP tool host was already stopped", "ACP_TOOL_HOST_STOPPED", { stage: "acp" });
@@ -177,7 +183,7 @@ export function createToolHost(calls, token = newToolHostToken(), opts = {}) {
177
183
  state.port = await listen(http);
178
184
  return {
179
185
  type: "http",
180
- name: TOOL_HOST_SERVER_NAME,
186
+ name: serverName,
181
187
  url: `http://${LOOPBACK}:${state.port}${TOOL_HOST_PATH}`,
182
188
  headers: [{ name: "Authorization", value: `${BEARER}${token}` }],
183
189
  };
@@ -1,4 +1,4 @@
1
- import { type TurnResult } from "@nathapp/nax-agent";
1
+ import { type ImageAttachment, type TurnResult } from "@nathapp/nax-agent";
2
2
  import type { AcpLink } from "#src/client/connection";
3
3
  import type { TurnCollector } from "#src/client/events";
4
4
  import { type LaunchedAgent } from "#src/client/launch";
@@ -13,6 +13,7 @@ export interface TurnState {
13
13
  }
14
14
  export interface TurnInput {
15
15
  readonly text: string;
16
+ readonly images?: readonly ImageAttachment[];
16
17
  readonly signal: AbortSignal;
17
18
  readonly collector: TurnCollector;
18
19
  }
@@ -1,4 +1,4 @@
1
- import { attachTurnSpend, NaxError } from "@nathapp/nax-agent";
1
+ import { attachTurnSpend, NaxError, } from "@nathapp/nax-agent";
2
2
  import { emptyTurnError, promptRequestError, rpcErrorOf, stopReasonError } from "#src/client/errors";
3
3
  import { agentGoneError } from "#src/client/launch";
4
4
  import { race } from "#src/client/race";
@@ -19,7 +19,7 @@ export async function runPromptTurn(state, input) {
19
19
  let carried;
20
20
  for (let continuation = 0;; continuation += 1) {
21
21
  const denialsBefore = input.collector.denials();
22
- const response = await promptOnce(state, input, text, carried);
22
+ const response = await promptOnce(state, input, { text, carried, firstPrompt: continuation === 0 });
23
23
  const usage = sumUsage(carried, response.usage);
24
24
  const continueAfterDenial = response.stopReason === "cancelled" &&
25
25
  !input.signal.aborted &&
@@ -36,10 +36,15 @@ export async function runPromptTurn(state, input) {
36
36
  * already answered and no cost (the cost reading moves to the next turn); an abort
37
37
  * throws with the spend of every prompt this turn answered.
38
38
  */
39
- async function promptOnce(state, input, text, carried) {
39
+ async function promptOnce(state, input, prompt) {
40
+ const { text, carried, firstPrompt } = prompt;
41
+ const images = firstPrompt ? (input.images ?? []) : [];
40
42
  const pending = state.link.prompt({
41
43
  sessionId: state.agentSessionId,
42
- prompt: [{ type: "text", text }],
44
+ prompt: [
45
+ ...images.map((image) => ({ type: "image", mimeType: image.mimeType, data: image.data })),
46
+ { type: "text", text },
47
+ ],
43
48
  });
44
49
  const outcome = await race(pending, { signal: input.signal });
45
50
  switch (outcome.kind) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nathapp/nax-agent-acp",
3
- "version": "0.91.7-canary.8",
3
+ "version": "0.91.7",
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",
@@ -49,12 +49,12 @@
49
49
  "zod": "^4.3.6"
50
50
  },
51
51
  "peerDependencies": {
52
- "@nathapp/nax-agent": "^0.91.7-canary.8"
52
+ "@nathapp/nax-agent": "^0.91.7"
53
53
  },
54
54
  "publishConfig": {
55
55
  "access": "public",
56
56
  "registry": "https://registry.npmjs.org/",
57
57
  "provenance": true,
58
- "tag": "canary"
58
+ "tag": "latest"
59
59
  }
60
60
  }