@nathapp/nax-agent-acp 0.90.0 → 0.90.2

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 (47) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/README.md +3 -1
  3. package/dist/client/backend.js +30 -6
  4. package/dist/client/capabilities.d.ts +35 -2
  5. package/dist/client/capabilities.js +61 -4
  6. package/dist/client/connection.d.ts +10 -1
  7. package/dist/client/connection.js +4 -0
  8. package/dist/client/cursor-sandbox.d.ts +5 -0
  9. package/dist/client/cursor-sandbox.js +60 -0
  10. package/dist/client/errors.d.ts +6 -0
  11. package/dist/client/errors.js +9 -0
  12. package/dist/client/events.d.ts +13 -0
  13. package/dist/client/events.js +34 -3
  14. package/dist/client/inbound.d.ts +2 -1
  15. package/dist/client/inbound.js +11 -2
  16. package/dist/client/index.d.ts +1 -0
  17. package/dist/client/open.d.ts +2 -0
  18. package/dist/client/open.js +82 -34
  19. package/dist/client/opencode-sandbox.d.ts +15 -0
  20. package/dist/client/opencode-sandbox.js +94 -0
  21. package/dist/client/options.d.ts +38 -0
  22. package/dist/client/options.js +54 -2
  23. package/dist/client/permissions.d.ts +25 -1
  24. package/dist/client/permissions.js +79 -12
  25. package/dist/client/pi-sandbox.d.ts +2 -0
  26. package/dist/client/pi-sandbox.js +22 -0
  27. package/dist/client/policy-files.d.ts +21 -0
  28. package/dist/client/policy-files.js +73 -0
  29. package/dist/client/registry.d.ts +33 -9
  30. package/dist/client/registry.js +130 -9
  31. package/dist/client/resume.d.ts +5 -3
  32. package/dist/client/resume.js +3 -2
  33. package/dist/client/rule-policy.d.ts +55 -0
  34. package/dist/client/rule-policy.js +181 -0
  35. package/dist/client/session-offers.d.ts +18 -0
  36. package/dist/client/session-offers.js +32 -0
  37. package/dist/client/shell-rules.d.ts +22 -0
  38. package/dist/client/shell-rules.js +134 -0
  39. package/dist/client/shell-sandbox.d.ts +38 -0
  40. package/dist/client/shell-sandbox.js +107 -0
  41. package/dist/client/startup-banner.d.ts +1 -0
  42. package/dist/client/startup-banner.js +16 -0
  43. package/dist/client/turn.d.ts +3 -0
  44. package/dist/client/turn.js +40 -9
  45. package/dist/client/usage.d.ts +3 -1
  46. package/dist/client/usage.js +23 -0
  47. package/package.json +2 -2
@@ -13,13 +13,16 @@
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";
25
+ import { startupBannerOf } from "#src/client/startup-banner";
23
26
  import { cleanLabel } from "#src/client/text";
24
27
  function chooseLaunch(options) {
25
28
  if (options.launch.kind === "explicit")
@@ -37,7 +40,12 @@ export async function openAcpSession(options, ctx, handlers, launch, host, resto
37
40
  if (ctx.openSignal.aborted)
38
41
  throw closedDuringOpen(ctx.sessionId);
39
42
  const candidate = chooseLaunch(options);
40
- const launched = launch({ command: candidate.command, args: candidate.args, cwd: ctx.workdir, env: options.env });
43
+ // nax#2372: the profile's enforcement env (opencode's permission policy, translated from
44
+ // the caller's read-tool deny rules) wins over the caller's, so a model's own
45
+ // OPENCODE_CONFIG_CONTENT cannot weaken a read-only session. A rejection here refuses the
46
+ // open before anything is launched (rule-policy.ts, US-004).
47
+ const env = { ...options.env, ...(await policyLaunchEnv(ctx.profile, options)) };
48
+ const launched = launch({ command: candidate.command, args: candidate.args, cwd: ctx.workdir, env });
41
49
  watchProcess(options.onProcess, launched);
42
50
  const link = openConnection(launched.target, handlers);
43
51
  void launched.exited.then(() => link.close(new NaxError("The ACP agent process exited", "ACP_AGENT_EXITED", { stage: "acp" })));
@@ -111,12 +119,12 @@ async function establish(o) {
111
119
  });
112
120
  if (unmet !== undefined)
113
121
  throw capabilityUnsupported(unmet.capability, unmet.reason);
114
- const sandbox = sandboxFor(o.ctx);
122
+ const sandbox = sandboxFor(o.ctx, o.options.entry);
115
123
  const setup = await sessionSetup(o, sandbox);
116
124
  const session = o.restore === undefined
117
125
  ? await newSession(o, setup)
118
126
  : await restoreSession(o.restore, record, setup, o.link, (label, request) => step(o, label, request));
119
- await applyConfig(o, session.agentSessionId, session.configOptions);
127
+ await applyConfig(o, session.agentSessionId, session.offers);
120
128
  if (o.restore === undefined) {
121
129
  await o.ctx.transcriptStore.save(o.ctx.sessionId, initialDoc(o, record, session.agentSessionId));
122
130
  }
@@ -127,16 +135,30 @@ async function establish(o) {
127
135
  agentSessionId: session.agentSessionId,
128
136
  cwd: session.cwd,
129
137
  ...(session.restoredWith === undefined ? {} : { restoredWith: session.restoredWith }),
138
+ ...(session.startupBanner === undefined ? {} : { startupBanner: session.startupBanner }),
130
139
  };
131
140
  }
