@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
@@ -0,0 +1,22 @@
1
+ /** pi's per-command confirmation gate plus a spawn-time sandbox wrapper. */
2
+ import { PI_SHELL_GATE_SOURCE } from "#src/client/shell-rules";
3
+ import { sandboxWrapSnippet } from "#src/client/shell-sandbox";
4
+ /** Generate a standalone extension; piModule is replaceable by a test fixture. */
5
+ export function piSandboxGateSource(prefix, piModule = "@earendil-works/pi-coding-agent") {
6
+ return `import { createBashTool } from ${JSON.stringify(piModule)};
7
+ ${sandboxWrapSnippet(prefix)}
8
+ ${PI_SHELL_GATE_SOURCE.replace("export default function", "function")}
9
+ export default function naxSandboxGate(pi) {
10
+ naxShellGate(pi);
11
+ const bash = createBashTool(process.cwd(), {
12
+ spawnHook: ({ command, cwd, env }) => ({ command: naxSandboxWrap(command), cwd, env }),
13
+ });
14
+ pi.registerTool({
15
+ ...bash,
16
+ execute(id, params, signal, onUpdate) {
17
+ return bash.execute(id, params, signal, onUpdate);
18
+ },
19
+ });
20
+ }
21
+ `;
22
+ }
@@ -0,0 +1,21 @@
1
+ /** Every file-system call the writers make; a test overrides them before any real write. */
2
+ export interface PolicyFileDeps {
3
+ mkdir(path: string, options: {
4
+ readonly recursive: true;
5
+ readonly mode: number;
6
+ }): Promise<unknown>;
7
+ writeFile(path: string, content: string): Promise<unknown>;
8
+ chmod(path: string, mode: number): Promise<unknown>;
9
+ rename(from: string, to: string): Promise<unknown>;
10
+ }
11
+ export declare const _policyFilesDeps: PolicyFileDeps;
12
+ /** pi's rule or sandbox gate extension, and the wrapper `PI_ACP_PI_COMMAND` names. */
13
+ export type PiPolicyFile = "shell-gate" | "wrapper" | "sandbox-gate";
14
+ /** The content-addressed part of a policy path. */
15
+ export declare function digest(content: string): string;
16
+ /** Write a nax-owned file under the state directory through the shared atomic writer. */
17
+ export declare function writeStateFile(stateDir: string, relPath: string, content: string, mode: number): Promise<string>;
18
+ /** Cursor's isolated config: `<stateDir>/cursor/<h>/cli-config.json`. Returns the directory to point CURSOR_CONFIG_DIR at. */
19
+ export declare function writeCursorPolicy(stateDir: string, content: string): Promise<string>;
20
+ /** pi's `<stateDir>/pi/<name>-<h><ext>`; returns the file path. */
21
+ export declare function writePiFile(stateDir: string, name: PiPolicyFile, content: string, mode: number): Promise<string>;
@@ -0,0 +1,73 @@
1
+ /**
2
+ * The policy files Cursor and pi read (SPEC-cursor-pi-acp-read-only US-004).
3
+ * Neither agent reads nax's rules directly: Cursor loads a `cli-config.json` from
4
+ * `CURSOR_CONFIG_DIR` and pi loads an extension with `-e` and takes its tool
5
+ * allowlist from `--tools`, so nax writes the files and points the process's
6
+ * environment at them (rule-policy.ts).
7
+ *
8
+ * Each file is content-addressed — the first 16 hex characters of the SHA-256 of
9
+ * its body — and written atomically through a temporary name in its target
10
+ * directory, on every launch: Cursor rewrites its config itself, and a rewrite
11
+ * replaces a planted or half-written file. The state directory's owner is the
12
+ * trust boundary; this package creates the directories 0700 and never reads back
13
+ * what is already there.
14
+ */
15
+ import { createHash, randomBytes } from "node:crypto";
16
+ import { chmod, mkdir, rename, writeFile } from "node:fs/promises";
17
+ import { basename, dirname, join } from "node:path";
18
+ import { backendUnavailable } from "#src/client/errors";
19
+ export const _policyFilesDeps = { mkdir, writeFile, chmod, rename };
20
+ const PI_EXTENSIONS = Object.freeze({
21
+ "shell-gate": ".ts",
22
+ wrapper: ".sh",
23
+ "sandbox-gate": ".ts",
24
+ });
25
+ /** Nothing here is readable by another user: the directory is ours, the policy files are ours. */
26
+ const DIR_MODE = 0o700;
27
+ const CURSOR_CONFIG_MODE = 0o600;
28
+ /** The content-addressed part of a policy path. */
29
+ export function digest(content) {
30
+ return createHash("sha256").update(content).digest("hex").slice(0, 16);
31
+ }
32
+ function messageOf(err) {
33
+ return err instanceof Error ? err.message : String(err);
34
+ }
35
+ /**
36
+ * `target` with `content`, atomically and every time. The chmod runs on the
37
+ * temporary file before the rename, so the umask cannot narrow the mode and no
38
+ * reader ever sees a partial file. The temporary name is unique per call: two
39
+ * opens racing on the same content (two sessions, one process) never rename each
40
+ * other's file away. Any failure refuses the open — the caller has launched
41
+ * nothing yet — naming the path that could not be written.
42
+ */
43
+ async function writeAtomic(target, content, mode) {
44
+ const dir = dirname(target);
45
+ const temp = join(dir, `${basename(target)}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`);
46
+ try {
47
+ await _policyFilesDeps.mkdir(dir, { recursive: true, mode: DIR_MODE });
48
+ await _policyFilesDeps.writeFile(temp, content);
49
+ await _policyFilesDeps.chmod(temp, mode);
50
+ await _policyFilesDeps.rename(temp, target);
51
+ }
52
+ catch (err) {
53
+ throw backendUnavailable(`the read-only policy file "${target}" could not be written: ${messageOf(err)}`, {
54
+ path: target,
55
+ });
56
+ }
57
+ }
58
+ /** Write a nax-owned file under the state directory through the shared atomic writer. */
59
+ export async function writeStateFile(stateDir, relPath, content, mode) {
60
+ const target = join(stateDir, relPath);
61
+ await writeAtomic(target, content, mode);
62
+ return target;
63
+ }
64
+ /** Cursor's isolated config: `<stateDir>/cursor/<h>/cli-config.json`. Returns the directory to point CURSOR_CONFIG_DIR at. */
65
+ export async function writeCursorPolicy(stateDir, content) {
66
+ const dir = join(stateDir, "cursor", digest(content));
67
+ await writeAtomic(join(dir, "cli-config.json"), content, CURSOR_CONFIG_MODE);
68
+ return dir;
69
+ }
70
+ /** pi's `<stateDir>/pi/<name>-<h><ext>`; returns the file path. */
71
+ export async function writePiFile(stateDir, name, content, mode) {
72
+ return writeStateFile(stateDir, join("pi", `${name}-${digest(content)}${PI_EXTENSIONS[name]}`), content, mode);
73
+ }
@@ -6,7 +6,7 @@
6
6
  * agents (`{ name, command }`) have no entry: no mode ids, no pre-approval and no
