@nathapp/nax-agent-acp 0.91.6 → 0.91.7-canary.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/README.md +2 -2
  3. package/dist/client/backend.d.ts +3 -2
  4. package/dist/client/backend.js +52 -13
  5. package/dist/client/capabilities.d.ts +2 -0
  6. package/dist/client/capabilities.js +6 -2
  7. package/dist/client/inbound.d.ts +5 -2
  8. package/dist/client/inbound.js +6 -2
  9. package/dist/client/index.d.ts +1 -1
  10. package/dist/client/index.js +1 -1
  11. package/dist/client/launch.js +10 -1
  12. package/dist/client/offered-choices.d.ts +8 -0
  13. package/dist/client/offered-choices.js +52 -0
  14. package/dist/client/open.d.ts +11 -1
  15. package/dist/client/open.js +21 -11
  16. package/dist/client/own-tool-calls.d.ts +37 -0
  17. package/dist/client/own-tool-calls.js +62 -0
  18. package/dist/client/permissions.d.ts +10 -1
  19. package/dist/client/permissions.js +7 -0
  20. package/dist/client/pre-approval.d.ts +10 -4
  21. package/dist/client/pre-approval.js +14 -5
  22. package/dist/client/registry.d.ts +5 -0
  23. package/dist/client/registry.js +7 -0
  24. package/dist/client/session-configure.d.ts +38 -0
  25. package/dist/client/session-configure.js +65 -0
  26. package/dist/client/tool-host.d.ts +6 -0
  27. package/dist/client/tool-host.js +7 -1
  28. package/dist/server/connection.js +1 -1
  29. package/dist/server/errors.js +6 -0
  30. package/dist/server/main.js +1 -2
  31. package/dist/server/nax-config.js +2 -2
  32. package/dist/server/options.js +2 -1
  33. package/dist/server/permissions.d.ts +1 -2
  34. package/dist/server/permissions.js +3 -79
  35. package/dist/server/registry-lifecycle.d.ts +1 -2
  36. package/dist/server/registry-open.d.ts +1 -2
  37. package/dist/server/registry.d.ts +1 -1
  38. package/dist/server/registry.js +7 -1
  39. package/package.json +3 -3
  40. package/dist/server/session-lock-guard.d.ts +0 -6
  41. package/dist/server/session-lock-guard.js +0 -85
  42. package/dist/server/session-lock.d.ts +0 -10
  43. package/dist/server/session-lock.js +0 -164
  44. package/dist/server/storage.d.ts +0 -52
  45. package/dist/server/storage.js +0 -157
package/CHANGELOG.md CHANGED
@@ -3,6 +3,46 @@
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-canary.10] - 2026-10-30
7
+
8
+ - No changes in this package. Released in lockstep with the other nax packages.
9
+
10
+ ## [0.91.7-canary.9] - 2026-10-30
11
+
12
+ - No changes in this package. Released in lockstep with the other nax packages.
13
+
14
+ ## [0.91.7-canary.8] - 2026-10-29
15
+
16
+ - No changes in this package. Released in lockstep with the other nax packages.
17
+
18
+ ## [0.91.7-canary.7] - 2026-10-29
19
+
20
+ - No changes in this package. Released in lockstep with the other nax packages.
21
+
22
+ ## [0.91.7-canary.6] - 2026-10-28
23
+
24
+ - No changes in this package. Released in lockstep with the other nax packages.
25
+
26
+ ## [0.91.7-canary.5] - 2026-10-27
27
+
28
+ - No changes in this package. Released in lockstep with the other nax packages.
29
+
30
+ ## [0.91.7-canary.4] - 2026-10-27
31
+
32
+ - No changes in this package. Released in lockstep with the other nax packages.
33
+
34
+ ## [0.91.7-canary.3] - 2026-10-27
35
+
36
+ - No changes in this package. Released in lockstep with the other nax packages.
37
+
38
+ ## [0.91.7-canary.2] - 2026-10-26
39
+
40
+ - No changes in this package. Released in lockstep with the other nax packages.
41
+
42
+ ## [0.91.7-canary.1] - 2026-10-24
43
+
44
+ - No changes in this package. Released in lockstep with the other nax packages.
45
+
6
46
  ## [0.91.6] - 2026-10-24
7
47
 
8
48
  - 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;
@@ -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,7 @@ function assemble(s) {
181
200
  return infoOf(s);
182
201
  },
183
202
  turnOpts: () => ({ interactionHandler: NO_OP_INTERACTION_HANDLER }),