132
141
  async function newSession(o, setup) {
133
142
  const created = await step(o, "session/new", o.link.newSession({ cwd: o.ctx.workdir, ...setup }));
134
143
  if (!isUsableSessionId(created.sessionId))
135
144
  throw backendUnavailable("session/new returned no usable session id");
136
- return { agentSessionId: created.sessionId, cwd: o.ctx.workdir, configOptions: created.configOptions ?? [] };
145
+ const startupBanner = startupBannerOf(created);
146
+ return {
147
+ agentSessionId: created.sessionId,
148
+ cwd: o.ctx.workdir,
149
+ offers: sessionOffers(created),
150
+ ...(startupBanner === undefined ? {} : { startupBanner }),
151
+ };
137
152
  }
138
- /** nax#2500: review/full sessions with an embedder sandbox; an unusable one refuses the open. */
139
- function sandboxFor(ctx) {
153
+ /**
154
+ * nax#2500: review/full sessions with an embedder sandbox; an unusable one refuses
155
+ * the open. nax#2372: only an agent that receives the sandbox (one with a
156
+ * pre-approval channel — Claude) gets it; for any other the embedder sandbox is
157
+ * ignored, so an unusable one does not refuse an open it was never meant for.
158
+ */
159
+ function sandboxFor(ctx, entry) {
160
+ if (entry?.preApproval === undefined)
161
+ return undefined;
140
162
  if (ctx.profile !== "review" && ctx.profile !== "full")
141
163
  return undefined;
142
164
  if (ctx.sandbox === undefined)
@@ -163,50 +185,76 @@ async function sessionSetup(o, sandbox) {
163
185
  return { mcpServers: [server], _meta: { ...meta } };
164
186
  }
165
187
  /** §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);
188
+ async function applyConfig(o, sessionId, offers) {
189
+ const afterMode = await applyMode(o, sessionId, offers);
168
190
  const afterModel = await applyModel(o, sessionId, afterMode);
169
191
  await applyEffort(o, sessionId, afterModel);
170
192
  }
171
- async function applyMode(o, sessionId, offered) {
172
- const mode = modeFor(o.ctx.profile, o.options.entry);
193
+ /**
194
+ * The profile's mode. A config option offering the value is used first (the ACP 1.x
195
+ * way); an agent that offers it only in its legacy `modes` block (Gemini) gets
196
+ * session/set_mode, whose request carries the mode id alone and no config id. A mode
197
+ * neither offers refuses the open.
198
+ */
199
+ async function applyMode(o, sessionId, offers) {
200
+ const mode = modeFor(o.ctx.profile, o.options.entry, o.options.rules, o.options.shellSandboxPlan !== undefined);
173
201
  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}"`);
202
+ return offers;
203
+ if (offersValue(offers.configOptions, mode.configId, mode.value)) {
204
+ const set = await step(o, "session/set_config_option", o.link.setConfigOption({ sessionId, ...mode }));
205
+ return { ...offers, configOptions: set.configOptions ?? offers.configOptions };
177
206
  }
178
- const set = await step(o, "session/set_config_option", o.link.setConfigOption({ sessionId, ...mode }));
179
- return set.configOptions ?? offered;
207
+ if (offers.modeIds.includes(mode.value)) {
208
+ await step(o, "session/set_mode", o.link.setMode({ sessionId, modeId: mode.value }));
209
+ return offers;
210
+ }
211
+ throw capabilityUnsupported("profile", `the agent does not offer ${mode.configId} "${mode.value}"`);
180
212
  }
181
213
  /** At most this many offered ids, each cleaned and capped, go into a model refusal (agent-supplied text). */
182
214
  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))