7
7
  * auth variables, so their requirements fail closed.
8
8
  */
9
- export type AcpAgentName = "claude" | "codex" | "gemini" | "opencode" | "pi";
9
+ export type AcpAgentName = "claude" | "codex" | "cursor" | "gemini" | "opencode" | "pi";
10
10
  export interface LaunchCandidate {
11
11
  readonly command: string;
12
12
  readonly args: readonly string[];
@@ -17,23 +17,41 @@ export interface ModeSetting {
17
17
  readonly value: string;
18
18
  }
19
19
  /**
20
- * How profiles none and read are enforced on this agent (§6.4 layer 1, as revised
21
- * by the 2026-10-07 fix bundle). Applied through the agent's pre-approval channel,
22
- * so only an agent with one may declare it.
20
+ * How profiles none, read and review are enforced on this agent (§6.4 layer 1, as
21
+ * revised by the 2026-10-07 fix bundle). An agent may enforce read-only through its
22
+ * mode alone (codex-acp's `read-only`, nax#2372) or through variables injected into
23
+ * its process environment (opencode's `OPENCODE_CONFIG_CONTENT` permission policy);
24
+ * `disallowedTools` and `sessionOptions` go through the pre-approval channel and are
25
+ * empty for an agent that has none.
23
26
  */
24
27
  export interface ReadOnlyEnforcement {
25
- /** The mode set for none/read. */
26
- readonly mode: ModeSetting;
27
- /** Agent tools removed from the session under none/read. */
28
+ /** The mode set for none/read/review; undefined means nax sets no mode for them. */
29
+ readonly mode: ModeSetting | undefined;
30
+ /**
31
+ * The mode set under `review` instead of `mode` when an operator Bash allow rule
32
+ * makes nax decide shell requests (nax#2592). For an agent whose read-only mode
33
+ * tells the model it cannot run commands, so it never asks; enforcement stays with
34
+ * the agent's permission config and nax's shell decision. Absent: `mode` throughout.
35
+ */
36
+ readonly reviewShellMode?: ModeSetting;
37
+ /** Agent tools removed from the session under none/read/review. */
28
38
  readonly disallowedTools: readonly string[];
29
- /** Extra agent options under none/read, merged into the pre-approval channel's options. */
39
+ /** Extra agent options under none/read/review, merged into the pre-approval channel's options. */
30
40
  readonly sessionOptions: Readonly<Record<string, unknown>>;
41
+ /** Extra agent process environment under none/read/review, by profile; {} when the agent needs none. */
42
+ readonly launchEnv: Readonly<Partial<Record<"none" | "read" | "review", Readonly<Record<string, string>>>>>;
43
+ /**
44
+ * The rule-policy translator that builds this agent's launch env from nax's
45
+ * permission rules (rule-policy.ts); undefined means the agent's env is the
46
+ * `launchEnv` above, whatever the rules.
47
+ */
48
+ readonly policy: "opencode" | "cursor" | "pi" | undefined;
31
49
  }
32
50
  export interface AgentRegistryEntry {
33
51
  readonly name: AcpAgentName;
34
52
  /** Tried in order; the first command found wins (S4-2 launch). */
35
53
  readonly launch: readonly LaunchCandidate[];
36
- /** How profiles `none` and `read` are enforced; undefined means those profiles are unsupported (§6.4). */
54
+ /** How profiles `none`, `read` and `review` are enforced; undefined means those profiles are unsupported (§6.4). */
37
55
  readonly readOnly: ReadOnlyEnforcement | undefined;
38
56
  /** Mode for profiles `ask` and `full`; undefined means the agent's own default is kept. */
39
57
  readonly defaultMode: ModeSetting | undefined;
@@ -42,6 +60,12 @@ export interface AgentRegistryEntry {
42
60
  /** Variables passed through the env allowlist so the adapter can authenticate itself (§6.2). */
43
61
  readonly authEnv: readonly string[];
44
62
  }
63
+ /** none: no tool at all. */
64
+ export declare const OPENCODE_NONE_CONFIG: string;
65
+ /** read: only opencode's read tools. */
66
+ export declare const OPENCODE_READ_CONFIG: string;
67
+ /** review: the read tools, plus shell commands asked of nax (decided by the review rule). */
68
+ export declare const OPENCODE_REVIEW_CONFIG: string;
45
69
  export declare const ACP_AGENT_NAMES: readonly AcpAgentName[];
46
70
  export declare function isAcpAgentName(name: string): name is AcpAgentName;
47
71
  /** The registry entry for a registered agent name; undefined for anything else (custom agents included). */
@@ -15,19 +15,41 @@ function freezeReadOnly(readOnly) {
15
15
  key,
16
16
  Array.isArray(value) ? Object.freeze([...value]) : value,
17
17
  ]);
18
+ const launchEnv = Object.entries(readOnly.launchEnv).map(([profile, env]) => [profile, Object.freeze({ ...env })]);
19
+ // A mode-less agent (opencode, nax#2372) sets no mode at all: there is nothing to copy.
20
+ const mode = readOnly.mode === undefined ? undefined : Object.freeze({ ...readOnly.mode });
18
21
  return Object.freeze({
19
- mode: Object.freeze({ ...readOnly.mode }),
22
+ mode,
23
+ ...(readOnly.reviewShellMode === undefined
24
+ ? {}
25
+ : { reviewShellMode: Object.freeze({ ...readOnly.reviewShellMode }) }),
20
26
  disallowedTools: Object.freeze([...readOnly.disallowedTools]),
21
27
  sessionOptions: Object.freeze(Object.fromEntries(options)),
28
+ launchEnv: Object.freeze(Object.fromEntries(launchEnv)),
29
+ policy: readOnly.policy,
22
30
  });
23
31
  }