203
+ configure: (change) => configure(s, change),
184
204
  close: () => {
185
205
  s.closing ??= shutdown(s);
186
206
  return s.closing;
@@ -215,7 +235,8 @@ async function reconnect(s, signal) {
215
235
  // close() aborts openSignal; cancel() and the turn timeout abort the turn signal.
216
236
  const ctx = { ...s.ctx, openSignal: AbortSignal.any([s.ctx.openSignal, signal]) };
217
237
  try {
218
- s.live = await connect(s.base, ctx, restore, old.tokens);
238
+ s.live = await connect(s.base, ctx, restore, old.tokens, s.serverName);
239
+ s.configOptions = s.live.acp.configOptions;
219
240
  return s.live;
220
241
  }
221
242
  catch (err) {
@@ -224,6 +245,24 @@ async function reconnect(s, signal) {
224
245
  throw err;
225
246
  }
226
247
  }
248
+ /** US-002: model and effort set on the live process; each accepted part is recorded for a reconnect. */
249
+ async function configure(s, change) {
250
+ const live = await liveFor(s, s.ctx.openSignal);
251
+ await configureAcpSession({
252
+ link: live.acp.link,
253
+ agentSessionId: live.acp.agentSessionId,
254
+ agentName: s.base.agentName,
255
+ secrets: live.options.secrets,
256
+ timeoutMs: s.base.initializeTimeoutMs,
257
+ signal: s.ctx.openSignal,
258
+ sessionId: s.ctx.sessionId,
259
+ configOptions: s.configOptions,
260
+ change,
261
+ }, (part, configOptions) => {
262
+ s.base = Object.freeze({ ...s.base, ...part });
263
+ s.configOptions = configOptions;
264
+ });
265
+ }
227
266
  async function sendTurn(s, prompt, opts) {
228
267
  const signal = opts.signal ?? s.ctx.turnSignal();
229
268
  const live = await liveFor(s, signal);
@@ -21,6 +21,8 @@ export type CapabilityRecord = {
21
21
  readonly readOnlyMode: boolean;
22
22
  /** The registry knows how to pre-approve embedder tools at the adapter (R12). */
23
23
  readonly preApproval: boolean;
24
+ /** The registry knows the structured shape this agent reports MCP tool calls in. */
25
+ readonly ownToolCalls: boolean;
24
26
  };
25
27
  export interface Requirements {
26
28
  readonly profile: AgentSessionProfile;
@@ -25,6 +25,7 @@ export function buildCapabilityRecord(init, entry) {
25
25
  mcpHttp: caps.mcpCapabilities?.http === true,
26
26
  readOnlyMode: entry?.readOnly !== undefined,
27
27
  preApproval: entry?.preApproval !== undefined,
28
+ ownToolCalls: entry?.mcpCallIdentity !== undefined,
28
29
  });
29
30
  }
30
31
  /** none, read and review (nax#2500) run with the agent's own write tools removed. */
@@ -39,8 +40,11 @@ export function unmetRequirement(record, req) {
39
40
  reason: `profile "${req.profile}" needs read-only enforcement; this agent has none`,
40
41
  };
41
42
  }
42
- if (req.toolCount > 0 && !(record.mcpHttp && record.preApproval)) {
43
- return { capability: "tools", reason: "embedder tools need HTTP MCP support and adapter pre-approval" };
43
+ if (req.toolCount > 0 && !(record.mcpHttp && (record.preApproval || record.ownToolCalls))) {
44
+ return {
45
+ capability: "tools",
46
+ reason: "embedder tools need HTTP MCP support and adapter pre-approval or a known MCP call identity",
47
+ };
44
48
  }
45
49
  if (req.resume && !(record.resume || record.loadSession)) {
46
50
  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";
@@ -41,6 +41,15 @@ export function pickCandidate(candidates, pathVar) {
41
41
  return candidates.find((candidate) => findExecutable(candidate.command, pathVar));
42
42
  }
43
43
  function ignore() { }
44
+ /**
45
+ * `Readable.toWeb` is declared against `node:stream/web`'s `ReadableStream`, while the ACP
46
+ * stream wants the global one. The two are the same class at runtime and differ only in how
47
+ * their `getReader` overloads are written, so no assignment between them typechecks. This is
48
+ * the one place that bridges the two declarations.
49
+ */
50
+ function toWebStream(stream) {
51
+ return Readable.toWeb(stream);
52
+ }
44
53
  function failedLaunch(stderr, error) {
45
54
  const exit = {
46
55
  code: null,
@@ -91,7 +100,7 @@ function startedLaunch(child, stderr, maxMessageBytes) {
91
100
  child.stdout.on("error", ignore);
92
101
  child.stderr.on("error", ignore);
93
102
  child.stderr.on("data", (chunk) => stderr.push(chunk));
94
- const stream = ndJsonStream(Writable.toWeb(child.stdin), Readable.toWeb(child.stdout), maxMessageBytes === undefined ? undefined : { maxMessageBytes });
103
+ const stream = ndJsonStream(Writable.toWeb(child.stdin), toWebStream(child.stdout), maxMessageBytes === undefined ? undefined : { maxMessageBytes });
95
104
  const pid = child.pid;
96
105
  let gone = false;
97
106
  void exited.then(() => {
@@ -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;