215
+ /** 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));
218
+ }
219
+ /** The model ids a refusal names: the config options' ids first, then the legacy `models` block's, capped. */
220
+ function offeredModels(offers, secrets) {
221
+ return [...configModelIds(offers), ...offers.modelIds]
188
222
  .slice(0, MAX_OFFERED_MODELS)
189
- .map((id) => cleanLabel(id, secrets, MAX_MODEL_ID_CHARS) ?? "")
223
+ .map((id) => cleanLabel(id, secrets, MODEL_ID_MAX_CHARS) ?? "")
190
224
  .filter((id) => id !== "");
191
225
  }
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 });
226
+ /**
227
+ * The requested model: through a config option when one offers it (the ACP 1.x way),
228
+ * else through the legacy session/set_model; an agent offering it in neither refuses
229
+ * the open, naming every id it does offer. The requested name is first resolved against
230
+ * the offered ids (resolveModelValue), so a settings-carrying id (Cursor) can be named
231
+ * by its bare form; the config options' ids are used when there are any, else the
232
+ * legacy block's.
233
+ */
234
+ async function applyModel(o, sessionId, offers) {
235
+ const requested = o.options.model;
236
+ if (requested === undefined)
237
+ return offers;
238
+ const fromOptions = configModelIds(offers);
239
+ const model = resolveModelValue(o.options.agentName, fromOptions.length > 0 ? fromOptions : offers.modelIds, requested, o.options.secrets);
240
+ const configId = modelOptionId(offers.configOptions, model);
241
+ if (configId !== undefined) {
242
+ const set = await step(o, "session/set_config_option", o.link.setConfigOption({ sessionId, configId, value: model }));
243
+ return { ...offers, configOptions: set.configOptions ?? offers.configOptions };
244
+ }
245
+ if (offers.modelIds.includes(model)) {
246
+ await step(o, "session/set_model", o.link.setModel({ sessionId, modelId: model }));
247
+ return offers;
200
248
  }
201
- const set = await step(o, "session/set_config_option", o.link.setConfigOption({ sessionId, configId, value: model }));
202
- return set.configOptions ?? offered;
249
+ const ids = offeredModels(offers, o.options.secrets);
250
+ throw capabilityUnsupported("model", `the agent offers no model option "${model}"; offered: ${ids.length === 0 ? "(none)" : ids.join(", ")}`, { offered: ids });
203
251
  }
