@nathapp/nax-agent-acp 0.90.0 → 0.90.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -3,6 +3,10 @@
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.90.1] - 2026-10-17
7
+
8
+ - No changes in this package. Released in lockstep with the other nax packages.
9
+
6
10
  ## [0.90.0] - 2026-10-17
7
11
 
8
12
  - No changes in this package. Released in lockstep with the other nax packages.
@@ -73,14 +73,25 @@ export function toolHostFor(ctx, router, secrets, token) {
73
73
  });
74
74
  return _acpBackendDeps.createToolHost(calls, token, toolHostOptions(ctx));
75
75
  }
76
- /** Permission requests and elicitations, decided by profile with the session's redaction set. */
77
- function routerFor(ctx, secrets) {
76
+ /**
77
+ * Permission requests and elicitations, decided by profile with the session's
78
+ * redaction set. nax#2372: the embedder sandbox joins the permission context only
79
+ * for an agent that actually receives it (one with a pre-approval channel); for any
80
+ * other, a policy there would approve an escalation the agent never sandboxed.
81
+ * US-003: the agent's name (which raw field carries a shell command) and the
82
+ * session's rules join it too, so review with no sandbox can adjudicate a command.
83
+ */
84
+ function routerFor(ctx, options) {
85
+ const entry = options.entry;
86
+ const sandbox = entry?.preApproval !== undefined && ctx.sandbox?.kind === "policy" ? ctx.sandbox.policy : undefined;
78
87
  const base = {
79
88
  profile: ctx.profile,
80
89
  asks: ctx.asks,
81
- secrets,
90
+ secrets: options.secrets,
82
91
  cwd: ctx.workdir,
83
- ...(ctx.sandbox?.kind === "policy" ? { sandbox: ctx.sandbox.policy } : {}),
92
+ agentName: options.agentName,
93
+ rules: options.rules,
94
+ ...(sandbox === undefined ? {} : { sandbox }),
84
95
  };
85
96
  return createInboundRouter((request, signal) => decidePermission(request, { ...base, signal }), (request, signal) => answerElicitation(request, { ...base, signal }));
86
97
  }
@@ -90,7 +101,7 @@ async function connect(base, ctx, restore, retiredTokens) {
90
101
  const tokens = token === undefined ? retiredTokens : [...retiredTokens, token];
91
102
  const options = withTokens(base, tokens);
92
103
  const gone = new AbortController();
93
- const router = routerFor(ctx, options.secrets);
104
+ const router = routerFor(ctx, options);
94
105
  const host = toolHostFor(ctx, router, options.secrets, token);
95
106
  const acp = await openAcpSession(options, ctx, router.handlers, _acpBackendDeps.launch, host, restore).catch(async (err) => {
96
107
  await host?.stop();
@@ -31,6 +31,8 @@ export interface UnmetRequirement {
31
31
  readonly reason: string;
32
32
  }
33
33
  export declare function buildCapabilityRecord(init: InitializeResponse, entry: AgentRegistryEntry | undefined): CapabilityRecord;
34
+ /** none, read and review (nax#2500) run with the agent's own write tools removed. */
35
+ export declare const isReadOnlyProfile: (profile: AgentSessionProfile) => profile is "none" | "read" | "review";
34
36
  /** The first requirement this agent cannot meet, or undefined. The model is checked after session/new. */
35
37
  export declare function unmetRequirement(record: CapabilityRecord, req: Requirements): UnmetRequirement | undefined;
36
38
  /** The value ids a select option offers, groups flattened; none for a boolean option. */
@@ -38,6 +40,17 @@ export declare function selectValues(option: SessionConfigOption): readonly stri
38
40
  export declare function offersValue(options: readonly SessionConfigOption[], configId: string, value: string): boolean;
39
41
  /** The id of the agent's model option (category "model") that offers `model`. */
40
42
  export declare function modelOptionId(options: readonly SessionConfigOption[], model: string): string | undefined;
43
+ /** At most this many characters of an agent-supplied model id go into a refusal (agent text). */
44
+ export declare const MODEL_ID_MAX_CHARS = 100;
45
+ /**
46
+ * The model value to set (SPEC-cursor-pi-acp-read-only US-001). Cursor's model ids carry
47
+ * their settings (`gpt-5.5[context=272k,reasoning=medium]`, Auto is `default[]`), so a
48
+ * configured bare name matches no offered id exactly: the one offered id that starts with
49
+ * `requested + "["` is used instead. Two or more are ambiguous and refuse the open, naming
50
+ * each; none, another agent's name and an exact offer all keep `requested`, so the caller's
51
+ * existing "not offered" refusal follows.
52
+ */
53
+ export declare function resolveModelValue(agentName: string, offered: readonly string[], requested: string, secrets: readonly string[]): string;
41
54
  /** Per-agent effort option ids, tried when no option has category "thought_level" (nax's EFFORT_OPTION_BY_AGENT). */
42
55
  export declare const EFFORT_FALLBACK_IDS: Readonly<Record<string, string>>;
43
56
  /** The option that sets `effort`: a "thought_level" option offering it, else the agent's fallback id offering it. */
@@ -46,3 +59,10 @@ export declare function effortOptionId(options: readonly SessionConfigOption[],
46
59
  export declare function readOnlyFor(profile: AgentSessionProfile, entry: AgentRegistryEntry | undefined): ReadOnlyEnforcement | undefined;
47
60
  /** The mode a profile selects (§6.4 layer 1): the read-only entry's for none/read, the default mode otherwise. */
48
61
  export declare function modeFor(profile: AgentSessionProfile, entry: AgentRegistryEntry | undefined): ModeSetting | undefined;
62
+ /**
63
+ * The environment a profile adds to the agent process (nax#2372): opencode's
64
+ * permission policy for none/read/review, `{}` for every other profile and for any
65
+ * agent that enforces read-only another way. The caller spreads this over its own
66
+ * env, so the enforcement value cannot be weakened by a caller-supplied variable.
67
+ */
68
+ export declare function launchEnvFor(profile: AgentSessionProfile, entry: AgentRegistryEntry | undefined): Readonly<Record<string, string>>;
@@ -1,3 +1,5 @@
1
+ import { capabilityUnsupported } from "#src/client/errors";
2
+ import { cleanLabel } from "#src/client/text";
1
3
  const LABEL_MAX_CHARS = 200;
2
4
  function isObject(value) {
3
5
  return typeof value === "object" && value !== null;
@@ -26,7 +28,9 @@ export function buildCapabilityRecord(init, entry) {
26
28
  });
27
29
  }
28
30
  /** none, read and review (nax#2500) run with the agent's own write tools removed. */
29
- const isReadOnlyProfile = (profile) => profile === "none" || profile === "read" || profile === "review";
31
+ export const isReadOnlyProfile = (profile) => profile === "none" || profile === "read" || profile === "review";
32
+ /** No injected environment: the common answer for full, ask and every mode-only agent. */
33
+ const NO_LAUNCH_ENV = Object.freeze({});
30
34
  /** The first requirement this agent cannot meet, or undefined. The model is checked after session/new. */
31
35
  export function unmetRequirement(record, req) {
32
36
  if (isReadOnlyProfile(req.profile) && !record.readOnlyMode) {
@@ -56,6 +60,29 @@ export function offersValue(options, configId, value) {
56
60
  export function modelOptionId(options, model) {
57
61
  return options.find((option) => option.category === "model" && selectValues(option).includes(model))?.id;
58
62
  }
63
+ /** At most this many characters of an agent-supplied model id go into a refusal (agent text). */
64
+ export const MODEL_ID_MAX_CHARS = 100;
65
+ /**
66
+ * The model value to set (SPEC-cursor-pi-acp-read-only US-001). Cursor's model ids carry
67
+ * their settings (`gpt-5.5[context=272k,reasoning=medium]`, Auto is `default[]`), so a
68
+ * configured bare name matches no offered id exactly: the one offered id that starts with
69
+ * `requested + "["` is used instead. Two or more are ambiguous and refuse the open, naming
70
+ * each; none, another agent's name and an exact offer all keep `requested`, so the caller's
71
+ * existing "not offered" refusal follows.
72
+ */
73
+ export function resolveModelValue(agentName, offered, requested, secrets) {
74
+ if (agentName !== "cursor" || offered.includes(requested))
75
+ return requested;
76
+ const matches = offered.filter((id) => id.startsWith(`${requested}[`));
77
+ if (matches.length <= 1) {
78
+ const [only] = matches;
79
+ return only ?? requested;
80
+ }
81
+ const named = matches.map((id) => cleanLabel(id, secrets, MODEL_ID_MAX_CHARS) ?? "").filter((id) => id !== "");
82
+ throw capabilityUnsupported("model", `"${requested}" matches several offered models: ${named.join(", ")}`, {
83
+ offered: named,
84
+ });
85
+ }
59
86
  /** Per-agent effort option ids, tried when no option has category "thought_level" (nax's EFFORT_OPTION_BY_AGENT). */
60
87
  export const EFFORT_FALLBACK_IDS = Object.freeze({
61
88
  claude: "effort",
@@ -80,3 +107,14 @@ export function readOnlyFor(profile, entry) {
80
107
  export function modeFor(profile, entry) {
81
108
  return isReadOnlyProfile(profile) ? entry?.readOnly?.mode : entry?.defaultMode;
82
109
  }
110
+ /**
111
+ * The environment a profile adds to the agent process (nax#2372): opencode's
112
+ * permission policy for none/read/review, `{}` for every other profile and for any
113
+ * agent that enforces read-only another way. The caller spreads this over its own
114
+ * env, so the enforcement value cannot be weakened by a caller-supplied variable.
115
+ */
116
+ export function launchEnvFor(profile, entry) {
117
+ if (!isReadOnlyProfile(profile))
118
+ return NO_LAUNCH_ENV;
119
+ return entry?.readOnly?.launchEnv[profile] ?? NO_LAUNCH_ENV;
120
+ }
@@ -7,8 +7,10 @@
7
7
  * backend's handlers. Requests are not bounded here: callers race them (race.ts),
8
8
  * because the SDK's cancellation is cooperative and still waits for the agent's answer.
9
9
  */
10
- import { type CreateElicitationRequest, type CreateElicitationResponse, type InitializeRequest, type InitializeResponse, type LoadSessionRequest, type LoadSessionResponse, type NewSessionRequest, type NewSessionResponse, type PromptRequest, type PromptResponse, type RequestPermissionRequest, type RequestPermissionResponse, type ResumeSessionRequest, type ResumeSessionResponse, type SessionNotification, type SetSessionConfigOptionRequest, type SetSessionConfigOptionResponse } from "@agentclientprotocol/sdk";
10
+ import { type CreateElicitationRequest, type CreateElicitationResponse, type InitializeRequest, type InitializeResponse, type LoadSessionRequest, type LoadSessionResponse, type NewSessionRequest, type NewSessionResponse, type PromptRequest, type PromptResponse, type RequestPermissionRequest, type RequestPermissionResponse, type ResumeSessionRequest, type ResumeSessionResponse, type SessionNotification, type SetSessionConfigOptionRequest, type SetSessionConfigOptionResponse, type SetSessionModeRequest, type SetSessionModeResponse } from "@agentclientprotocol/sdk";
11
11
  import type { LaunchTarget } from "#src/client/launch";
12
+ /** The legacy model method (Gemini); ACP 1.x's method table does not carry it. */
13
+ export declare const SET_MODEL_METHOD = "session/set_model";
12
14
  export interface InboundHandlers {
13
15
  onUpdate(notification: SessionNotification): void;
14
16
  onPermission(request: RequestPermissionRequest): Promise<RequestPermissionResponse>;
@@ -20,6 +22,13 @@ export interface AcpLink {
20
22
  resumeSession(params: ResumeSessionRequest): Promise<ResumeSessionResponse>;
21
23
  loadSession(params: LoadSessionRequest): Promise<LoadSessionResponse>;
22
24
  setConfigOption(params: SetSessionConfigOptionRequest): Promise<SetSessionConfigOptionResponse>;
25
+ /** The legacy mode method an agent offering only a `modes` block understands (Gemini). */
26
+ setMode(params: SetSessionModeRequest): Promise<SetSessionModeResponse>;
27
+ /** The legacy model method (`SET_MODEL_METHOD`), whose answer carries nothing nax reads. */
28
+ setModel(params: {
29
+ readonly sessionId: string;
30
+ readonly modelId: string;
31
+ }): Promise<unknown>;
23
32
  prompt(params: PromptRequest): Promise<PromptResponse>;
24
33
  cancel(sessionId: string): Promise<void>;
25
34
  closeSession(sessionId: string): Promise<void>;
@@ -8,6 +8,8 @@
8
8
  * because the SDK's cancellation is cooperative and still waits for the agent's answer.
9
9
  */
10
10
  import { client, methods, } from "@agentclientprotocol/sdk";
11
+ /** The legacy model method (Gemini); ACP 1.x's method table does not carry it. */
12
+ export const SET_MODEL_METHOD = "session/set_model";
11
13
  export function openConnection(target, handlers) {
12
14
  const app = client({ name: "nax-agent-acp" })
13
15
  .onNotification(methods.client.session.update, (ctx) => handlers.onUpdate(ctx.params))
@@ -21,6 +23,8 @@ export function openConnection(target, handlers) {
21
23
  resumeSession: (params) => agent.request(methods.agent.session.resume, params),
22
24
  loadSession: (params) => agent.request(methods.agent.session.load, params),
23
25
  setConfigOption: (params) => agent.request(methods.agent.session.setConfigOption, params),
26
+ setMode: (params) => agent.request(methods.agent.session.setMode, params),
27
+ setModel: (params) => agent.request(SET_MODEL_METHOD, params),
24
28
  prompt: (params) => agent.request(methods.agent.session.prompt, params),
25
29
  cancel: (sessionId) => agent.notify(methods.agent.session.cancel, { sessionId }),
26
30
  closeSession: async (sessionId) => {
@@ -33,5 +33,9 @@ export interface TurnCollector {
33
33
  settle(response: PromptResponse): TurnSpend;
34
34
  /** The turn's agent message text, scrubbed (turn_end.output). */
35
35
  output(): string;
36
+ /** A permission request of this turn was answered with a deny (nax#2582). */
37
+ noteDenial(): void;
38
+ /** Denials answered so far in this turn. */
39
+ denials(): number;
36
40
  }
37
41
  export declare function createTurnCollector(emit: TurnEventSink | undefined, options?: CollectorOptions): TurnCollector;
@@ -57,6 +57,7 @@ export function createTurnCollector(emit, options = {}) {
57
57
  let done = false;
58
58
  let spend;
59
59
  let received = false;
60
+ let denials = 0;
60
61
  const receipt = () => {
61
62
  if (received)
62
63
  return;
@@ -121,5 +122,9 @@ export function createTurnCollector(emit, options = {}) {
121
122
  return spend;
122
123
  },
123
124
  output: () => scrubSecrets(parts.join(""), secrets),
125
+ noteDenial() {
126
+ denials += 1;
127
+ },
128
+ denials: () => denials,
124
129
  };
125
130
  }
@@ -7,7 +7,8 @@
7
7
  * elicitation handler with the binding's signal, which aborts when the turn is
8
8
  * cancelled, times out or loses its process, and when the binding is released
9
9
  * (D3-d, D5-k). A permission request first announces its tool call on the turn's
10
- * events (D5-c). Any other request (no turn, another session, a request-scoped
10
+ * events (D5-c); a deny answered while the turn is live is counted on its
11
+ * collector (nax#2582). Any other request (no turn, another session, a request-scoped
11
12
  * elicitation, more than MAX_PENDING_DECISIONS pending at once) is answered locally,
12
13
  * a permission rejected and an elicitation cancelled, and raises no event; each
13
14
  * reason is logged once per session and kind (D3-c). Releasing a binding aborts its
@@ -1,5 +1,5 @@
1
1
  import { getLogger } from "@nathapp/nax-agent";
2
- import { rejectLocally } from "#src/client/permissions";
2
+ import { isDenial, rejectLocally } from "#src/client/permissions";
3
3
  import { isRecord } from "#src/client/text";
4
4
  /** Concurrent permission requests and elicitations one turn may hold; further ones are answered locally. */
5
5
  export const MAX_PENDING_DECISIONS = 16;
@@ -66,7 +66,16 @@ export function createInboundRouter(decide, elicit = cancelElicitation) {
66
66
  }
67
67
  if (!admitted.signal.aborted)
68
68
  admitted.collector.announce(request.toolCall);
69
- return track(admitted, decide(request, admitted.signal).catch(cancelled));
69
+ let decided = true;
70
+ const answer = await track(admitted, decide(request, admitted.signal).catch(() => {
71
+ decided = false;
72
+ return cancelled();
73
+ }));
74
+ // nax#2582: the turn learns of its policy denials, so a cancel they cause can be
75
+ // continued; a decider fault is not a policy denial.
76
+ if (decided && !admitted.signal.aborted && isDenial(request, answer))
77
+ admitted.collector.noteDenial();
78
+ return answer;
70
79
  },
71
80
  onElicitation: async (request) => {
72
81
  const admitted = admit(sessionOf(request));
@@ -15,3 +15,4 @@ export type { AcpAgentSpec, AcpBackendOptions, AcpProcessHooks } from "#src/clie
15
15
  export { 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
+ export type { AcpPermissionRules, AcpRule } from "#src/client/rule-policy";
@@ -13,13 +13,15 @@
13
13
  */
14
14
  import { PROTOCOL_VERSION } from "@agentclientprotocol/sdk";
15
15
  import { getLogger, NaxError, } from "@nathapp/nax-agent";
16
- import { buildCapabilityRecord, effortOptionId, modeFor, modelOptionId, offersValue, readOnlyFor, selectValues, unmetRequirement, } from "#src/client/capabilities";
16
+ import { buildCapabilityRecord, effortOptionId, MODEL_ID_MAX_CHARS, modeFor, modelOptionId, offersValue, readOnlyFor, resolveModelValue, selectValues, unmetRequirement, } from "#src/client/capabilities";
17
17
  import { openConnection } from "#src/client/connection";
18
18
  import { backendUnavailable, capabilityUnsupported, closedDuringOpen, EXCERPT_BYTES, openRequestError, rpcErrorOf, } from "#src/client/errors";
19
19
  import { agentGoneError, pickCandidate } from "#src/client/launch";
20
20
  import { claudeSessionMeta } from "#src/client/pre-approval";
21
21
  import { race } from "#src/client/race";
22
22
  import { isUsableSessionId, restoreSession, } from "#src/client/resume";
23
+ import { policyLaunchEnv } from "#src/client/rule-policy";
24
+ import { sessionOffers } from "#src/client/session-offers";
23
25
  import { cleanLabel } from "#src/client/text";
24
26
  function chooseLaunch(options) {
25
27
  if (options.launch.kind === "explicit")
@@ -37,7 +39,12 @@ export async function openAcpSession(options, ctx, handlers, launch, host, resto
37
39
  if (ctx.openSignal.aborted)
38
40
  throw closedDuringOpen(ctx.sessionId);
39
41
  const candidate = chooseLaunch(options);
40
- const launched = launch({ command: candidate.command, args: candidate.args, cwd: ctx.workdir, env: options.env });
42
+ // nax#2372: the profile's enforcement env (opencode's permission policy, translated from
43
+ // the caller's read-tool deny rules) wins over the caller's, so a model's own
44
+ // OPENCODE_CONFIG_CONTENT cannot weaken a read-only session. A rejection here refuses the
45
+ // open before anything is launched (rule-policy.ts, US-004).
46
+ const env = { ...options.env, ...(await policyLaunchEnv(ctx.profile, options)) };
47
+ const launched = launch({ command: candidate.command, args: candidate.args, cwd: ctx.workdir, env });
41
48
  watchProcess(options.onProcess, launched);
42
49
  const link = openConnection(launched.target, handlers);
43
50
  void launched.exited.then(() => link.close(new NaxError("The ACP agent process exited", "ACP_AGENT_EXITED", { stage: "acp" })));
@@ -111,12 +118,12 @@ async function establish(o) {
111
118
  });
112
119
  if (unmet !== undefined)
113
120
  throw capabilityUnsupported(unmet.capability, unmet.reason);
114
- const sandbox = sandboxFor(o.ctx);
121
+ const sandbox = sandboxFor(o.ctx, o.options.entry);
115
122
  const setup = await sessionSetup(o, sandbox);
116
123
  const session = o.restore === undefined
117
124
  ? await newSession(o, setup)
118
125
  : await restoreSession(o.restore, record, setup, o.link, (label, request) => step(o, label, request));
119
- await applyConfig(o, session.agentSessionId, session.configOptions);
126
+ await applyConfig(o, session.agentSessionId, session.offers);
120
127
  if (o.restore === undefined) {
121
128
  await o.ctx.transcriptStore.save(o.ctx.sessionId, initialDoc(o, record, session.agentSessionId));
122
129
  }
@@ -133,10 +140,17 @@ async function newSession(o, setup) {
133
140
  const created = await step(o, "session/new", o.link.newSession({ cwd: o.ctx.workdir, ...setup }));
134
141
  if (!isUsableSessionId(created.sessionId))
135
142
  throw backendUnavailable("session/new returned no usable session id");
136
- return { agentSessionId: created.sessionId, cwd: o.ctx.workdir, configOptions: created.configOptions ?? [] };
143
+ return { agentSessionId: created.sessionId, cwd: o.ctx.workdir, offers: sessionOffers(created) };
137
144
  }
138
- /** nax#2500: review/full sessions with an embedder sandbox; an unusable one refuses the open. */
139
- function sandboxFor(ctx) {
145
+ /**
146
+ * nax#2500: review/full sessions with an embedder sandbox; an unusable one refuses
147
+ * the open. nax#2372: only an agent that receives the sandbox (one with a
148
+ * pre-approval channel — Claude) gets it; for any other the embedder sandbox is
149
+ * ignored, so an unusable one does not refuse an open it was never meant for.
150
+ */
151
+ function sandboxFor(ctx, entry) {
152
+ if (entry?.preApproval === undefined)
153
+ return undefined;
140
154
  if (ctx.profile !== "review" && ctx.profile !== "full")
141
155
  return undefined;
142
156
  if (ctx.sandbox === undefined)
@@ -163,50 +177,76 @@ async function sessionSetup(o, sandbox) {
163
177
  return { mcpServers: [server], _meta: { ...meta } };
164
178
  }
165
179
  /** §6.3 step 5: the profile's mode, then the model, then the effort (S4b). Only values the agent offered are set. */
166
- async function applyConfig(o, sessionId, offered) {
167
- const afterMode = await applyMode(o, sessionId, offered);
180
+ async function applyConfig(o, sessionId, offers) {
181
+ const afterMode = await applyMode(o, sessionId, offers);
168
182
  const afterModel = await applyModel(o, sessionId, afterMode);
169
183
  await applyEffort(o, sessionId, afterModel);
170
184
  }
171
- async function applyMode(o, sessionId, offered) {
185
+ /**
186
+ * The profile's mode. A config option offering the value is used first (the ACP 1.x
187
+ * way); an agent that offers it only in its legacy `modes` block (Gemini) gets
188
+ * session/set_mode, whose request carries the mode id alone and no config id. A mode
189
+ * neither offers refuses the open.
190
+ */
191
+ async function applyMode(o, sessionId, offers) {
172
192
  const mode = modeFor(o.ctx.profile, o.options.entry);
173
193
  if (mode === undefined)
174
- return offered;
175
- if (!offersValue(offered, mode.configId, mode.value)) {
176
- throw capabilityUnsupported("profile", `the agent does not offer ${mode.configId} "${mode.value}"`);
194
+ return offers;
195
+ if (offersValue(offers.configOptions, mode.configId, mode.value)) {
196
+ const set = await step(o, "session/set_config_option", o.link.setConfigOption({ sessionId, ...mode }));
197
+ return { ...offers, configOptions: set.configOptions ?? offers.configOptions };
198
+ }
199
+ if (offers.modeIds.includes(mode.value)) {
200
+ await step(o, "session/set_mode", o.link.setMode({ sessionId, modeId: mode.value }));
201
+ return offers;
177
202
  }
178
- const set = await step(o, "session/set_config_option", o.link.setConfigOption({ sessionId, ...mode }));
179
- return set.configOptions ?? offered;
203
+ throw capabilityUnsupported("profile", `the agent does not offer ${mode.configId} "${mode.value}"`);
180
204
  }
181
205
  /** At most this many offered ids, each cleaned and capped, go into a model refusal (agent-supplied text). */
182
206
  const MAX_OFFERED_MODELS = 50;
183
- const MAX_MODEL_ID_CHARS = 100;
184
- function offeredModels(offered, secrets) {
185
- return offered
186
- .filter((option) => option.category === "model")
187
- .flatMap((option) => selectValues(option))
207
+ /** The model ids the config options offer, raw: category "model" values in offer order. */
208
+ function configModelIds(offers) {
209
+ return offers.configOptions.filter((option) => option.category === "model").flatMap((option) => selectValues(option));
210
+ }
211
+ /** The model ids a refusal names: the config options' ids first, then the legacy `models` block's, capped. */
212
+ function offeredModels(offers, secrets) {
213
+ return [...configModelIds(offers), ...offers.modelIds]
188
214
  .slice(0, MAX_OFFERED_MODELS)
189
- .map((id) => cleanLabel(id, secrets, MAX_MODEL_ID_CHARS) ?? "")
215
+ .map((id) => cleanLabel(id, secrets, MODEL_ID_MAX_CHARS) ?? "")
190
216
  .filter((id) => id !== "");
191
217
  }
192
- async function applyModel(o, sessionId, offered) {
193
- const model = o.options.model;
194
- if (model === undefined)
195
- return offered;
196
- const configId = modelOptionId(offered, model);
197
- if (configId === undefined) {
198
- const ids = offeredModels(offered, o.options.secrets);
199
- throw capabilityUnsupported("model", `the agent offers no model option "${model}"; offered: ${ids.length === 0 ? "(none)" : ids.join(", ")}`, { offered: ids });
218
+ /**
219
+ * The requested model: through a config option when one offers it (the ACP 1.x way),
220
+ * else through the legacy session/set_model; an agent offering it in neither refuses
221
+ * the open, naming every id it does offer. The requested name is first resolved against
222
+ * the offered ids (resolveModelValue), so a settings-carrying id (Cursor) can be named
223
+ * by its bare form; the config options' ids are used when there are any, else the
224
+ * legacy block's.
225
+ */
226
+ async function applyModel(o, sessionId, offers) {
227
+ const requested = o.options.model;
228
+ if (requested === undefined)
229
+ return offers;
230
+ const fromOptions = configModelIds(offers);
231
+ const model = resolveModelValue(o.options.agentName, fromOptions.length > 0 ? fromOptions : offers.modelIds, requested, o.options.secrets);
232
+ const configId = modelOptionId(offers.configOptions, model);
233
+ if (configId !== undefined) {
234
+ const set = await step(o, "session/set_config_option", o.link.setConfigOption({ sessionId, configId, value: model }));
235
+ return { ...offers, configOptions: set.configOptions ?? offers.configOptions };
236
+ }
237
+ if (offers.modelIds.includes(model)) {
238
+ await step(o, "session/set_model", o.link.setModel({ sessionId, modelId: model }));
239
+ return offers;
200
240
  }
201
- const set = await step(o, "session/set_config_option", o.link.setConfigOption({ sessionId, configId, value: model }));
202
- return set.configOptions ?? offered;
241
+ const ids = offeredModels(offers, o.options.secrets);
242
+ throw capabilityUnsupported("model", `the agent offers no model option "${model}"; offered: ${ids.length === 0 ? "(none)" : ids.join(", ")}`, { offered: ids });
203
243
  }
204
244
  /** S4b spec §6.7: an effort the agent does not offer is skipped with a warning, as acpx does. */
205
- async function applyEffort(o, sessionId, offered) {
245
+ async function applyEffort(o, sessionId, offers) {
206
246
  const effort = o.options.effort;
207
247
  if (effort === undefined)
208
248
  return;
209
- const configId = effortOptionId(offered, o.options.agentName, effort);
249
+ const configId = effortOptionId(offers.configOptions, o.options.agentName, effort);
210
250
  if (configId === undefined) {
211
251
  getLogger().warn("acp", "The agent offers no effort option for this value; effort skipped", {
212
252
  agent: o.options.agentName,
@@ -1,6 +1,9 @@
1
1
  import { type AcpAgentName, type AgentRegistryEntry, type LaunchCandidate } from "#src/client/registry";
2
+ import { type AcpPermissionRules, type AcpRule } from "#src/client/rule-policy";
2
3
  export declare const DEFAULT_CANCEL_GRACE_MS = 10000;
3
4
  export declare const DEFAULT_INITIALIZE_TIMEOUT_MS = 60000;
5
+ /** Where rule-policy files go when the caller names no directory (rule-policy.ts, US-004 writes them). */
6
+ export declare const DEFAULT_STATE_DIR: string;
4
7
  export type AcpAgentSpec = AcpAgentName | {
5
8
  readonly name: string;
6
9
  readonly command: string;
@@ -23,6 +26,14 @@ export interface AcpBackendOptions {
23
26
  readonly env?: Readonly<Record<string, string>>;
24
27
  /** Default false: the allowlist only. true hands the whole process.env to the agent. */
25
28
  readonly inheritEnv?: boolean;
29
+ /** nax's permission rules, translated into the agent's own config where the agent supports it. */
30
+ readonly rules?: {
31
+ readonly allow?: readonly AcpRule[];
32
+ readonly deny?: readonly AcpRule[];
33
+ readonly ask?: readonly AcpRule[];
34
+ };
35
+ /** Where an agent's rule-policy files are written; absolute. Defaults to DEFAULT_STATE_DIR. */
36
+ readonly stateDir?: string;
26
37
  /** Overrides the registry's launch command (a bare name or an absolute path). */
27
38
  readonly command?: string;
28
39
  readonly args?: readonly string[];
@@ -47,6 +58,10 @@ export interface ResolvedAcpOptions {
47
58
  readonly launch: AcpLaunch;
48
59
  readonly model: string | undefined;
49
60
  readonly effort: string | undefined;
61
+ /** The rules translated into the agent's own config; NO_RULES when the caller has none. */
62
+ readonly rules: AcpPermissionRules;
63
+ /** The directory an agent's rule-policy files go in (absolute). */
64
+ readonly stateDir: string;
50
65
  readonly env: Readonly<Record<string, string>>;
51
66
  /** Values redacted from every agent excerpt (D-g). */
52
67
  readonly secrets: readonly string[];
@@ -3,13 +3,17 @@
3
3
  * option fails at acpBackend() and never at open. allowUnsandboxed is checked
4
4
  * first: anything but `true` is AGENT_SESSION_SANDBOX_UNAVAILABLE (R7).
5
5
  */
6
- import { isAbsolute } from "node:path";
6
+ import { tmpdir } from "node:os";
7
+ import { isAbsolute, join } from "node:path";
7
8
  import { AgentSessionError } from "@nathapp/nax-agent";
8
9
  import { z } from "zod";
9
10
  import { buildAgentEnv, secretValues } from "#src/client/env";
10
11
  import { isAcpAgentName, registryEntry, } from "#src/client/registry";
12
+ import { NO_RULES } from "#src/client/rule-policy";
11
13
  export const DEFAULT_CANCEL_GRACE_MS = 10_000;
12
14
  export const DEFAULT_INITIALIZE_TIMEOUT_MS = 60_000;
15
+ /** Where rule-policy files go when the caller names no directory (rule-policy.ts, US-004 writes them). */
16
+ export const DEFAULT_STATE_DIR = join(tmpdir(), "nax-agent-acp");
13
17
  const noNul = (value) => !value.includes("\u0000");
14
18
  const plain = z.string().refine(noNul, "must not contain NUL");
15
19
  const command = z
@@ -25,14 +29,25 @@ const customAgent = z.strictObject({
25
29
  command,
26
30
  args: z.array(plain).optional(),
27
31
  });
32
+ /** One `Tool(pattern, …)` grant: a tool name and at least one pattern. */
33
+ const ruleSchema = z.strictObject({ tool: plain.min(1), patterns: z.array(plain).min(1) });
34
+ const rulesSchema = z.strictObject({
35
+ allow: z.array(ruleSchema).optional(),
36
+ deny: z.array(ruleSchema).optional(),
37
+ ask: z.array(ruleSchema).optional(),
38
+ });
39
+ /** Rule-policy files are written outside the workdir, so the caller must be explicit about where. */
40
+ const stateDirSchema = plain.refine(isAbsolute, "must be an absolute path");
28
41
  const SCHEMA = z
29
42
  .strictObject({
30
- agent: z.union([z.enum(["claude", "codex", "gemini", "opencode", "pi"]), customAgent]),
43
+ agent: z.union([z.enum(["claude", "codex", "cursor", "gemini", "opencode", "pi"]), customAgent]),
31
44
  allowUnsandboxed: z.literal(true),
32
45
  model: z.string().min(1).optional(),
33
46
  effort: z.string().min(1).optional(),
34
47
  env: z.record(z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/), plain).optional(),
35
48
  inheritEnv: z.boolean().optional(),
49
+ rules: rulesSchema.optional(),
50
+ stateDir: stateDirSchema.optional(),
36
51
  command: command.optional(),
37
52
  args: z.array(plain).optional(),
38
53
  cancelGraceMs: z.number().int().positive().max(600_000).optional(),
@@ -49,6 +64,20 @@ const SCHEMA = z
49
64
  function isRecord(value) {
50
65
  return typeof value === "object" && value !== null && !Array.isArray(value);
51
66
  }
67
+ /** A frozen copy of one parsed rule; the caller's arrays never reach the resolved options. */
68
+ function freezeRule(rule) {
69
+ return Object.freeze({ tool: rule.tool, patterns: Object.freeze([...rule.patterns]) });
70
+ }
71
+ /** The caller's rules with every absent list empty, deeply frozen; NO_RULES when there are none. */
72
+ function freezeRules(input) {
73
+ if (input === undefined)
74
+ return NO_RULES;
75
+ return Object.freeze({
76
+ allow: Object.freeze((input.allow ?? []).map(freezeRule)),
77
+ deny: Object.freeze((input.deny ?? []).map(freezeRule)),
78
+ ask: Object.freeze((input.ask ?? []).map(freezeRule)),
79
+ });
80
+ }
52
81
  function launchOf(data, entry) {
53
82
  if (data.command !== undefined)
54
83
  return { kind: "explicit", candidate: { command: data.command, args: data.args ?? [] } };
@@ -79,6 +108,8 @@ function resolved(data, source, onProcess) {
79
108
  launch: launchOf(data, entry),
80
109
  model: data.model,
81
110
  effort: data.effort,
111
+ rules: freezeRules(data.rules),
112
+ stateDir: data.stateDir ?? DEFAULT_STATE_DIR,
82
113
  env: Object.freeze(env),
83
114
  secrets: Object.freeze([...secretValues(env)]),
84
115
  cancelGraceMs: data.cancelGraceMs ?? DEFAULT_CANCEL_GRACE_MS,
@@ -1,7 +1,9 @@
1
1
  /**
2
2
  * session/request_permission by profile (S4 spec §6.4 layer 2). none and read
3
3
  * reject every request; review allows commands (kind execute) only when a
4
- * sandbox policy is present (fail closed) and rejects the rest; under review and full a sandbox network request follows the sandbox
4
+ * sandbox policy is present (fail closed) or an operator Bash rule allows the
5
+ * command itself (shell-rules.ts, SPEC-cursor-pi-acp-read-only US-003), and
6
+ * rejects the rest; under review and full a sandbox network request follows the sandbox
5
7
  * network policy (open: allow, allow-list: deny); full allows it; ask puts it in front of the caller through
6
8
  * asks.requestApproval and answer(). Only options the agent offered are chosen,
7
9
  * and only the *_once kinds: allow_always would outlive the session. Auto-decisions
@@ -13,6 +15,7 @@
13
15
  */
14
16
  import type { RequestPermissionRequest, RequestPermissionResponse } from "@agentclientprotocol/sdk";
15
17
  import type { AgentSessionProfile, SandboxPolicy, SessionAskPort } from "@nathapp/nax-agent";
18
+ import { type AcpPermissionRules } from "#src/client/rule-policy";
16
19
  export declare const NO_ALLOW_ONCE_REASON = "agent offered no allow-once option";
17
20
  export declare const UNSHOWABLE_REASON = "the request could not be shown safely";
18
21
  export declare const ASK_REASON = "the ACP agent asks permission";
@@ -34,12 +37,21 @@ export interface PermissionContext {
34
37
  readonly sandbox?: SandboxPolicy;
35
38
  /** nax#2500: the session cwd, for resolving relative edit targets (R4). */
36
39
  readonly cwd?: string;
40
+ /**
41
+ * The ACP agent's name (US-003): which raw field carries a shell command. Absent
42
+ * reads `rawInput.command`, the field every agent but pi and Cursor uses.
43
+ */
44
+ readonly agentName?: string;
45
+ /** nax's rules for this stage (US-003). Absent: no Bash rule allows anything. */
46
+ readonly rules?: AcpPermissionRules;
37
47
  }
38
48
  export interface OfferedOptions {
39
49
  readonly allowOnce?: string;
40
50
  readonly rejectOnce?: string;
41
51
  }
42
52
  export declare function offeredOptions(request: RequestPermissionRequest): OfferedOptions;
53
+ /** A deny: `cancelled`, or a selected option the agent offered as a reject kind (nax#2582). */
54
+ export declare function isDenial(request: RequestPermissionRequest, response: RequestPermissionResponse): boolean;
43
55
  /** A deny: the agent's reject_once, or `cancelled` when it offered none. */
44
56
  export declare function rejectWith(offered: OfferedOptions): RequestPermissionResponse;
45
57
  /** The answer to a request outside the running turn (spec §6.3): a deny, never an event. */