24
- function entry(name, launch, authEnv, claude) {
32
+ // opencode's permission policy, injected as `OPENCODE_CONFIG_CONTENT` (its highest-rank
33
+ // config source). Rules are last-match-wins over { action, resource }, so the catch-all
34
+ // deny comes first and each allowance after it. A denied tool is removed from opencode's
35
+ // catalog, so the model never sees it.
36
+ /** none: no tool at all. */
37
+ export const OPENCODE_NONE_CONFIG = JSON.stringify({ permission: { "*": "deny" } });
38
+ /** read: only opencode's read tools. */
39
+ export const OPENCODE_READ_CONFIG = JSON.stringify({
40
+ permission: { "*": "deny", read: "allow", glob: "allow", grep: "allow", list: "allow" },
41
+ });
42
+ /** review: the read tools, plus shell commands asked of nax (decided by the review rule). */
43
+ export const OPENCODE_REVIEW_CONFIG = JSON.stringify({
44
+ permission: { "*": "deny", read: "allow", glob: "allow", grep: "allow", list: "allow", bash: "ask" },
45
+ });
46
+ function entry(name, launch, authEnv, policy) {
25
47
  return Object.freeze({
26
48
  name,
27
49
  launch: Object.freeze(launch.map((c) => Object.freeze({ command: c.command, args: Object.freeze([...c.args]) }))),
28
- readOnly: freezeReadOnly(claude?.readOnly),
29
- defaultMode: claude?.defaultMode === undefined ? undefined : Object.freeze({ ...claude.defaultMode }),
30
- preApproval: claude?.preApproval,
50
+ readOnly: freezeReadOnly(policy?.readOnly),
51
+ defaultMode: policy?.defaultMode === undefined ? undefined : Object.freeze({ ...policy.defaultMode }),
52
+ preApproval: policy?.preApproval,
31
53
  authEnv: Object.freeze([...authEnv]),
32
54
  });
33
55
  }
@@ -42,16 +64,115 @@ const REGISTRY = new Map([
42
64
  mode: { configId: "mode", value: "default" },
43
65
  disallowedTools: ["Write", "Edit", "MultiEdit", "NotebookEdit", "EnterPlanMode"],
44
66
  sessionOptions: { settingSources: [], allowDangerouslySkipPermissions: false },
67
+ launchEnv: {},
68
+ policy: undefined,
45
69
  },
46
70
  defaultMode: { configId: "mode", value: "default" },
47
71
  preApproval: "claudeCode.allowedTools",
48
72
  }),