204
252
  /** 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) {
253
+ async function applyEffort(o, sessionId, offers) {
206
254
  const effort = o.options.effort;
207
255
  if (effort === undefined)
208
256
  return;
209
- const configId = effortOptionId(offered, o.options.agentName, effort);
257
+ const configId = effortOptionId(offers.configOptions, o.options.agentName, effort);
210
258
  if (configId === undefined) {
211
259
  getLogger().warn("acp", "The agent offers no effort option for this value; effort skipped", {
212
260
  agent: o.options.agentName,
@@ -0,0 +1,15 @@
1
+ /** opencode's isolated V2 shell plugin and restored AGENTS.md instructions. */
2
+ import { readFile, stat } from "node:fs/promises";
3
+ import { type ShellSandboxPlan } from "#src/client/shell-sandbox";
4
+ export declare const _opencodeSandboxDeps: {
5
+ readFile: typeof readFile;
6
+ stat: typeof stat;
7
+ };
8
+ /** The hook wraps only shell commands, before opencode asks permission for the original. */
9
+ export declare function opencodeSandboxPluginSource(prefix: string): string;
10
+ /**
11
+ * All writes use the shared fail-closed writer, on every launch. Operator config
12
+ * may itself name V2 plugins that undo this hook; isolating the whole process is
13
+ * outside this shell-only sandbox. Only AGENTS.md (not CLAUDE.md) is restored.
14
+ */
15
+ export declare function opencodeSandboxEnv(plan: ShellSandboxPlan, permissionConfig: string, callerEnv: Readonly<Record<string, string>>): Promise<Readonly<Record<string, string>>>;
@@ -0,0 +1,94 @@
1
+ /** opencode's isolated V2 shell plugin and restored AGENTS.md instructions. */
2
+ import { readFile, stat } from "node:fs/promises";
3
+ import { dirname, join } from "node:path";
4
+ import { backendUnavailable } from "#src/client/errors";
5
+ import { digest, writeStateFile } from "#src/client/policy-files";
6
+ import { sandboxWrapSnippet } from "#src/client/shell-sandbox";
7
+ export const _opencodeSandboxDeps = { readFile, stat };
8
+ /** The hook wraps only shell commands, before opencode asks permission for the original. */
9
+ export function opencodeSandboxPluginSource(prefix) {
10
+ return `${sandboxWrapSnippet(prefix)}
11
+ export default {
12
+ id: "nax-shell-sandbox",
13
+ async setup(ctx) {
14
+ await ctx.tool.hook("execute.before", (event) => {
15
+ const tool = typeof event.tool === "string" ? event.tool.toLowerCase() : "";
16
+ if ((tool === "shell" || tool === "bash") && typeof event.input?.command === "string") {
17
+ event.input = { ...event.input, command: naxSandboxWrap(event.input.command) };
18
+ }
19
+ });
20
+ }
21
+ };
22
+ `;
23
+ }
24
+ function missing(error) {
25
+ return error instanceof Error && "code" in error && error.code === "ENOENT";
26
+ }
27
+ async function optionalText(path) {
28
+ try {
29
+ return await _opencodeSandboxDeps.readFile(path, "utf8");
30
+ }
31
+ catch (cause) {
32
+ if (missing(cause))
33
+ return undefined;
34
+ throw backendUnavailable(`the opencode instruction file "${path}" could not be read`, { path, cause });
35
+ }
36
+ }
37
+ async function exists(path) {
38
+ try {
39
+ await _opencodeSandboxDeps.stat(path);
40
+ return true;
41
+ }
42
+ catch (cause) {
43
+ if (missing(cause))
44
+ return false;
45
+ throw backendUnavailable(`the opencode config path "${path}" could not be inspected`, { path, cause });
46
+ }
47
+ }
48
+ async function instructions(userDir, workdir) {
49
+ const texts = [];
50
+ const global = await optionalText(join(userDir, "AGENTS.md"));
51
+ if (global !== undefined)
52
+ texts.push(global);
53
+ for (let dir = workdir;; dir = dirname(dir)) {
54
+ const text = await optionalText(join(dir, "AGENTS.md"));
55
+ if (text !== undefined)
56
+ texts.push(text);
57
+ if (await exists(join(dir, ".git")))
58
+ break;
59
+ if (dirname(dir) === dir)
60
+ break;
61
+ }
62
+ return texts.join("\n\n");
63
+ }
64
+ async function operatorConfig(userDir) {
65
+ for (const name of ["opencode.json", "opencode.jsonc"]) {
66
+ const path = join(userDir, name);
67
+ if (await exists(path))
68
+ return path;
69
+ }
70
+ return undefined;
71
+ }
72
+ /**
73
+ * All writes use the shared fail-closed writer, on every launch. Operator config
74
+ * may itself name V2 plugins that undo this hook; isolating the whole process is
75
+ * outside this shell-only sandbox. Only AGENTS.md (not CLAUDE.md) is restored.
76
+ */
77
+ export async function opencodeSandboxEnv(plan, permissionConfig, callerEnv) {
78
+ const userDir = callerEnv.OPENCODE_CONFIG_DIR ?? join(callerEnv.XDG_CONFIG_HOME ?? join(plan.home, ".config"), "opencode");
79
+ const text = await instructions(userDir, plan.workdir);
80
+ const source = opencodeSandboxPluginSource(plan.prefix);
81
+ // Planning owns the invariant <stateDir>/sandbox/policy-<digest>.json.
82
+ const stateDir = dirname(dirname(plan.policyFile));
83
+ const relativeDir = join("opencode", digest(source + "\n\n" + text));
84
+ await writeStateFile(stateDir, join(relativeDir, "plugins", "nax-shell-sandbox.js"), source, 0o600);
85
+ if (text.length > 0)
86
+ await writeStateFile(stateDir, join(relativeDir, "AGENTS.md"), text, 0o600);
87
+ const config = callerEnv.OPENCODE_CONFIG === undefined ? await operatorConfig(userDir) : undefined;
88
+ return Object.freeze({
89
+ OPENCODE_CONFIG_CONTENT: permissionConfig,
90
+ OPENCODE_DISABLE_PROJECT_CONFIG: "1",
91
+ OPENCODE_CONFIG_DIR: join(stateDir, relativeDir),
92
+ ...(config === undefined ? {} : { OPENCODE_CONFIG: config }),
93
+ });
94
+ }
@@ -1,6 +1,10 @@
1
1
  import { type AcpAgentName, type AgentRegistryEntry, type LaunchCandidate } from "#src/client/registry";