49
73
  ],
50
- ["codex", entry("codex", [local("codex-acp"), npx("@agentclientprotocol/codex-acp@~2.1.1")], ["OPENAI_API_KEY"])],
51
- ["gemini", entry("gemini", [local("gemini", "--acp")], ["GEMINI_API_KEY"])],
52
- ["opencode", entry("opencode", [local("opencode", "acp")], [])],
74
+ [
75
+ "codex",
76
+ entry("codex", [local("codex-acp"), npx("@agentclientprotocol/codex-acp@~2.1.1")], ["OPENAI_API_KEY"], {
77
+ // nax#2372: codex-acp enforces none/read/review with its own `read-only` mode (OS
78
+ // sandbox, read-only filesystem, no network, every escalation asked of us). It has
79
+ // no pre-approval channel, so no settings and no removed tools ride along; full and
80
+ // ask keep the launch mode (US-002 sets it from config).
81
+ readOnly: {
82
+ mode: { configId: "mode", value: "read-only" },
83
+ disallowedTools: [],
84
+ sessionOptions: {},
85
+ launchEnv: {},
86
+ policy: undefined,
87
+ },
88
+ defaultMode: undefined,
89
+ preApproval: undefined,
90
+ }),
91
+ ],
92
+ // nax#2372: cursor's own modes do not enforce anything (probed: mode `ask` let a forced
93
+ // write through, mode `plan` let the model switch back to `agent` and write), so `ask`
94
+ // only tells the model it is read-only; the real enforcement is its permission config
95
+ // (US-004: an isolated cli-config.json, pointed at by CURSOR_CONFIG_DIR). No plan mode
96
+ // is ever used here. nax#2592: `ask` also makes the model refuse to try a shell command,
97
+ // so review with an operator Bash allow rule runs in `agent`: writes stay denied by the
98
+ // permission config, and nax decides every shell request (shell-rules.ts).
99
+ [
100
+ "cursor",
101
+ entry("cursor", [local("cursor-agent", "acp")], ["CURSOR_API_KEY"], {
102
+ readOnly: {
103
+ mode: { configId: "mode", value: "ask" },
104
+ reviewShellMode: { configId: "mode", value: "agent" },
105
+ disallowedTools: [],
106
+ sessionOptions: {},
107
+ launchEnv: {},
108
+ policy: "cursor",
109
+ },
110
+ defaultMode: undefined,
111
+ preApproval: undefined,
112
+ }),
113
+ ],
114
+ // nax#2372: gemini's `plan` mode is its read-only mode (read tools only, no shell
115
+ // tool). It has no pre-approval channel, so no settings and no removed tools ride
116
+ // along; full and ask keep the launch mode.
117
+ [
118
+ "gemini",
119
+ entry("gemini", [local("gemini", "--acp")], ["GEMINI_API_KEY"], {
120
+ readOnly: {
121
+ mode: { configId: "mode", value: "plan" },
122
+ disallowedTools: [],
123
+ sessionOptions: {},
124
+ launchEnv: {},
125
+ policy: undefined,
126
+ },
127
+ defaultMode: undefined,
128
+ preApproval: undefined,
129
+ }),
130
+ ],
131
+ // nax#2372: opencode has no read-only mode (its `plan` agent still runs shell and web
132
+ // tools). Enforcement is its own permission config, injected per profile as an env
133
+ // variable: opencode denies every tool, then allows its read tools back for read and
134
+ // review, and under review asks nax about each shell command. No mode is set, and it
135
+ // has no pre-approval channel (embedder tools stay unsupported). The launch env below
136
+ // is what an operator with no read-tool deny rule gets; `policy: "opencode"` lets
137
+ // rule-policy.ts translate an unconditional deny of Read, Glob or Grep instead.
138
+ [
139
+ "opencode",
140
+ entry("opencode", [local("opencode", "acp")], [], {
141
+ readOnly: {
142
+ mode: undefined,
143
+ disallowedTools: [],
144
+ sessionOptions: {},
145
+ launchEnv: {
146
+ none: { OPENCODE_CONFIG_CONTENT: OPENCODE_NONE_CONFIG },
147
+ read: { OPENCODE_CONFIG_CONTENT: OPENCODE_READ_CONFIG },
148
+ review: { OPENCODE_CONFIG_CONTENT: OPENCODE_REVIEW_CONFIG },
149
+ },
150
+ policy: "opencode",
151
+ },
152
+ defaultMode: undefined,
153
+ preApproval: undefined,
154
+ }),
155
+ ],
53
156
  // Exact pin: a tilde range does not pin 0.0.x.
54
- ["pi", entry("pi", [local("pi-acp"), npx("pi-acp@0.0.34")], [])],
157
+ // nax#2372, US-004: pi has no mode and no permission config of its own. Read-only is
158
+ // its own tool allowlist (`--tools` / `--no-tools`) plus, under review, the gate
159
+ // extension that turns every bash call into a confirm prompt nax decides
160
+ // (rule-policy.ts, shell-rules.ts). Both are written per launch and named by the
161
+ // wrapper PI_ACP_PI_COMMAND points at.
162
+ [
163
+ "pi",
164
+ entry("pi", [local("pi-acp"), npx("pi-acp@0.0.34")], [], {
165
+ readOnly: {
166
+ mode: undefined,
167
+ disallowedTools: [],
168
+ sessionOptions: {},
169
+ launchEnv: {},
170
+ policy: "pi",
171
+ },
172
+ defaultMode: undefined,
173
+ preApproval: undefined,
174
+ }),
175
+ ],
55
176
  ]);
56
177
  export const ACP_AGENT_NAMES = Object.freeze([...REGISTRY.keys()]);
57
178
  export function isAcpAgentName(name) {
@@ -1,8 +1,9 @@
1
- import type { LoadSessionResponse, McpServer, ResumeSessionResponse, SessionConfigOption } from "@agentclientprotocol/sdk";
1
+ import type { LoadSessionResponse, McpServer, ResumeSessionResponse } from "@agentclientprotocol/sdk";
2
2
  import { type BackendOpenContext, type TranscriptDoc } from "@nathapp/nax-agent";
3
3
  import type { CapabilityRecord } from "#src/client/capabilities";
4
4
  import type { AcpLink } from "#src/client/connection";
5
5
  import type { ResolvedAcpOptions } from "#src/client/options";
6
+ import { type SessionOffers } from "#src/client/session-offers";
6
7
  /** An agent session id longer than this is not trusted (S4-2 Review Focus 5). */
7
8
  export declare const MAX_SESSION_ID_CHARS = 512;
8
9
  /** A stored agent session to restore: from the document (resume) or the live session (reconnect). */
@@ -17,7 +18,8 @@ export type RestoredWith = "resume" | "load";
17
18
  export interface RestoredSession {
18
19
  readonly agentSessionId: string;
19
20
  readonly cwd: string;
20
- readonly configOptions: readonly SessionConfigOption[];
21
+ /** What the resume/load answer offers a profile: config options and the legacy blocks (session-offers.ts). */
22
+ readonly offers: SessionOffers;
21
23
  readonly restoredWith: RestoredWith;
22
24
  }
23
25
  /** What session/new, session/resume and session/load add to `cwd`: the tool host's entry and Claude's `_meta` (§6.6, #2365). */
@@ -31,7 +33,7 @@ export declare function isUsableSessionId(value: unknown): value is string;
31
33
  export declare function canRestore(record: CapabilityRecord): boolean;
32
34
  /** §6.9 step 1 (D6-b, D6-c). Throws before anything is spawned. */
33
35
  export declare function storedSessionOf(doc: TranscriptDoc, ctx: BackendOpenContext, options: ResolvedAcpOptions): Restore;
34
- /** §6.9 step 3 (D6-d): an echoed id must be the stored one. A null answer (D6-k) has no config options. */
36
+ /** §6.9 step 3 (D6-d): an echoed id must be the stored one. A null answer (D6-k) offers nothing. */
35
37
  export declare function checkRestored(restore: Restore, via: RestoredWith, response: ResumeSessionResponse | LoadSessionResponse): RestoredSession;
36
38
  /** §6.9 step 2: session/resume when advertised, else session/load; never a fresh session. */
37
39
  export declare function restoreSession(restore: Restore, record: CapabilityRecord, setup: SessionSetup, link: AcpLink, step: OpenStep): Promise<RestoredSession>;
@@ -14,6 +14,7 @@ import { realpathSync } from "node:fs";
14
14
  import { resolve } from "node:path";
15
15
  import { AgentSessionError, NaxError } from "@nathapp/nax-agent";
16
16
  import { capabilityUnsupported } from "#src/client/errors";
17
+ import { sessionOffers } from "#src/client/session-offers";
17
18
  import { isRecord } from "#src/client/text";
18
19
  /** An agent session id longer than this is not trusted (S4-2 Review Focus 5). */
19
20
  export const MAX_SESSION_ID_CHARS = 512;
@@ -65,7 +66,7 @@ export function storedSessionOf(doc, ctx, options) {
65
66
  }
66
67
  return { agentSessionId: acp.agentSessionId, cwd: acp.cwd, costUsd: costOf(acp.costUsd) };
67
68
  }