2
+ import { type AcpPermissionRules, type AcpRule } from "#src/client/rule-policy";
3
+ import type { ShellSandboxPlan } from "#src/client/shell-sandbox";
2
4
  export declare const DEFAULT_CANCEL_GRACE_MS = 10000;
3
5
  export declare const DEFAULT_INITIALIZE_TIMEOUT_MS = 60000;
6
+ /** Where rule-policy files go when the caller names no directory (rule-policy.ts, US-004 writes them). */
7
+ export declare const DEFAULT_STATE_DIR: string;
4
8
  export type AcpAgentSpec = AcpAgentName | {
5
9
  readonly name: string;
6
10
  readonly command: string;
@@ -23,6 +27,28 @@ export interface AcpBackendOptions {
23
27
  readonly env?: Readonly<Record<string, string>>;
24
28
  /** Default false: the allowlist only. true hands the whole process.env to the agent. */
25
29
  readonly inheritEnv?: boolean;
30
+ /** nax's permission rules, translated into the agent's own config where the agent supports it. */
31
+ readonly rules?: {
32
+ readonly allow?: readonly AcpRule[];
33
+ readonly deny?: readonly AcpRule[];
34
+ readonly ask?: readonly AcpRule[];
35
+ };
36
+ /** Where an agent's rule-policy files are written; absolute. Defaults to DEFAULT_STATE_DIR. */
37
+ readonly stateDir?: string;
38
+ /** Optional command-only sandbox; the agent process still runs on the host. */
39
+ readonly shellSandbox?: {
40
+ readonly runtime: string;
41
+ readonly runner: readonly string[];
42
+ readonly pi?: {
43
+ readonly extensions?: "user" | "none";
44
+ };
45
+ readonly opencode?: {
46
+ readonly projectConfig?: "disable" | "keep";
47
+ };
48
+ readonly cursor?: {
49
+ readonly onUnwrapped?: "rules" | "deny";
50
+ };
51
+ };
26
52
  /** Overrides the registry's launch command (a bare name or an absolute path). */
27
53
  readonly command?: string;
28
54
  readonly args?: readonly string[];
@@ -47,6 +73,18 @@ export interface ResolvedAcpOptions {
47
73
  readonly launch: AcpLaunch;
48
74
  readonly model: string | undefined;
49
75
  readonly effort: string | undefined;
76
+ /** The rules translated into the agent's own config; NO_RULES when the caller has none. */
77
+ readonly rules: AcpPermissionRules;
78
+ /** The directory an agent's rule-policy files go in (absolute). */
79
+ readonly stateDir: string;
80
+ readonly shellSandbox: {
81
+ readonly runtime: string;
82
+ readonly runner: readonly string[];
83
+ readonly piExtensions: "user" | "none";
84
+ readonly opencodeProjectConfig: "disable" | "keep";
85
+ readonly cursorOnUnwrapped: "rules" | "deny";
86
+ } | undefined;
87
+ readonly shellSandboxPlan?: ShellSandboxPlan;
50
88
  readonly env: Readonly<Record<string, string>>;
51
89
  /** Values redacted from every agent excerpt (D-g). */
52
90
  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,34 @@ 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(),
51
+ shellSandbox: z
52
+ .strictObject({
53
+ runtime: stateDirSchema,
54
+ runner: z.array(plain).min(1),
55
+ pi: z.strictObject({ extensions: z.enum(["user", "none"]).optional() }).optional(),
56
+ opencode: z.strictObject({ projectConfig: z.enum(["disable", "keep"]).optional() }).optional(),
57
+ cursor: z.strictObject({ onUnwrapped: z.enum(["rules", "deny"]).optional() }).optional(),
58
+ })
59
+ .optional(),
36
60
  command: command.optional(),
37
61
  args: z.array(plain).optional(),
38
62
  cancelGraceMs: z.number().int().positive().max(600_000).optional(),
@@ -49,6 +73,31 @@ const SCHEMA = z
49
73
  function isRecord(value) {
50
74
  return typeof value === "object" && value !== null && !Array.isArray(value);
51
75
  }
76
+ /** A frozen copy of one parsed rule; the caller's arrays never reach the resolved options. */
77
+ function freezeRule(rule) {
78
+ return Object.freeze({ tool: rule.tool, patterns: Object.freeze([...rule.patterns]) });
79
+ }
80
+ /** The caller's rules with every absent list empty, deeply frozen; NO_RULES when there are none. */
81
+ function freezeRules(input) {
82
+ if (input === undefined)
83
+ return NO_RULES;
84
+ return Object.freeze({
85
+ allow: Object.freeze((input.allow ?? []).map(freezeRule)),
86
+ deny: Object.freeze((input.deny ?? []).map(freezeRule)),
87
+ ask: Object.freeze((input.ask ?? []).map(freezeRule)),
88
+ });
89
+ }
90
+ function freezeShellSandbox(input) {
91
+ if (input === undefined)
92
+ return undefined;
93
+ return Object.freeze({
94
+ runtime: input.runtime,
95
+ runner: Object.freeze([...input.runner]),
96
+ piExtensions: input.pi?.extensions ?? "user",
97
+ opencodeProjectConfig: input.opencode?.projectConfig ?? "disable",
98
+ cursorOnUnwrapped: input.cursor?.onUnwrapped ?? "rules",
99
+ });
100
+ }
52
101
  function launchOf(data, entry) {
53
102
  if (data.command !== undefined)
54
103
  return { kind: "explicit", candidate: { command: data.command, args: data.args ?? [] } };
@@ -79,6 +128,9 @@ function resolved(data, source, onProcess) {
79
128
  launch: launchOf(data, entry),
80
129
  model: data.model,
81
130
  effort: data.effort,
131
+ rules: freezeRules(data.rules),
132
+ stateDir: data.stateDir ?? DEFAULT_STATE_DIR,
133
+ shellSandbox: freezeShellSandbox(data.shellSandbox),
82
134
  env: Object.freeze(env),
83
135
  secrets: Object.freeze([...secretValues(env)]),
84
136
  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,8 @@
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";
19
+ import { type ToolCallDisplay } from "#src/client/tool-display";
16
20
  export declare const NO_ALLOW_ONCE_REASON = "agent offered no allow-once option";
17
21
  export declare const UNSHOWABLE_REASON = "the request could not be shown safely";
18
22
  export declare const ASK_REASON = "the ACP agent asks permission";
@@ -20,6 +24,8 @@ export declare const FULL_REASON = "profile \"full\" allows every permission req
20
24
  export declare const UNKNOWN_PROFILE_REASON = "unknown profile";
21
25
  export declare const REVIEW_EXECUTE_REASON = "profile \"review\" allows commands";
22
26
  export declare const REVIEW_NO_SANDBOX_REASON = "profile \"review\" runs commands only inside the sandbox";
27
+ export declare const REVIEW_UNWRAPPED_REASON = "the command did not arrive in nax's sandbox wrapper";
28
+ export declare const SHELL_RULE_BLOCKED_REASON = "a \"Bash\" deny or ask rule matches the command";
23
29
  export declare const NETWORK_OPEN_REASON = "the sandbox network is open";
24
30
  export declare const NETWORK_LISTED_REASON = "the sandbox network is an allow-list";
25
31
  export declare function isNetworkRequest(toolCall: unknown): boolean;
@@ -34,14 +40,32 @@ export interface PermissionContext {
34
40
  readonly sandbox?: SandboxPolicy;
35
41
  /** nax#2500: the session cwd, for resolving relative edit targets (R4). */
36
42
  readonly cwd?: string;
43
+ /**
44
+ * The ACP agent's name (US-003): which raw field carries a shell command. Absent
45
+ * reads `rawInput.command`, the field every agent but pi and Cursor uses.
46
+ */
47
+ readonly agentName?: string;
48
+ /** nax's rules for this stage (US-003). Absent: no Bash rule allows anything. */
49
+ readonly rules?: AcpPermissionRules;
50
+ readonly shellSandbox?: {
51
+ prefix: string;
52
+ verify: boolean;
53
+ onUnwrapped: "rules" | "deny";
54
+ };
37
55
  }
38
56
  export interface OfferedOptions {
39
57
  readonly allowOnce?: string;
40
58
  readonly rejectOnce?: string;
41
59
  }
42
60
  export declare function offeredOptions(request: RequestPermissionRequest): OfferedOptions;
61
+ /** A deny: `cancelled`, or a selected option the agent offered as a reject kind (nax#2582). */
62
+ export declare function isDenial(request: RequestPermissionRequest, response: RequestPermissionResponse): boolean;
43
63
  /** A deny: the agent's reject_once, or `cancelled` when it offered none. */
44
64
  export declare function rejectWith(offered: OfferedOptions): RequestPermissionResponse;
45
65
  /** The answer to a request outside the running turn (spec §6.3): a deny, never an event. */
46
66
  export declare function rejectLocally(request: RequestPermissionRequest): RequestPermissionResponse;
67
+ type AutoDecide = (reason: string, decision: "allow" | "deny") => void;
47
68
  export declare function decidePermission(request: RequestPermissionRequest, ctx: PermissionContext): Promise<RequestPermissionResponse>;
69
+ /** Shell sandbox approvals precede the legacy sandbox/rule-only paths. */
70
+ export declare function decideSandboxedShell(request: RequestPermissionRequest, display: ToolCallDisplay, offered: OfferedOptions, auto: AutoDecide, ctx: PermissionContext): RequestPermissionResponse;
71
+ export {};
@@ -1,4 +1,7 @@
1
1
  import { editTargets, firstOutsidePolicy, OUTSIDE_WRITE_ROOTS_REASON, WRITE_KINDS } from "#src/client/edit-targets";
2
+ import { NO_RULES } from "#src/client/rule-policy";
3
+ import { SHELL_RULE_REASON, shellCommandOf, shellRuleBlocks, shellRuleVerdict } from "#src/client/shell-rules";
4
+ import { isSandboxWrapped } from "#src/client/shell-sandbox";
2
5
  import { isRecord } from "#src/client/text";
3
6
  import { describeToolCall } from "#src/client/tool-display";
4
7
  export const NO_ALLOW_ONCE_REASON = "agent offered no allow-once option";
@@ -8,6 +11,8 @@ export const FULL_REASON = 'profile "full" allows every permission request';
8
11
  export const UNKNOWN_PROFILE_REASON = "unknown profile";
9
12
  export const REVIEW_EXECUTE_REASON = 'profile "review" allows commands';
10
13
  export const REVIEW_NO_SANDBOX_REASON = 'profile "review" runs commands only inside the sandbox';
14
+ export const REVIEW_UNWRAPPED_REASON = "the command did not arrive in nax's sandbox wrapper";
15
+ export const SHELL_RULE_BLOCKED_REASON = 'a "Bash" deny or ask rule matches the command';
11
16
  export const NETWORK_OPEN_REASON = "the sandbox network is open";
12
17
  export const NETWORK_LISTED_REASON = "the sandbox network is an allow-list";
13
18
  /** claude-agent-acp 0.85.1 surfaces the SDK's sandbox network callback as a tool call titled with its tool name. */
@@ -34,6 +39,15 @@ export function offeredOptions(request) {
34
39
  ...(rejectOnce === undefined ? {} : { rejectOnce }),
35
40
  };
36
41
  }
42
+ /** A deny: `cancelled`, or a selected option the agent offered as a reject kind (nax#2582). */
43
+ export function isDenial(request, response) {
44
+ if (response.outcome.outcome === "cancelled")
45
+ return true;
46
+ const { optionId } = response.outcome;
47
+ const options = Array.isArray(request.options) ? request.options : [];
48
+ const chosen = options.find((option) => isRecord(option) && option.optionId === optionId);
49
+ return isRecord(chosen) && (chosen.kind === "reject_once" || chosen.kind === "reject_always");
50
+ }
37
51
  const cancelled = () => ({ outcome: { outcome: "cancelled" } });
38
52
  const selected = (optionId) => ({ outcome: { outcome: "selected", optionId } });
39
53
  /** A deny: the agent's reject_once, or `cancelled` when it offered none. */
@@ -69,18 +83,7 @@ export async function decidePermission(request, ctx) {
69
83
  auto(readOnlyReason(ctx.profile), "deny");
70
84
  return rejectWith(offered);
71
85
  case "review":
72
- if (display.tool !== "execute") {
73
- auto(readOnlyReason(ctx.profile), "deny");
74
- return rejectWith(offered);
75
- }
76
- if (ctx.sandbox === undefined) {
77
- auto(REVIEW_NO_SANDBOX_REASON, "deny");
78
- return rejectWith(offered);
79
- }
80
- if (offered.allowOnce === undefined)
81
- return denyNoAllowOnce(offered, auto);
82
- auto(REVIEW_EXECUTE_REASON, "allow");
83
- return selected(offered.allowOnce);
86
+ return decideReview(request, display, offered, auto, ctx);
84
87
  case "full":
85
88
  return decideFull(request, display, offered, auto, ctx);
86
89
  case "ask":
@@ -97,6 +100,70 @@ export async function decidePermission(request, ctx) {
97
100
  return rejectWith(offered);
98
101
  }
99
102
  }
103
+ /**
104
+ * review (SPEC-cursor-pi-acp-read-only US-003): a command may run when a sandbox
105
+ * holds it (Claude, nax#2500) or when the operator's own Bash rules allow the
106
+ * raw command. With no sandbox the rules are the whole decision — a command nax
107
+ * cannot read, a redirect, an opaque token, no allow rule, or an ask rule all
108
+ * deny — and everything that is not a command stays read-only.
109
+ */
110
+ function decideReview(request, display, offered, auto, ctx) {
111
+ if (ctx.shellSandbox !== undefined)
112
+ return decideSandboxedShell(request, display, offered, auto, ctx);
113
+ if (ctx.sandbox !== undefined) {
114
+ if (display.tool !== "execute") {
115
+ auto(readOnlyReason(ctx.profile), "deny");
116
+ return rejectWith(offered);
117
+ }
118
+ if (offered.allowOnce === undefined)
119
+ return denyNoAllowOnce(offered, auto);
120
+ auto(REVIEW_EXECUTE_REASON, "allow");
121
+ return selected(offered.allowOnce);
122
+ }
123
+ const command = shellCommandOf(ctx.agentName ?? "", request.toolCall);
124
+ if (command === undefined) {
125
+ // An execute request with no derivable command fails closed; anything else was never a command.
126
+ auto(display.tool === "execute" ? REVIEW_NO_SANDBOX_REASON : readOnlyReason(ctx.profile), "deny");
127
+ return rejectWith(offered);
128
+ }
129
+ if (shellRuleVerdict(command, ctx.rules ?? NO_RULES) === "deny") {
130
+ auto(REVIEW_NO_SANDBOX_REASON, "deny");
131
+ return rejectWith(offered);
132
+ }
133
+ if (offered.allowOnce === undefined)
134
+ return denyNoAllowOnce(offered, auto);
135
+ auto(SHELL_RULE_REASON, "allow");
136
+ return selected(offered.allowOnce);
137
+ }
138
+ /** Shell sandbox approvals precede the legacy sandbox/rule-only paths. */
139
+ export function decideSandboxedShell(request, display, offered, auto, ctx) {
140
+ const plan = ctx.shellSandbox;
141
+ const command = shellCommandOf(ctx.agentName ?? "", request.toolCall);
142
+ const deny = (reason) => {
143
+ auto(reason, "deny");
144
+ return rejectWith(offered);
145
+ };
146
+ if (command === undefined) {
147
+ return deny(display.tool === "execute" ? REVIEW_NO_SANDBOX_REASON : readOnlyReason(ctx.profile));
148
+ }
149
+ if (offered.allowOnce === undefined)
150
+ return denyNoAllowOnce(offered, auto);
151
+ const wrapped = plan !== undefined && isSandboxWrapped(plan.prefix, command);
152
+ // The verifier guarantees one quoted word; decode only its POSIX apostrophe escapes.
153
+ const inner = wrapped && plan?.verify ? command.slice(plan.prefix.length + 1, -1).replaceAll("'\\''", "'") : command;
154
+ if (shellRuleBlocks(inner, ctx.rules ?? NO_RULES))
155
+ return deny(SHELL_RULE_BLOCKED_REASON);
156
+ if (plan !== undefined && (!plan.verify || wrapped)) {
157
+ auto(REVIEW_EXECUTE_REASON, "allow");
158
+ return selected(offered.allowOnce);
159
+ }
160
+ if (plan?.onUnwrapped === "deny")
161
+ return deny(REVIEW_UNWRAPPED_REASON);
162
+ if (shellRuleVerdict(command, ctx.rules ?? NO_RULES) === "deny")
163
+ return deny(REVIEW_NO_SANDBOX_REASON);
164
+ auto(SHELL_RULE_REASON, "allow");
165
+ return selected(offered.allowOnce);
166
+ }
100
167
  /**
101
168
  * ACP kinds exempt from the R4 path check (nax#2500 R5/R8): they do not write a path
102
169
  * the sandbox has to police. execute is the Bash sandbox's job. Every other kind,
@@ -0,0 +1,2 @@
1
+ /** Generate a standalone extension; piModule is replaceable by a test fixture. */
2
+ export declare function piSandboxGateSource(prefix: string, piModule?: string): string;