68
- /** §6.9 step 3 (D6-d): an echoed id must be the stored one. A null answer (D6-k) has no config options. */
69
+ /** §6.9 step 3 (D6-d): an echoed id must be the stored one. A null answer (D6-k) offers nothing. */
69
70
  export function checkRestored(restore, via, response) {
70
71
  const raw = response;
71
72
  const echoed = isRecord(raw) ? raw.sessionId : undefined;
@@ -78,7 +79,7 @@ export function checkRestored(restore, via, response) {
78
79
  return {
79
80
  agentSessionId: restore.agentSessionId,
80
81
  cwd: restore.cwd,
81
- configOptions: isRecord(raw) ? (response.configOptions ?? []) : [],
82
+ offers: sessionOffers(raw),
82
83
  restoredWith: via,
83
84
  };
84
85
  }
@@ -0,0 +1,55 @@
1
+ import type { AgentSessionProfile } from "@nathapp/nax-agent";
2
+ import type { ResolvedAcpOptions } from "#src/client/options";
3
+ export interface AcpRule {
4
+ readonly tool: string;
5
+ readonly patterns: readonly string[];
6
+ }
7
+ export interface AcpPermissionRules {
8
+ readonly allow: readonly AcpRule[];
9
+ readonly deny: readonly AcpRule[];
10
+ readonly ask: readonly AcpRule[];
11
+ }
12
+ /** The rules of a caller that has none: every list empty. */
13
+ export declare const NO_RULES: AcpPermissionRules;
14
+ /**
15
+ * opencode's permission config for a read-only profile (SPEC US-002). An
16
+ * unconditional deny of a read tool removes its entries, so opencode drops the
17
+ * tool from the model's catalog; with no such rule the result is byte-identical
18
+ * to the registry's OPENCODE_*_CONFIG. `none` ignores the rules: every tool is
19
+ * denied there and no rule can widen it. Bash rules are never translated (an
20
+ * agent matching command text knows nothing of redirects), and `read` keeps no
21
+ * shell tool while `review` asks nax about every command.
22
+ */
23
+ export declare function opencodePermissionConfig(profile: "none" | "read" | "review", rules: AcpPermissionRules): string;
24
+ /**
25
+ * Cursor's isolated permission config (SPEC US-004). Cursor's own modes enforce
26
+ * nothing, so this file is the whole enforcement: `Read(**)` is allowed unless an
27
+ * unconditional Read deny removes it (and then joins the deny list), writes, MCP
28
+ * and the web are denied, and shell is denied under `read` and absent under
29
+ * `review`, where Cursor asks the client about every command and nax decides it
30
+ * (shell-rules.ts). `none` ignores the rules: everything is denied there, and no
31
+ * rule can widen it.
32
+ */
33
+ export declare function cursorCliConfig(profile: "none" | "read" | "review", rules: AcpPermissionRules): string;
34
+ /**
35
+ * pi's `--tools` arguments (SPEC US-004): `--no-tools` under `none`, else pi's
36
+ * read tools in a fixed order minus the ones an unconditional deny removed.
37
+ * `Glob` owns pi's `find` and `ls`. Under `review` with a Bash allow rule, `bash`
38
+ * is appended after the read tools and the gate extension is loaded first, so
39
+ * every command goes through the nax shell gate.
40
+ */
41
+ export declare function piToolArgs(profile: "none" | "read" | "review", rules: AcpPermissionRules, gatePath: string, sandbox?: {
42
+ extensions: "user" | "none";
43
+ }): readonly string[];
44
+ /**
45
+ * The environment the profile's rules add to the agent process (SPEC US-002,
46
+ * extended by US-004), the one seam every launch goes through — a new session, a
47
+ * resume and a reconnect. An agent whose entry names no policy keeps its
48
+ * `launchEnv` untouched, so its env is exactly what it was before rules existed;
49
+ * a custom agent has no entry and gets nothing. Cursor and pi read their policy
50
+ * from files under the state directory, written here before anything is spawned:
51
+ * a file that cannot be written refuses the open (policy-files.ts). The caller
52
+ * spreads this over its own env, so neither the caller nor a model can weaken the
53
+ * enforcement value.
54
+ */
55
+ export declare function policyLaunchEnv(profile: AgentSessionProfile, options: ResolvedAcpOptions): Promise<Readonly<Record<string, string>>>;
@@ -0,0 +1,181 @@
1
+ /**
2
+ * nax's permission rules, translated into an ACP agent's own configuration
3
+ * (SPEC-cursor-pi-acp-read-only). A rule is one `Tool(...)` grant of the grammar
4
+ * native sessions use: `tool` names the tool, `patterns` are its patterns, and a
5
+ * rule is unconditional when one of its patterns is `*` (nax's own test, which
6
+ * treats `["*", "src/**"]` as unconditional too).
7
+ *
8
+ * Only an unconditional deny of a read tool (`Read`, `Glob`, `Grep`) is
9
+ * translated here, and only for profiles `read` and `review`: a read-only
10
+ * profile already runs with the agent's write tools removed, so no rule can
11
+ * widen it. Bash rules are applied by nax itself (shell-rules.ts, US-003), and
12
+ * a path-scoped or non-deny rule is left to the native matcher.
13
+ */
14
+ import { relative } from "node:path";
15
+ import { isReadOnlyProfile, launchEnvFor, reviewDecidesShell } from "#src/client/capabilities";
16
+ import { cursorSandboxEnv } from "#src/client/cursor-sandbox";
17
+ import { opencodeSandboxEnv } from "#src/client/opencode-sandbox";
18
+ import { piSandboxGateSource } from "#src/client/pi-sandbox";
19
+ import { writeCursorPolicy, writePiFile, writeStateFile } from "#src/client/policy-files";
20
+ import { OPENCODE_NONE_CONFIG, OPENCODE_READ_CONFIG, OPENCODE_REVIEW_CONFIG } from "#src/client/registry";
21
+ import { PI_SHELL_GATE_SOURCE } from "#src/client/shell-rules";
22
+ import { shellQuote } from "#src/client/shell-sandbox";
23
+ const NONE = Object.freeze([]);
24
+ /** The rules of a caller that has none: every list empty. */
25
+ export const NO_RULES = Object.freeze({ allow: NONE, deny: NONE, ask: NONE });
26
+ /** A rule denies this tool outright: nax's own "unconditional" test, a pattern holding `*`. */
27
+ function denied(rules, tool) {
28
+ return rules.deny.some((rule) => rule.tool === tool && rule.patterns.includes("*"));
29
+ }
30
+ /**
31
+ * opencode's `permission` entries and the read tool each one serves, in the order
32
+ * the registry's own configs list them: the catch-all deny first, then each
33
+ * allowance, because opencode's rules are last-match-wins. `list` belongs to
34
+ * `Read`: without the read tool opencode has no reason to list directories either.
35
+ */
36
+ const OPENCODE_ENTRIES = Object.freeze([
37
+ Object.freeze(["read", "Read"]),
38
+ Object.freeze(["glob", "Glob"]),
39
+ Object.freeze(["grep", "Grep"]),
40
+ Object.freeze(["list", "Read"]),
41
+ ]);
42
+ /**
43
+ * opencode's permission config for a read-only profile (SPEC US-002). An
44
+ * unconditional deny of a read tool removes its entries, so opencode drops the
45
+ * tool from the model's catalog; with no such rule the result is byte-identical
46
+ * to the registry's OPENCODE_*_CONFIG. `none` ignores the rules: every tool is
47
+ * denied there and no rule can widen it. Bash rules are never translated (an
48
+ * agent matching command text knows nothing of redirects), and `read` keeps no
49
+ * shell tool while `review` asks nax about every command.
50
+ */
51
+ export function opencodePermissionConfig(profile, rules) {
52
+ if (profile === "none")
53
+ return OPENCODE_NONE_CONFIG;
54
+ const kept = OPENCODE_ENTRIES.filter(([, tool]) => !denied(rules, tool));
55
+ // No read tool is denied: the operator default, byte for byte.
56
+ if (kept.length === OPENCODE_ENTRIES.length) {
57
+ return profile === "review" ? OPENCODE_REVIEW_CONFIG : OPENCODE_READ_CONFIG;
58
+ }
59
+ const permission = { "*": "deny" };
60
+ for (const [key] of kept)
61
+ permission[key] = "allow";
62
+ if (profile === "review")
63
+ permission.bash = "ask";
64
+ return JSON.stringify({ permission });
65
+ }
66
+ /** Cursor's write and web tools, denied in every read-only profile and in this order. */
67
+ const CURSOR_DENIES = Object.freeze(["Write(**)", "Delete(**)", "Mcp(*:*)", "WebFetch(*)"]);
68
+ /**
69
+ * Cursor's isolated permission config (SPEC US-004). Cursor's own modes enforce
70
+ * nothing, so this file is the whole enforcement: `Read(**)` is allowed unless an
71
+ * unconditional Read deny removes it (and then joins the deny list), writes, MCP
72
+ * and the web are denied, and shell is denied under `read` and absent under
73
+ * `review`, where Cursor asks the client about every command and nax decides it
74
+ * (shell-rules.ts). `none` ignores the rules: everything is denied there, and no
75
+ * rule can widen it.
76
+ */
77
+ export function cursorCliConfig(profile, rules) {
78
+ const readDenied = profile === "none" || denied(rules, "Read");
79
+ /** review leaves shell unlisted: every command is asked of the client, and nax answers (US-003). */
80
+ const deny = [...CURSOR_DENIES, ...(profile === "review" ? [] : ["Shell(*)"]), ...(readDenied ? ["Read(**)"] : [])];
81
+ return JSON.stringify({
82
+ version: 1,
83
+ permissions: { allow: readDenied ? [] : ["Read(**)"], deny },
84
+ approvalMode: "allowlist",
85
+ });
86
+ }
87
+ /** pi's tools in the order `--tools` lists them, and the read tool each one serves. */
88
+ const PI_TOOLS = Object.freeze([
89
+ Object.freeze(["read", "Read"]),
90
+ Object.freeze(["grep", "Grep"]),
91
+ Object.freeze(["find", "Glob"]),
92
+ Object.freeze(["ls", "Glob"]),
93
+ ]);
94
+ const PI_GATE_ARG = "-e";
95
+ /**
96
+ * pi's `--tools` arguments (SPEC US-004): `--no-tools` under `none`, else pi's
97
+ * read tools in a fixed order minus the ones an unconditional deny removed.
98
+ * `Glob` owns pi's `find` and `ls`. Under `review` with a Bash allow rule, `bash`
99
+ * is appended after the read tools and the gate extension is loaded first, so
100
+ * every command goes through the nax shell gate.
101
+ */
102
+ export function piToolArgs(profile, rules, gatePath, sandbox) {
103
+ if (profile === "none")
104
+ return ["--no-tools"];
105
+ const readTools = PI_TOOLS.filter(([, tool]) => !denied(rules, tool)).map(([name]) => name);
106
+ const sandboxed = profile === "review" && sandbox !== undefined;
107
+ const gated = sandboxed || reviewDecidesShell(profile, rules);
108
+ const tools = gated ? [...readTools, "bash"] : readTools;
109
+ if (tools.length === 0)
110
+ return ["--no-tools"];
111
+ return [
112
+ ...(sandboxed && sandbox.extensions === "none" ? ["--no-extensions"] : []),
113
+ ...(gated ? [PI_GATE_ARG, gatePath] : []),
114
+ "--tools",
115
+ tools.join(","),
116
+ ];
117
+ }
118
+ /** The gate extension is nax's own source, readable by the user alone; the wrapper has to be executable. */
119
+ const PI_GATE_MODE = 0o600;
120
+ const PI_WRAPPER_MODE = 0o700;
121
+ /** pi-acp's own default when the caller names no executable. */
122
+ const PI_DEFAULT_COMMAND = "pi";
123
+ /** The wrapper `PI_ACP_PI_COMMAND` names: exec pi with the profile's arguments, forwarding the caller's own. */
124
+ function piWrapper(command, args) {
125
+ return `#!/bin/sh\nexec ${[command, ...args].map(shellQuote).join(" ")} "$@"\n`;
126
+ }
127
+ /**
128
+ * pi's launch env: the gate extension when one is needed, then the wrapper that
129
+ * runs pi with the profile's `--tools` (or `--no-tools`). The caller's own
130
+ * `PI_ACP_PI_COMMAND` names the executable to wrap, so a caller can point nax at
131
+ * a pi build without weakening the enforcement.
132
+ */
133
+ async function piLaunchEnv(options, profile) {
134
+ const rules = options.rules;
135
+ const plan = profile === "review" && options.shellSandboxPlan?.agent === "pi" ? options.shellSandboxPlan : undefined;
136
+ const gate = plan
137
+ ? await writePiFile(options.stateDir, "sandbox-gate", piSandboxGateSource(plan.prefix), PI_GATE_MODE)
138
+ : reviewDecidesShell(profile, rules)
139
+ ? await writePiFile(options.stateDir, "shell-gate", PI_SHELL_GATE_SOURCE, PI_GATE_MODE)
140
+ : "";
141
+ const command = options.env.PI_ACP_PI_COMMAND ?? PI_DEFAULT_COMMAND;
142
+ const body = piWrapper(command, piToolArgs(profile, rules, gate, plan ? { extensions: plan.piExtensions } : undefined));
143
+ return Object.freeze({ PI_ACP_PI_COMMAND: await writePiFile(options.stateDir, "wrapper", body, PI_WRAPPER_MODE) });
144
+ }
145
+ /**
146
+ * The environment the profile's rules add to the agent process (SPEC US-002,
147
+ * extended by US-004), the one seam every launch goes through — a new session, a
148
+ * resume and a reconnect. An agent whose entry names no policy keeps its
149
+ * `launchEnv` untouched, so its env is exactly what it was before rules existed;
150
+ * a custom agent has no entry and gets nothing. Cursor and pi read their policy
151
+ * from files under the state directory, written here before anything is spawned:
152
+ * a file that cannot be written refuses the open (policy-files.ts). The caller
153
+ * spreads this over its own env, so neither the caller nor a model can weaken the
154
+ * enforcement value.
155
+ */
156
+ export async function policyLaunchEnv(profile, options) {
157
+ const plan = options.shellSandboxPlan;
158
+ if (plan !== undefined) {
159
+ await writeStateFile(options.stateDir, relative(options.stateDir, plan.policyFile), plan.policyContent, 0o600);
160
+ }
161
+ const entry = options.entry;
162
+ if (!isReadOnlyProfile(profile))
163
+ return launchEnvFor(profile, entry);
164
+ switch (entry?.readOnly?.policy) {
165
+ case "opencode":
166
+ if (profile === "review" && plan?.agent === "opencode") {
167
+ return opencodeSandboxEnv(plan, opencodePermissionConfig(profile, options.rules), options.env);
168
+ }
169
+ return Object.freeze({ OPENCODE_CONFIG_CONTENT: opencodePermissionConfig(profile, options.rules) });
170
+ case "cursor": {
171
+ const configDir = await writeCursorPolicy(options.stateDir, cursorCliConfig(profile, options.rules));
172
+ if (profile === "review" && plan?.agent === "cursor")
173
+ return cursorSandboxEnv(plan, configDir);
174
+ return Object.freeze({ CURSOR_CONFIG_DIR: configDir });
175
+ }
176
+ case "pi":
177
+ return piLaunchEnv(options, profile);
178
+ default:
179
+ return launchEnvFor(profile, entry);
180
+ }
181
+ }