@nathapp/nax-agent-acp 0.90.1 → 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.
- package/CHANGELOG.md +25 -0
- package/README.md +3 -1
- package/dist/client/backend.js +14 -1
- package/dist/client/capabilities.d.ts +15 -2
- package/dist/client/capabilities.js +22 -3
- package/dist/client/cursor-sandbox.d.ts +5 -0
- package/dist/client/cursor-sandbox.js +60 -0
- package/dist/client/errors.d.ts +6 -0
- package/dist/client/errors.js +9 -0
- package/dist/client/events.d.ts +9 -0
- package/dist/client/events.js +29 -3
- package/dist/client/open.d.ts +2 -0
- package/dist/client/open.js +10 -2
- package/dist/client/opencode-sandbox.d.ts +15 -0
- package/dist/client/opencode-sandbox.js +94 -0
- package/dist/client/options.d.ts +23 -0
- package/dist/client/options.js +21 -0
- package/dist/client/permissions.d.ts +12 -0
- package/dist/client/permissions.js +35 -1
- package/dist/client/pi-sandbox.d.ts +2 -0
- package/dist/client/pi-sandbox.js +22 -0
- package/dist/client/policy-files.d.ts +6 -2
- package/dist/client/policy-files.js +13 -5
- package/dist/client/registry.d.ts +7 -0
- package/dist/client/registry.js +7 -1
- package/dist/client/rule-policy.d.ts +3 -14
- package/dist/client/rule-policy.js +50 -30
- package/dist/client/shell-rules.d.ts +4 -0
- package/dist/client/shell-rules.js +11 -1
- package/dist/client/shell-sandbox.d.ts +38 -0
- package/dist/client/shell-sandbox.js +107 -0
- package/dist/client/startup-banner.d.ts +1 -0
- package/dist/client/startup-banner.js +16 -0
- package/dist/client/turn.js +4 -3
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -3,6 +3,31 @@
|
|
|
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.2] - 2026-10-18
|
|
7
|
+
|
|
8
|
+
- Shell sandbox for opencode, Cursor and pi under `review` (nax#2589). With the new
|
|
9
|
+
`shellSandbox` option and a session sandbox policy, every shell command those agents run
|
|
10
|
+
is rewritten into `<runtime> <runner> -- <policy file> <command>` and allowed with
|
|
11
|
+
`REVIEW_EXECUTE_REASON`, as for Claude. The rewrite happens through a nax-written pi
|
|
12
|
+
extension that wraps `bash` at spawn, an opencode V2 plugin (opencode runs with
|
|
13
|
+
`OPENCODE_DISABLE_PROJECT_CONFIG=1`, and nax carries the repo's `AGENTS.md` into its config
|
|
14
|
+
dir), and a Cursor `preToolUse` hook under a nax-owned `HOME`, where nax also verifies the
|
|
15
|
+
exact wrapper. `Bash` deny and ask rules still reject a matching command. An unavailable
|
|
16
|
+
sandbox keeps the previous behaviour. Known limitations (documented in the permissions
|
|
17
|
+
guide): extensions, plugins or hooks that run after nax's can rewrite a command, and only
|
|
18
|
+
shell commands are sandboxed.
|
|
19
|
+
- Cursor under `review` runs in its `agent` mode when the caller has a `Bash` allow rule,
|
|
20
|
+
instead of `ask`, whose prompt made the model refuse to try any shell command, so the
|
|
21
|
+
operator's allowed commands never reached nax. Writes stay denied by the isolated
|
|
22
|
+
`cli-config.json`, and nax still decides every shell request (nax#2592). In `agent` mode the
|
|
23
|
+
model does try to write, so a repository `.cursor/cli.json` that allows writes (already a known,
|
|
24
|
+
documented override) now lets them land.
|
|
25
|
+
- A turn that ends `end_turn` with no reply text, thought or tool call and no tokens now
|
|
26
|
+
ends `errored` with `ACP_EMPTY_TURN`, instead of `completed` with an empty answer. pi-acp
|
|
27
|
+
ends a turn this way when pi's model call fails at the provider (nax#2591).
|
|
28
|
+
- pi-acp's startup banner (`_meta.piAcp.startupInfo` on `session/new`) is no longer part of
|
|
29
|
+
the first turn's output or text deltas (nax#2591).
|
|
30
|
+
|
|
6
31
|
## [0.90.1] - 2026-10-17
|
|
7
32
|
|
|
8
33
|
- No changes in this package. Released in lockstep with the other nax packages.
|
package/README.md
CHANGED
|
@@ -31,7 +31,9 @@ What to know:
|
|
|
31
31
|
`inheritEnv: true` hands it your whole environment instead, credentials included.
|
|
32
32
|
- **Instructions** are prepended to the first prompt only; ACP has no system prompt.
|
|
33
33
|
- **Stop reasons.** A turn that stops for anything but `end_turn` ends `errored` with
|
|
34
|
-
an `ACP_STOP_*` code (`ACP_STOP_CODES`).
|
|
34
|
+
an `ACP_STOP_*` code (`ACP_STOP_CODES`). An `end_turn` with no reply text, thought or
|
|
35
|
+
tool call and no tokens ends `errored` with `ACP_EMPTY_TURN`: an agent that swallows
|
|
36
|
+
its model call's failure ends a turn this way (pi-acp on a provider error).
|
|
35
37
|
- **Model and effort.** `model` and `effort` are set through `session/set_config_option`,
|
|
36
38
|
after the profile's mode: the model only when the agent offers it (else
|
|
37
39
|
`AGENT_SESSION_CAPABILITY_UNSUPPORTED`), the effort through the agent's `thought_level`
|
package/dist/client/backend.js
CHANGED
|
@@ -31,6 +31,7 @@ import { resolveAcpOptions } from "#src/client/options";
|
|
|
31
31
|
import { decidePermission } from "#src/client/permissions";
|
|
32
32
|
import { race } from "#src/client/race";
|
|
33
33
|
import { canRestore, storedSessionOf } from "#src/client/resume";
|
|
34
|
+
import { shellSandboxPlan } from "#src/client/shell-sandbox";
|
|
34
35
|
import { createToolCalls } from "#src/client/tool-calls";
|
|
35
36
|
import { createToolHost, newToolHostToken } from "#src/client/tool-host";
|
|
36
37
|
import { runPromptTurn } from "#src/client/turn";
|
|
@@ -92,6 +93,15 @@ function routerFor(ctx, options) {
|
|
|
92
93
|
agentName: options.agentName,
|
|
93
94
|
rules: options.rules,
|
|
94
95
|
...(sandbox === undefined ? {} : { sandbox }),
|
|
96
|
+
...(options.shellSandboxPlan === undefined
|
|
97
|
+
? {}
|
|
98
|
+
: {
|
|
99
|
+
shellSandbox: {
|
|
100
|
+
prefix: options.shellSandboxPlan.prefix,
|
|
101
|
+
verify: options.shellSandboxPlan.verify,
|
|
102
|
+
onUnwrapped: options.shellSandboxPlan.onUnwrapped,
|
|
103
|
+
},
|
|
104
|
+
}),
|
|
95
105
|
};
|
|
96
106
|
return createInboundRouter((request, signal) => decidePermission(request, { ...base, signal }), (request, signal) => answerElicitation(request, { ...base, signal }));
|
|
97
107
|
}
|
|
@@ -99,7 +109,9 @@ function routerFor(ctx, options) {
|
|
|
99
109
|
async function connect(base, ctx, restore, retiredTokens) {
|
|
100
110
|
const token = ctx.tools.length > 0 ? newToolHostToken() : undefined;
|
|
101
111
|
const tokens = token === undefined ? retiredTokens : [...retiredTokens, token];
|
|
102
|
-
const
|
|
112
|
+
const tokenOptions = withTokens(base, tokens);
|
|
113
|
+
const plan = await shellSandboxPlan(ctx.profile, tokenOptions, ctx.sandbox, ctx.workdir);
|
|
114
|
+
const options = Object.freeze({ ...tokenOptions, ...(plan === undefined ? {} : { shellSandboxPlan: plan }) });
|
|
103
115
|
const gone = new AbortController();
|
|
104
116
|
const router = routerFor(ctx, options);
|
|
105
117
|
const host = toolHostFor(ctx, router, options.secrets, token);
|
|
@@ -220,6 +232,7 @@ async function sendTurn(s, prompt, opts) {
|
|
|
220
232
|
secrets: live.options.secrets,
|
|
221
233
|
meter: live.meter,
|
|
222
234
|
...(onReceipt === undefined ? {} : { onReceipt }),
|
|
235
|
+
...(live.acp.startupBanner === undefined ? {} : { startupBanner: live.acp.startupBanner }),
|
|
223
236
|
});
|
|
224
237
|
const release = live.router.attach(live.acp.agentSessionId, collector, AbortSignal.any([signal, live.gone.signal]));
|
|
225
238
|
try {
|
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
import type { InitializeResponse, SessionConfigOption } from "@agentclientprotocol/sdk";
|
|
9
9
|
import type { AgentSessionProfile } from "@nathapp/nax-agent";
|
|
10
10
|
import type { AgentRegistryEntry, ModeSetting, ReadOnlyEnforcement } from "#src/client/registry";
|
|
11
|
+
import type { AcpPermissionRules } from "#src/client/rule-policy";
|
|
11
12
|
export type CapabilityRecord = {
|
|
12
13
|
readonly protocolVersion: number;
|
|
13
14
|
readonly agentName?: string;
|
|
@@ -57,8 +58,20 @@ export declare const EFFORT_FALLBACK_IDS: Readonly<Record<string, string>>;
|
|
|
57
58
|
export declare function effortOptionId(options: readonly SessionConfigOption[], agentName: string, effort: string): string | undefined;
|
|
58
59
|
/** The read-only enforcement a profile uses: the entry's for none/read, none otherwise. */
|
|
59
60
|
export declare function readOnlyFor(profile: AgentSessionProfile, entry: AgentRegistryEntry | undefined): ReadOnlyEnforcement | undefined;
|
|
60
|
-
/**
|
|
61
|
-
|
|
61
|
+
/**
|
|
62
|
+
* Whether nax decides this profile's shell requests by the operator's Bash rules:
|
|
63
|
+
* only `review` has a shell tool to police, and only when a Bash allow rule could
|
|
64
|
+
* ever allow a command (an unconditional allow is not needed: each command is asked
|
|
65
|
+
* of nax, shell-rules.ts). `read` keeps no shell tool, `none` no tool. It gates pi's
|
|
66
|
+
* shell gate (rule-policy.ts) and Cursor's review mode (nax#2372, nax#2592).
|
|
67
|
+
*/
|
|
68
|
+
export declare function reviewDecidesShell(profile: AgentSessionProfile, rules: AcpPermissionRules | undefined): boolean;
|
|
69
|
+
/**
|
|
70
|
+
* The mode a profile selects (§6.4 layer 1): the read-only entry's for none/read/review,
|
|
71
|
+
* the default mode otherwise. Under `review` with a Bash allow rule, an entry's
|
|
72
|
+
* `reviewShellMode` wins (nax#2592).
|
|
73
|
+
*/
|
|
74
|
+
export declare function modeFor(profile: AgentSessionProfile, entry: AgentRegistryEntry | undefined, rules?: AcpPermissionRules, shellSandboxed?: boolean): ModeSetting | undefined;
|
|
62
75
|
/**
|
|
63
76
|
* The environment a profile adds to the agent process (nax#2372): opencode's
|
|
64
77
|
* permission policy for none/read/review, `{}` for every other profile and for any
|
|
@@ -103,9 +103,28 @@ export function effortOptionId(options, agentName, effort) {
|
|
|
103
103
|
export function readOnlyFor(profile, entry) {
|
|
104
104
|
return isReadOnlyProfile(profile) ? entry?.readOnly : undefined;
|
|
105
105
|
}
|
|
106
|
-
/**
|
|
107
|
-
|
|
108
|
-
|
|
106
|
+
/**
|
|
107
|
+
* Whether nax decides this profile's shell requests by the operator's Bash rules:
|
|
108
|
+
* only `review` has a shell tool to police, and only when a Bash allow rule could
|
|
109
|
+
* ever allow a command (an unconditional allow is not needed: each command is asked
|
|
110
|
+
* of nax, shell-rules.ts). `read` keeps no shell tool, `none` no tool. It gates pi's
|
|
111
|
+
* shell gate (rule-policy.ts) and Cursor's review mode (nax#2372, nax#2592).
|
|
112
|
+
*/
|
|
113
|
+
export function reviewDecidesShell(profile, rules) {
|
|
114
|
+
return profile === "review" && (rules?.allow.some((rule) => rule.tool === "Bash") ?? false);
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* The mode a profile selects (§6.4 layer 1): the read-only entry's for none/read/review,
|
|
118
|
+
* the default mode otherwise. Under `review` with a Bash allow rule, an entry's
|
|
119
|
+
* `reviewShellMode` wins (nax#2592).
|
|
120
|
+
*/
|
|
121
|
+
export function modeFor(profile, entry, rules, shellSandboxed) {
|
|
122
|
+
if (!isReadOnlyProfile(profile))
|
|
123
|
+
return entry?.defaultMode;
|
|
124
|
+
const shellMode = reviewDecidesShell(profile, rules) || (profile === "review" && shellSandboxed === true)
|
|
125
|
+
? entry?.readOnly?.reviewShellMode
|
|
126
|
+
: undefined;
|
|
127
|
+
return shellMode ?? entry?.readOnly?.mode;
|
|
109
128
|
}
|
|
110
129
|
/**
|
|
111
130
|
* The environment a profile adds to the agent process (nax#2372): opencode's
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { type ShellSandboxPlan } from "#src/client/shell-sandbox";
|
|
2
|
+
/** A malformed hook event fails closed; non-command tools need no rewrite. */
|
|
3
|
+
export declare function cursorSandboxHookSource(prefix: string): string;
|
|
4
|
+
/** Every open rewrites both private files through the shared atomic writer. */
|
|
5
|
+
export declare function cursorSandboxEnv(plan: ShellSandboxPlan, cursorConfigDir: string): Promise<Readonly<Record<string, string>>>;
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/** Cursor reads hooks only beneath HOME; isolate that HOME, not the command's home. */
|
|
2
|
+
import { dirname, join } from "node:path";
|
|
3
|
+
import { backendUnavailable } from "#src/client/errors";
|
|
4
|
+
import { digest, writeStateFile } from "#src/client/policy-files";
|
|
5
|
+
import { _shellSandboxDeps, sandboxWrapSnippet, shellQuote } from "#src/client/shell-sandbox";
|
|
6
|
+
/** A malformed hook event fails closed; non-command tools need no rewrite. */
|
|
7
|
+
export function cursorSandboxHookSource(prefix) {
|
|
8
|
+
return `${sandboxWrapSnippet(prefix)}
|
|
9
|
+
try {
|
|
10
|
+
let input = "";
|
|
11
|
+
process.stdin.setEncoding("utf8");
|
|
12
|
+
for await (const chunk of process.stdin) input += chunk;
|
|
13
|
+
const event = JSON.parse(input);
|
|
14
|
+
const toolInput = event?.tool_input;
|
|
15
|
+
const result = typeof toolInput?.command === "string"
|
|
16
|
+
? { updated_input: { ...toolInput, command: naxSandboxWrap(toolInput.command) } }
|
|
17
|
+
: {};
|
|
18
|
+
process.stdout.write(JSON.stringify(result));
|
|
19
|
+
} catch {
|
|
20
|
+
process.exitCode = 1;
|
|
21
|
+
}
|
|
22
|
+
`;
|
|
23
|
+
}
|
|
24
|
+
async function linkKeychains(home, realHome) {
|
|
25
|
+
const path = join(home, "Library", "Keychains");
|
|
26
|
+
const target = join(realHome, "Library", "Keychains");
|
|
27
|
+
try {
|
|
28
|
+
await _shellSandboxDeps.mkdir(dirname(path), { recursive: true, mode: 0o700 });
|
|
29
|
+
try {
|
|
30
|
+
await _shellSandboxDeps.symlink(target, path);
|
|
31
|
+
}
|
|
32
|
+
catch (cause) {
|
|
33
|
+
// Reuse and concurrent opens are safe only for this exact link target.
|
|
34
|
+
if (!(cause instanceof Error && "code" in cause && cause.code === "EEXIST"))
|
|
35
|
+
throw cause;
|
|
36
|
+
if ((await _shellSandboxDeps.readlink(path)) !== target)
|
|
37
|
+
throw cause;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
catch (cause) {
|
|
41
|
+
throw backendUnavailable(`the Cursor keychain link "${path}" could not be created`, { path, cause });
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
/** Every open rewrites both private files through the shared atomic writer. */
|
|
45
|
+
export async function cursorSandboxEnv(plan, cursorConfigDir) {
|
|
46
|
+
// Planning owns the invariant <stateDir>/sandbox/policy-<digest>.json.
|
|
47
|
+
const stateDir = dirname(dirname(plan.policyFile));
|
|
48
|
+
const source = cursorSandboxHookSource(plan.prefix);
|
|
49
|
+
const hookFile = await writeStateFile(stateDir, join("cursor", `sandbox-hook-${digest(source)}.mjs`), source, 0o600);
|
|
50
|
+
const content = JSON.stringify({
|
|
51
|
+
version: 1,
|
|
52
|
+
hooks: { preToolUse: [{ command: `${shellQuote(plan.runtime)} ${shellQuote(hookFile)}`, failClosed: true }] },
|
|
53
|
+
});
|
|
54
|
+
const relativeHome = join("cursor-home", digest(content));
|
|
55
|
+
await writeStateFile(stateDir, join(relativeHome, ".cursor", "hooks.json"), content, 0o600);
|
|
56
|
+
const home = join(stateDir, relativeHome);
|
|
57
|
+
if (_shellSandboxDeps.platform() === "darwin")
|
|
58
|
+
await linkKeychains(home, plan.home);
|
|
59
|
+
return Object.freeze({ CURSOR_CONFIG_DIR: cursorConfigDir, HOME: home });
|
|
60
|
+
}
|
package/dist/client/errors.d.ts
CHANGED
|
@@ -42,3 +42,9 @@ export declare function rateLimitOf(data: unknown): {
|
|
|
42
42
|
export declare function promptRequestError(err: RequestError, secrets: readonly string[]): NaxError;
|
|
43
43
|
/** A stop reason other than end_turn. Own keys only: "__proto__" or "toString" is unknown, not a code. */
|
|
44
44
|
export declare function stopReasonError(stopReason: string): NaxError;
|
|
45
|
+
/**
|
|
46
|
+
* nax#2591: an end_turn that showed no work (no reply text, thought or tool call)
|
|
47
|
+
* and reported no tokens. An agent that swallows its model call's failure ends the
|
|
48
|
+
* turn this way (pi-acp on a provider 402), so it is a failure, not an empty answer.
|
|
49
|
+
*/
|
|
50
|
+
export declare function emptyTurnError(): NaxError;
|
package/dist/client/errors.js
CHANGED
|
@@ -107,3 +107,12 @@ export function stopReasonError(stopReason) {
|
|
|
107
107
|
const shown = agentTextExcerpt(stopReason, []).slice(0, 64);
|
|
108
108
|
return new NaxError(`The ACP agent ended the turn with an unknown stop reason "${shown}"`, "AGENT_SESSION_TURN_FAILED", { stage: "acp", stopReason: shown });
|
|
109
109
|
}
|
|
110
|
+
/**
|
|
111
|
+
* nax#2591: an end_turn that showed no work (no reply text, thought or tool call)
|
|
112
|
+
* and reported no tokens. An agent that swallows its model call's failure ends the
|
|
113
|
+
* turn this way (pi-acp on a provider 402), so it is a failure, not an empty answer.
|
|
114
|
+
*/
|
|
115
|
+
export function emptyTurnError() {
|
|
116
|
+
return new NaxError("The ACP agent ended the turn without a reply, a tool call or any tokens; its model call likely failed " +
|
|
117
|
+
"(check the agent's provider, credit and model)", "ACP_EMPTY_TURN", { stage: "acp", stopReason: "end_turn" });
|
|
118
|
+
}
|
package/dist/client/events.d.ts
CHANGED
|
@@ -11,6 +11,11 @@
|
|
|
11
11
|
* turn-content update or the settle, so the backend knows its instructions arrived
|
|
12
12
|
* (#2364). Nothing is emitted after finish(). The
|
|
13
13
|
* sink is the facade's; a throw from it is contained.
|
|
14
|
+
*
|
|
15
|
+
* nax#2591: the agent's startup banner (pi-acp's `startupInfo`, sent as one message
|
|
16
|
+
* chunk that lands in the first turn) is dropped whole: it is not the agent's reply
|
|
17
|
+
* and does not show the agent read the prompt. worked() tells whether the turn showed
|
|
18
|
+
* any work: a non-empty reply or thought chunk (any non-text content counts), or a tool call.
|
|
14
19
|
*/
|
|
15
20
|
import type { PromptResponse, SessionUpdate } from "@agentclientprotocol/sdk";
|
|
16
21
|
import type { TurnEventSink } from "@nathapp/nax-agent";
|
|
@@ -22,6 +27,8 @@ export interface CollectorOptions {
|
|
|
22
27
|
readonly meter?: CostMeter;
|
|
23
28
|
/** Called once, when the turn first shows the agent has the prompt: a turn-content update or the prompt's response (#2364). */
|
|
24
29
|
readonly onReceipt?: () => void;
|
|
30
|
+
/** The session's startup banner, from session/new (nax#2591): a message chunk of exactly this text is dropped. */
|
|
31
|
+
readonly startupBanner?: string;
|
|
25
32
|
}
|
|
26
33
|
export interface TurnCollector {
|
|
27
34
|
onUpdate(update: SessionUpdate): void;
|
|
@@ -37,5 +44,7 @@ export interface TurnCollector {
|
|
|
37
44
|
noteDenial(): void;
|
|
38
45
|
/** Denials answered so far in this turn. */
|
|
39
46
|
denials(): number;
|
|
47
|
+
/** The turn showed work: reply text, a thought or a tool call (nax#2591). */
|
|
48
|
+
worked(): boolean;
|
|
40
49
|
}
|
|
41
50
|
export declare function createTurnCollector(emit: TurnEventSink | undefined, options?: CollectorOptions): TurnCollector;
|
package/dist/client/events.js
CHANGED
|
@@ -30,6 +30,26 @@ function containedSink(emit) {
|
|
|
30
30
|
}
|
|
31
31
|
};
|
|
32
32
|
}
|
|
33
|
+
/** Update kinds that show the agent worked on the prompt (nax#2591); usage and plans alone do not. */
|
|
34
|
+
const WORK_KINDS = new Set([
|
|
35
|
+
"agent_message_chunk",
|
|
36
|
+
"agent_thought_chunk",
|
|
37
|
+
"tool_call",
|
|
38
|
+
"tool_call_update",
|
|
39
|
+
]);
|
|
40
|
+
function isBanner(update, banner) {
|
|
41
|
+
return (banner !== undefined &&
|
|
42
|
+
update.sessionUpdate === "agent_message_chunk" &&
|
|
43
|
+
update.content.type === "text" &&
|
|
44
|
+
update.content.text === banner);
|
|
45
|
+
}
|
|
46
|
+
function showsWork(update) {
|
|
47
|
+
if (!WORK_KINDS.has(update.sessionUpdate))
|
|
48
|
+
return false;
|
|
49
|
+
if (update.sessionUpdate !== "agent_message_chunk" && update.sessionUpdate !== "agent_thought_chunk")
|
|
50
|
+
return true;
|
|
51
|
+
return update.content.type !== "text" || update.content.text !== "";
|
|
52
|
+
}
|
|
33
53
|
/**
|
|
34
54
|
* Update kinds that prove the agent is working on the prompt (#2364). An allowlist:
|
|
35
55
|
* session-level updates (commands, mode, config, session info) and replayed history
|
|
@@ -58,6 +78,7 @@ export function createTurnCollector(emit, options = {}) {
|
|
|
58
78
|
let spend;
|
|
59
79
|
let received = false;
|
|
60
80
|
let denials = 0;
|
|
81
|
+
let worked = false;
|
|
61
82
|
const receipt = () => {
|
|
62
83
|
if (received)
|
|
63
84
|
return;
|
|
@@ -101,15 +122,19 @@ export function createTurnCollector(emit, options = {}) {
|
|
|
101
122
|
};
|
|
102
123
|
return {
|
|
103
124
|
onUpdate(update) {
|
|
104
|
-
if (done)
|
|
125
|
+
if (done || isBanner(update, options.startupBanner))
|
|
105
126
|
return;
|
|
106
127
|
if (RECEIPT_KINDS.has(update.sessionUpdate))
|
|
107
128
|
receipt();
|
|
129
|
+
if (showsWork(update))
|
|
130
|
+
worked = true;
|
|
108
131
|
route(update);
|
|
109
132
|
},
|
|
110
133
|
announce(toolCall) {
|
|
111
|
-
if (
|
|
112
|
-
|
|
134
|
+
if (done)
|
|
135
|
+
return;
|
|
136
|
+
worked = true;
|
|
137
|
+
tools.announce(toolCall);
|
|
113
138
|
},
|
|
114
139
|
finish,
|
|
115
140
|
settle(response) {
|
|
@@ -126,5 +151,6 @@ export function createTurnCollector(emit, options = {}) {
|
|
|
126
151
|
denials += 1;
|
|
127
152
|
},
|
|
128
153
|
denials: () => denials,
|
|
154
|
+
worked: () => worked,
|
|
129
155
|
};
|
|
130
156
|
}
|
package/dist/client/open.d.ts
CHANGED
|
@@ -28,6 +28,8 @@ export interface OpenedAcp {
|
|
|
28
28
|
readonly cwd: string;
|
|
29
29
|
/** How a stored session was restored (§6.9); undefined for a new session. */
|
|
30
30
|
readonly restoredWith?: RestoredWith;
|
|
31
|
+
/** The startup banner session/new announced (nax#2591); turns drop it from their output. */
|
|
32
|
+
readonly startupBanner?: string;
|
|
31
33
|
}
|
|
32
34
|
/** `restore`: restore that stored agent session instead of creating one (§6.9). */
|
|
33
35
|
export declare function openAcpSession(options: ResolvedAcpOptions, ctx: BackendOpenContext, handlers: InboundHandlers, launch: LaunchFn, host?: ToolHost, restore?: Restore): Promise<OpenedAcp>;
|
package/dist/client/open.js
CHANGED
|
@@ -22,6 +22,7 @@ import { race } from "#src/client/race";
|
|
|
22
22
|
import { isUsableSessionId, restoreSession, } from "#src/client/resume";
|
|
23
23
|
import { policyLaunchEnv } from "#src/client/rule-policy";
|
|
24
24
|
import { sessionOffers } from "#src/client/session-offers";
|
|
25
|
+
import { startupBannerOf } from "#src/client/startup-banner";
|
|
25
26
|
import { cleanLabel } from "#src/client/text";
|
|
26
27
|
function chooseLaunch(options) {
|
|
27
28
|
if (options.launch.kind === "explicit")
|
|
@@ -134,13 +135,20 @@ async function establish(o) {
|
|
|
134
135
|
agentSessionId: session.agentSessionId,
|
|
135
136
|
cwd: session.cwd,
|
|
136
137
|
...(session.restoredWith === undefined ? {} : { restoredWith: session.restoredWith }),
|
|
138
|
+
...(session.startupBanner === undefined ? {} : { startupBanner: session.startupBanner }),
|
|
137
139
|
};
|
|
138
140
|
}
|
|
139
141
|
async function newSession(o, setup) {
|
|
140
142
|
const created = await step(o, "session/new", o.link.newSession({ cwd: o.ctx.workdir, ...setup }));
|
|
141
143
|
if (!isUsableSessionId(created.sessionId))
|
|
142
144
|
throw backendUnavailable("session/new returned no usable session id");
|
|
143
|
-
|
|
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
|
+
};
|
|
144
152
|
}
|
|
145
153
|
/**
|
|
146
154
|
* nax#2500: review/full sessions with an embedder sandbox; an unusable one refuses
|
|
@@ -189,7 +197,7 @@ async function applyConfig(o, sessionId, offers) {
|
|
|
189
197
|
* neither offers refuses the open.
|
|
190
198
|
*/
|
|
191
199
|
async function applyMode(o, sessionId, offers) {
|
|
192
|
-
const mode = modeFor(o.ctx.profile, o.options.entry);
|
|
200
|
+
const mode = modeFor(o.ctx.profile, o.options.entry, o.options.rules, o.options.shellSandboxPlan !== undefined);
|
|
193
201
|
if (mode === undefined)
|
|
194
202
|
return offers;
|
|
195
203
|
if (offersValue(offers.configOptions, mode.configId, mode.value)) {
|
|
@@ -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
|
+
}
|
package/dist/client/options.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { type AcpAgentName, type AgentRegistryEntry, type LaunchCandidate } from "#src/client/registry";
|
|
2
2
|
import { type AcpPermissionRules, type AcpRule } from "#src/client/rule-policy";
|
|
3
|
+
import type { ShellSandboxPlan } from "#src/client/shell-sandbox";
|
|
3
4
|
export declare const DEFAULT_CANCEL_GRACE_MS = 10000;
|
|
4
5
|
export declare const DEFAULT_INITIALIZE_TIMEOUT_MS = 60000;
|
|
5
6
|
/** Where rule-policy files go when the caller names no directory (rule-policy.ts, US-004 writes them). */
|
|
@@ -34,6 +35,20 @@ export interface AcpBackendOptions {
|
|
|
34
35
|
};
|
|
35
36
|
/** Where an agent's rule-policy files are written; absolute. Defaults to DEFAULT_STATE_DIR. */
|
|
36
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
|
+
};
|
|
37
52
|
/** Overrides the registry's launch command (a bare name or an absolute path). */
|
|
38
53
|
readonly command?: string;
|
|
39
54
|
readonly args?: readonly string[];
|
|
@@ -62,6 +77,14 @@ export interface ResolvedAcpOptions {
|
|
|
62
77
|
readonly rules: AcpPermissionRules;
|
|
63
78
|
/** The directory an agent's rule-policy files go in (absolute). */
|
|
64
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;
|
|
65
88
|
readonly env: Readonly<Record<string, string>>;
|
|
66
89
|
/** Values redacted from every agent excerpt (D-g). */
|
|
67
90
|
readonly secrets: readonly string[];
|
package/dist/client/options.js
CHANGED
|
@@ -48,6 +48,15 @@ const SCHEMA = z
|
|
|
48
48
|
inheritEnv: z.boolean().optional(),
|
|
49
49
|
rules: rulesSchema.optional(),
|
|
50
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(),
|
|
51
60
|
command: command.optional(),
|
|
52
61
|
args: z.array(plain).optional(),
|
|
53
62
|
cancelGraceMs: z.number().int().positive().max(600_000).optional(),
|
|
@@ -78,6 +87,17 @@ function freezeRules(input) {
|
|
|
78
87
|
ask: Object.freeze((input.ask ?? []).map(freezeRule)),
|
|
79
88
|
});
|
|
80
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
|
+
}
|
|
81
101
|
function launchOf(data, entry) {
|
|
82
102
|
if (data.command !== undefined)
|
|
83
103
|
return { kind: "explicit", candidate: { command: data.command, args: data.args ?? [] } };
|
|
@@ -110,6 +130,7 @@ function resolved(data, source, onProcess) {
|
|
|
110
130
|
effort: data.effort,
|
|
111
131
|
rules: freezeRules(data.rules),
|
|
112
132
|
stateDir: data.stateDir ?? DEFAULT_STATE_DIR,
|
|
133
|
+
shellSandbox: freezeShellSandbox(data.shellSandbox),
|
|
113
134
|
env: Object.freeze(env),
|
|
114
135
|
secrets: Object.freeze([...secretValues(env)]),
|
|
115
136
|
cancelGraceMs: data.cancelGraceMs ?? DEFAULT_CANCEL_GRACE_MS,
|
|
@@ -16,6 +16,7 @@
|
|
|
16
16
|
import type { RequestPermissionRequest, RequestPermissionResponse } from "@agentclientprotocol/sdk";
|
|
17
17
|
import type { AgentSessionProfile, SandboxPolicy, SessionAskPort } from "@nathapp/nax-agent";
|
|
18
18
|
import { type AcpPermissionRules } from "#src/client/rule-policy";
|
|
19
|
+
import { type ToolCallDisplay } from "#src/client/tool-display";
|
|
19
20
|
export declare const NO_ALLOW_ONCE_REASON = "agent offered no allow-once option";
|
|
20
21
|
export declare const UNSHOWABLE_REASON = "the request could not be shown safely";
|
|
21
22
|
export declare const ASK_REASON = "the ACP agent asks permission";
|
|
@@ -23,6 +24,8 @@ export declare const FULL_REASON = "profile \"full\" allows every permission req
|
|
|
23
24
|
export declare const UNKNOWN_PROFILE_REASON = "unknown profile";
|
|
24
25
|
export declare const REVIEW_EXECUTE_REASON = "profile \"review\" allows commands";
|
|
25
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";
|
|
26
29
|
export declare const NETWORK_OPEN_REASON = "the sandbox network is open";
|
|
27
30
|
export declare const NETWORK_LISTED_REASON = "the sandbox network is an allow-list";
|
|
28
31
|
export declare function isNetworkRequest(toolCall: unknown): boolean;
|
|
@@ -44,6 +47,11 @@ export interface PermissionContext {
|
|
|
44
47
|
readonly agentName?: string;
|
|
45
48
|
/** nax's rules for this stage (US-003). Absent: no Bash rule allows anything. */
|
|
46
49
|
readonly rules?: AcpPermissionRules;
|
|
50
|
+
readonly shellSandbox?: {
|
|
51
|
+
prefix: string;
|
|
52
|
+
verify: boolean;
|
|
53
|
+
onUnwrapped: "rules" | "deny";
|
|
54
|
+
};
|
|
47
55
|
}
|
|
48
56
|
export interface OfferedOptions {
|
|
49
57
|
readonly allowOnce?: string;
|
|
@@ -56,4 +64,8 @@ export declare function isDenial(request: RequestPermissionRequest, response: Re
|
|
|
56
64
|
export declare function rejectWith(offered: OfferedOptions): RequestPermissionResponse;
|
|
57
65
|
/** The answer to a request outside the running turn (spec §6.3): a deny, never an event. */
|
|
58
66
|
export declare function rejectLocally(request: RequestPermissionRequest): RequestPermissionResponse;
|
|
67
|
+
type AutoDecide = (reason: string, decision: "allow" | "deny") => void;
|
|
59
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,6 +1,7 @@
|
|
|
1
1
|
import { editTargets, firstOutsidePolicy, OUTSIDE_WRITE_ROOTS_REASON, WRITE_KINDS } from "#src/client/edit-targets";
|
|
2
2
|
import { NO_RULES } from "#src/client/rule-policy";
|
|
3
|
-
import { SHELL_RULE_REASON, shellCommandOf, shellRuleVerdict } from "#src/client/shell-rules";
|
|
3
|
+
import { SHELL_RULE_REASON, shellCommandOf, shellRuleBlocks, shellRuleVerdict } from "#src/client/shell-rules";
|
|
4
|
+
import { isSandboxWrapped } from "#src/client/shell-sandbox";
|
|
4
5
|
import { isRecord } from "#src/client/text";
|
|
5
6
|
import { describeToolCall } from "#src/client/tool-display";
|
|
6
7
|
export const NO_ALLOW_ONCE_REASON = "agent offered no allow-once option";
|
|
@@ -10,6 +11,8 @@ export const FULL_REASON = 'profile "full" allows every permission request';
|
|
|
10
11
|
export const UNKNOWN_PROFILE_REASON = "unknown profile";
|
|
11
12
|
export const REVIEW_EXECUTE_REASON = 'profile "review" allows commands';
|
|
12
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';
|
|
13
16
|
export const NETWORK_OPEN_REASON = "the sandbox network is open";
|
|
14
17
|
export const NETWORK_LISTED_REASON = "the sandbox network is an allow-list";
|
|
15
18
|
/** claude-agent-acp 0.85.1 surfaces the SDK's sandbox network callback as a tool call titled with its tool name. */
|
|
@@ -105,6 +108,8 @@ export async function decidePermission(request, ctx) {
|
|
|
105
108
|
* deny — and everything that is not a command stays read-only.
|
|
106
109
|
*/
|
|
107
110
|
function decideReview(request, display, offered, auto, ctx) {
|
|
111
|
+
if (ctx.shellSandbox !== undefined)
|
|
112
|
+
return decideSandboxedShell(request, display, offered, auto, ctx);
|
|
108
113
|
if (ctx.sandbox !== undefined) {
|
|
109
114
|
if (display.tool !== "execute") {
|
|
110
115
|
auto(readOnlyReason(ctx.profile), "deny");
|
|
@@ -130,6 +135,35 @@ function decideReview(request, display, offered, auto, ctx) {
|
|
|
130
135
|
auto(SHELL_RULE_REASON, "allow");
|
|
131
136
|
return selected(offered.allowOnce);
|
|
132
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
|
+
}
|
|
133
167
|
/**
|
|
134
168
|
* ACP kinds exempt from the R4 path check (nax#2500 R5/R8): they do not write a path
|
|
135
169
|
* the sandbox has to police. execute is the Bash sandbox's job. Every other kind,
|
|
@@ -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
|
+
}
|
|
@@ -9,8 +9,12 @@ export interface PolicyFileDeps {
|
|
|
9
9
|
rename(from: string, to: string): Promise<unknown>;
|
|
10
10
|
}
|
|
11
11
|
export declare const _policyFilesDeps: PolicyFileDeps;
|
|
12
|
-
/**
|
|
13
|
-
export type PiPolicyFile = "shell-gate" | "wrapper";
|
|
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>;
|
|
14
18
|
/** Cursor's isolated config: `<stateDir>/cursor/<h>/cli-config.json`. Returns the directory to point CURSOR_CONFIG_DIR at. */
|
|
15
19
|
export declare function writeCursorPolicy(stateDir: string, content: string): Promise<string>;
|
|
16
20
|
/** pi's `<stateDir>/pi/<name>-<h><ext>`; returns the file path. */
|
|
@@ -17,12 +17,16 @@ import { chmod, mkdir, rename, writeFile } from "node:fs/promises";
|
|
|
17
17
|
import { basename, dirname, join } from "node:path";
|
|
18
18
|
import { backendUnavailable } from "#src/client/errors";
|
|
19
19
|
export const _policyFilesDeps = { mkdir, writeFile, chmod, rename };
|
|
20
|
-
const PI_EXTENSIONS = Object.freeze({
|
|
20
|
+
const PI_EXTENSIONS = Object.freeze({
|
|
21
|
+
"shell-gate": ".ts",
|
|
22
|
+
wrapper: ".sh",
|
|
23
|
+
"sandbox-gate": ".ts",
|
|
24
|
+
});
|
|
21
25
|
/** Nothing here is readable by another user: the directory is ours, the policy files are ours. */
|
|
22
26
|
const DIR_MODE = 0o700;
|
|
23
27
|
const CURSOR_CONFIG_MODE = 0o600;
|
|
24
28
|
/** The content-addressed part of a policy path. */
|
|
25
|
-
function digest(content) {
|
|
29
|
+
export function digest(content) {
|
|
26
30
|
return createHash("sha256").update(content).digest("hex").slice(0, 16);
|
|
27
31
|
}
|
|
28
32
|
function messageOf(err) {
|
|
@@ -51,6 +55,12 @@ async function writeAtomic(target, content, mode) {
|
|
|
51
55
|
});
|
|
52
56
|
}
|
|
53
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
|
+
}
|
|
54
64
|
/** Cursor's isolated config: `<stateDir>/cursor/<h>/cli-config.json`. Returns the directory to point CURSOR_CONFIG_DIR at. */
|
|
55
65
|
export async function writeCursorPolicy(stateDir, content) {
|
|
56
66
|
const dir = join(stateDir, "cursor", digest(content));
|
|
@@ -59,7 +69,5 @@ export async function writeCursorPolicy(stateDir, content) {
|
|
|
59
69
|
}
|
|
60
70
|
/** pi's `<stateDir>/pi/<name>-<h><ext>`; returns the file path. */
|
|
61
71
|
export async function writePiFile(stateDir, name, content, mode) {
|
|
62
|
-
|
|
63
|
-
await writeAtomic(target, content, mode);
|
|
64
|
-
return target;
|
|
72
|
+
return writeStateFile(stateDir, join("pi", `${name}-${digest(content)}${PI_EXTENSIONS[name]}`), content, mode);
|
|
65
73
|
}
|
|
@@ -27,6 +27,13 @@ export interface ModeSetting {
|
|
|
27
27
|
export interface ReadOnlyEnforcement {
|
|
28
28
|
/** The mode set for none/read/review; undefined means nax sets no mode for them. */
|
|
29
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;
|
|
30
37
|
/** Agent tools removed from the session under none/read/review. */
|
|
31
38
|
readonly disallowedTools: readonly string[];
|
|
32
39
|
/** Extra agent options under none/read/review, merged into the pre-approval channel's options. */
|
package/dist/client/registry.js
CHANGED
|
@@ -20,6 +20,9 @@ function freezeReadOnly(readOnly) {
|
|
|
20
20
|
const mode = readOnly.mode === undefined ? undefined : Object.freeze({ ...readOnly.mode });
|
|
21
21
|
return Object.freeze({
|
|
22
22
|
mode,
|
|
23
|
+
...(readOnly.reviewShellMode === undefined
|
|
24
|
+
? {}
|
|
25
|
+
: { reviewShellMode: Object.freeze({ ...readOnly.reviewShellMode }) }),
|
|
23
26
|
disallowedTools: Object.freeze([...readOnly.disallowedTools]),
|
|
24
27
|
sessionOptions: Object.freeze(Object.fromEntries(options)),
|
|
25
28
|
launchEnv: Object.freeze(Object.fromEntries(launchEnv)),
|
|
@@ -90,12 +93,15 @@ const REGISTRY = new Map([
|
|
|
90
93
|
// write through, mode `plan` let the model switch back to `agent` and write), so `ask`
|
|
91
94
|
// only tells the model it is read-only; the real enforcement is its permission config
|
|
92
95
|
// (US-004: an isolated cli-config.json, pointed at by CURSOR_CONFIG_DIR). No plan mode
|
|
93
|
-
// is ever used here.
|
|
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).
|
|
94
99
|
[
|
|
95
100
|
"cursor",
|
|
96
101
|
entry("cursor", [local("cursor-agent", "acp")], ["CURSOR_API_KEY"], {
|
|
97
102
|
readOnly: {
|
|
98
103
|
mode: { configId: "mode", value: "ask" },
|
|
104
|
+
reviewShellMode: { configId: "mode", value: "agent" },
|
|
99
105
|
disallowedTools: [],
|
|
100
106
|
sessionOptions: {},
|
|
101
107
|
launchEnv: {},
|
|
@@ -1,16 +1,3 @@
|
|
|
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
1
|
import type { AgentSessionProfile } from "@nathapp/nax-agent";
|
|
15
2
|
import type { ResolvedAcpOptions } from "#src/client/options";
|
|
16
3
|
export interface AcpRule {
|
|
@@ -51,7 +38,9 @@ export declare function cursorCliConfig(profile: "none" | "read" | "review", rul
|
|
|
51
38
|
* is appended after the read tools and the gate extension is loaded first, so
|
|
52
39
|
* every command goes through the nax shell gate.
|
|
53
40
|
*/
|
|
54
|
-
export declare function piToolArgs(profile: "none" | "read" | "review", rules: AcpPermissionRules, gatePath: string
|
|
41
|
+
export declare function piToolArgs(profile: "none" | "read" | "review", rules: AcpPermissionRules, gatePath: string, sandbox?: {
|
|
42
|
+
extensions: "user" | "none";
|
|
43
|
+
}): readonly string[];
|
|
55
44
|
/**
|
|
56
45
|
* The environment the profile's rules add to the agent process (SPEC US-002,
|
|
57
46
|
* extended by US-004), the one seam every launch goes through — a new session, a
|
|
@@ -1,7 +1,25 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
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";
|
|
3
20
|
import { OPENCODE_NONE_CONFIG, OPENCODE_READ_CONFIG, OPENCODE_REVIEW_CONFIG } from "#src/client/registry";
|
|
4
21
|
import { PI_SHELL_GATE_SOURCE } from "#src/client/shell-rules";
|
|
22
|
+
import { shellQuote } from "#src/client/shell-sandbox";
|
|
5
23
|
const NONE = Object.freeze([]);
|
|
6
24
|
/** The rules of a caller that has none: every list empty. */
|
|
7
25
|
export const NO_RULES = Object.freeze({ allow: NONE, deny: NONE, ask: NONE });
|
|
@@ -45,8 +63,6 @@ export function opencodePermissionConfig(profile, rules) {
|
|
|
45
63
|
permission.bash = "ask";
|
|
46
64
|
return JSON.stringify({ permission });
|
|
47
65
|
}
|
|
48
|
-
/** The only tool whose rules can allow a shell command (shell-rules.ts, US-003). */
|
|
49
|
-
const BASH_TOOL = "Bash";
|
|
50
66
|
/** Cursor's write and web tools, denied in every read-only profile and in this order. */
|
|
51
67
|
const CURSOR_DENIES = Object.freeze(["Write(**)", "Delete(**)", "Mcp(*:*)", "WebFetch(*)"]);
|
|
52
68
|
/**
|
|
@@ -76,16 +92,6 @@ const PI_TOOLS = Object.freeze([
|
|
|
76
92
|
Object.freeze(["ls", "Glob"]),
|
|
77
93
|
]);
|
|
78
94
|
const PI_GATE_ARG = "-e";
|
|
79
|
-
/**
|
|
80
|
-
* Whether this profile runs its shell commands through nax's own gate: only
|
|
81
|
-
* `review` has a shell tool to police, and only when an operator Bash rule could
|
|
82
|
-
* ever allow a command (an unconditional allow is not needed — the gate asks
|
|
83
|
-
* about each command and nax decides it, shell-rules.ts). `read` keeps no shell
|
|
84
|
-
* tool at all, and `none` keeps no tool.
|
|
85
|
-
*/
|
|
86
|
-
function usesShellGate(profile, rules) {
|
|
87
|
-
return profile === "review" && rules.allow.some((rule) => rule.tool === BASH_TOOL);
|
|
88
|
-
}
|
|
89
95
|
/**
|
|
90
96
|
* pi's `--tools` arguments (SPEC US-004): `--no-tools` under `none`, else pi's
|
|
91
97
|
* read tools in a fixed order minus the ones an unconditional deny removed.
|
|
@@ -93,28 +99,30 @@ function usesShellGate(profile, rules) {
|
|
|
93
99
|
* is appended after the read tools and the gate extension is loaded first, so
|
|
94
100
|
* every command goes through the nax shell gate.
|
|
95
101
|
*/
|
|
96
|
-
export function piToolArgs(profile, rules, gatePath) {
|
|
102
|
+
export function piToolArgs(profile, rules, gatePath, sandbox) {
|
|
97
103
|
if (profile === "none")
|
|
98
104
|
return ["--no-tools"];
|
|
99
105
|
const readTools = PI_TOOLS.filter(([, tool]) => !denied(rules, tool)).map(([name]) => name);
|
|
100
|
-
const
|
|
106
|
+
const sandboxed = profile === "review" && sandbox !== undefined;
|
|
107
|
+
const gated = sandboxed || reviewDecidesShell(profile, rules);
|
|
101
108
|
const tools = gated ? [...readTools, "bash"] : readTools;
|
|
102
109
|
if (tools.length === 0)
|
|
103
110
|
return ["--no-tools"];
|
|
104
|
-
return [
|
|
111
|
+
return [
|
|
112
|
+
...(sandboxed && sandbox.extensions === "none" ? ["--no-extensions"] : []),
|
|
113
|
+
...(gated ? [PI_GATE_ARG, gatePath] : []),
|
|
114
|
+
"--tools",
|
|
115
|
+
tools.join(","),
|
|
116
|
+
];
|
|
105
117
|
}
|
|
106
118
|
/** The gate extension is nax's own source, readable by the user alone; the wrapper has to be executable. */
|
|
107
119
|
const PI_GATE_MODE = 0o600;
|
|
108
120
|
const PI_WRAPPER_MODE = 0o700;
|
|
109
121
|
/** pi-acp's own default when the caller names no executable. */
|
|
110
122
|
const PI_DEFAULT_COMMAND = "pi";
|
|
111
|
-
/** One `sh` word, single-quoted; a `'` inside becomes `'\''`. */
|
|
112
|
-
function shQuote(word) {
|
|
113
|
-
return `'${word.replaceAll("'", "'\\''")}'`;
|
|
114
|
-
}
|
|
115
123
|
/** The wrapper `PI_ACP_PI_COMMAND` names: exec pi with the profile's arguments, forwarding the caller's own. */
|
|
116
124
|
function piWrapper(command, args) {
|
|
117
|
-
return `#!/bin/sh\nexec ${[command, ...args].map(
|
|
125
|
+
return `#!/bin/sh\nexec ${[command, ...args].map(shellQuote).join(" ")} "$@"\n`;
|
|
118
126
|
}
|
|
119
127
|
/**
|
|
120
128
|
* pi's launch env: the gate extension when one is needed, then the wrapper that
|
|
@@ -124,11 +132,14 @@ function piWrapper(command, args) {
|
|
|
124
132
|
*/
|
|
125
133
|
async function piLaunchEnv(options, profile) {
|
|
126
134
|
const rules = options.rules;
|
|
127
|
-
const
|
|
128
|
-
|
|
129
|
-
|
|
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
|
+
: "";
|
|
130
141
|
const command = options.env.PI_ACP_PI_COMMAND ?? PI_DEFAULT_COMMAND;
|
|
131
|
-
const body = piWrapper(command, piToolArgs(profile, rules, gate));
|
|
142
|
+
const body = piWrapper(command, piToolArgs(profile, rules, gate, plan ? { extensions: plan.piExtensions } : undefined));
|
|
132
143
|
return Object.freeze({ PI_ACP_PI_COMMAND: await writePiFile(options.stateDir, "wrapper", body, PI_WRAPPER_MODE) });
|
|
133
144
|
}
|
|
134
145
|
/**
|
|
@@ -143,16 +154,25 @@ async function piLaunchEnv(options, profile) {
|
|
|
143
154
|
* enforcement value.
|
|
144
155
|
*/
|
|
145
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
|
+
}
|
|
146
161
|
const entry = options.entry;
|
|
147
162
|
if (!isReadOnlyProfile(profile))
|
|
148
163
|
return launchEnvFor(profile, entry);
|
|
149
164
|
switch (entry?.readOnly?.policy) {
|
|
150
165
|
case "opencode":
|
|
166
|
+
if (profile === "review" && plan?.agent === "opencode") {
|
|
167
|
+
return opencodeSandboxEnv(plan, opencodePermissionConfig(profile, options.rules), options.env);
|
|
168
|
+
}
|
|
151
169
|
return Object.freeze({ OPENCODE_CONFIG_CONTENT: opencodePermissionConfig(profile, options.rules) });
|
|
152
|
-
case "cursor":
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
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
|
+
}
|
|
156
176
|
case "pi":
|
|
157
177
|
return piLaunchEnv(options, profile);
|
|
158
178
|
default:
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import type { AcpPermissionRules } from "#src/client/rule-policy";
|
|
2
2
|
export declare const SHELL_RULE_REASON = "an operator Bash rule allows this command";
|
|
3
3
|
export declare const PI_SHELL_GATE_TITLE = "nax: run shell command";
|
|
4
|
+
/** The reason the gate extension blocks a bash call with, both when nobody can answer and when they said no. */
|
|
5
|
+
export declare const PI_SHELL_GATE_REJECTED = "nax: shell command rejected";
|
|
4
6
|
/**
|
|
5
7
|
* The pi extension that gives pi a permission system (SPEC US-003): pi-acp hands
|
|
6
8
|
* the confirm prompt to nax as an ACP permission request, and nax answers it with
|
|
@@ -14,5 +16,7 @@ export declare const PI_SHELL_GATE_SOURCE: string;
|
|
|
14
16
|
* (never the masked display text), or undefined when the call is not one.
|
|
15
17
|
*/
|
|
16
18
|
export declare function shellCommandOf(agentName: string, toolCall: unknown): string | undefined;
|
|
19
|
+
/** Explicit deny/ask rules still bind inside the sandbox; lexer refusals remain sandboxed. */
|
|
20
|
+
export declare function shellRuleBlocks(command: string, rules: AcpPermissionRules): boolean;
|
|
17
21
|
/** "allow" only when the lexer read the whole command and every segment is allowed. */
|
|
18
22
|
export declare function shellRuleVerdict(command: string, rules: AcpPermissionRules): "allow" | "deny";
|
|
@@ -24,7 +24,7 @@ export const PI_SHELL_GATE_TITLE = "nax: run shell command";
|
|
|
24
24
|
/** The only tool whose rules can allow a command: `Exec` and `RunCommand` are not applied to ACP agents. */
|
|
25
25
|
const BASH_TOOL = "Bash";
|
|
26
26
|
/** The reason the gate extension blocks a bash call with, both when nobody can answer and when they said no. */
|
|
27
|
-
const PI_SHELL_GATE_REJECTED = "nax: shell command rejected";
|
|
27
|
+
export const PI_SHELL_GATE_REJECTED = "nax: shell command rejected";
|
|
28
28
|
/**
|
|
29
29
|
* The pi extension that gives pi a permission system (SPEC US-003): pi-acp hands
|
|
30
30
|
* the confirm prompt to nax as an ACP permission request, and nax answers it with
|
|
@@ -115,6 +115,16 @@ function segmentAllowed(segment, rules) {
|
|
|
115
115
|
return false;
|
|
116
116
|
return !anyPatternMatches(rules.deny, argv) && !anyPatternMatches(rules.ask, argv);
|
|
117
117
|
}
|
|
118
|
+
/** Explicit deny/ask rules still bind inside the sandbox; lexer refusals remain sandboxed. */
|
|
119
|
+
export function shellRuleBlocks(command, rules) {
|
|
120
|
+
const lexed = lexBashCommand(command);
|
|
121
|
+
if (lexed.kind !== "ok")
|
|
122
|
+
return false;
|
|
123
|
+
return lexed.segments.some((segment) => {
|
|
124
|
+
const argv = segment.tokens.map((token) => token.text);
|
|
125
|
+
return anyPatternMatches(rules.deny, argv) || anyPatternMatches(rules.ask, argv);
|
|
126
|
+
});
|
|
127
|
+
}
|
|
118
128
|
/** "allow" only when the lexer read the whole command and every segment is allowed. */
|
|
119
129
|
export function shellRuleVerdict(command, rules) {
|
|
120
130
|
const lexed = lexBashCommand(command);
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/** Per-session command sandbox planning. Agent processes themselves remain on the host. */
|
|
2
|
+
import { mkdir, readlink, symlink } from "node:fs/promises";
|
|
3
|
+
import { homedir, platform } from "node:os";
|
|
4
|
+
import type { AgentSessionProfile, SandboxPolicy, SessionSandbox } from "@nathapp/nax-agent";
|
|
5
|
+
import type { ResolvedAcpOptions } from "#src/client/options";
|
|
6
|
+
export declare const _shellSandboxDeps: {
|
|
7
|
+
homedir: typeof homedir;
|
|
8
|
+
realpath: (path: string) => Promise<string>;
|
|
9
|
+
mkdir: typeof mkdir;
|
|
10
|
+
platform: typeof platform;
|
|
11
|
+
symlink: typeof symlink;
|
|
12
|
+
readlink: typeof readlink;
|
|
13
|
+
};
|
|
14
|
+
/** Internal to the ACP package, not part of the ./client API. */
|
|
15
|
+
export type ShellSandboxPlan = {
|
|
16
|
+
agent: "opencode" | "cursor" | "pi";
|
|
17
|
+
policy: SandboxPolicy;
|
|
18
|
+
policyContent: string;
|
|
19
|
+
policyFile: string;
|
|
20
|
+
prefix: string;
|
|
21
|
+
home: string;
|
|
22
|
+
runtime: string;
|
|
23
|
+
workdir: string;
|
|
24
|
+
verify: boolean;
|
|
25
|
+
onUnwrapped: "rules" | "deny";
|
|
26
|
+
piExtensions: "user" | "none";
|
|
27
|
+
stripEnv: readonly string[];
|
|
28
|
+
};
|
|
29
|
+
/** One POSIX shell word; an embedded apostrophe closes, escapes, then reopens the quote. */
|
|
30
|
+
export declare function shellQuote(word: string): string;
|
|
31
|
+
/** Always wrap, including commands that already resemble a wrapper. */
|
|
32
|
+
export declare function wrapForSandbox(prefix: string, command: string): string;
|
|
33
|
+
/** The suffix must be exactly one POSIX single-quoted word, not shell syntax. */
|
|
34
|
+
export declare function isSandboxWrapped(prefix: string, command: string): boolean;
|
|
35
|
+
/** Reuse the actual quoting implementation in each generated agent hook. */
|
|
36
|
+
export declare function sandboxWrapSnippet(prefix: string): string;
|
|
37
|
+
/** Plans only opted-in review commands with an available policy; does not write the policy file. */
|
|
38
|
+
export declare function shellSandboxPlan(profile: AgentSessionProfile, options: ResolvedAcpOptions, sandbox: SessionSandbox | undefined, workdir: string): Promise<ShellSandboxPlan | undefined>;
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
/** Per-session command sandbox planning. Agent processes themselves remain on the host. */
|
|
2
|
+
import { mkdir, readlink, realpath, symlink } from "node:fs/promises";
|
|
3
|
+
import { homedir, platform } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { backendUnavailable } from "#src/client/errors";
|
|
6
|
+
import { digest } from "#src/client/policy-files";
|
|
7
|
+
export const _shellSandboxDeps = {
|
|
8
|
+
homedir,
|
|
9
|
+
realpath: (path) => realpath(path),
|
|
10
|
+
mkdir,
|
|
11
|
+
platform,
|
|
12
|
+
symlink,
|
|
13
|
+
readlink,
|
|
14
|
+
};
|
|
15
|
+
/** One POSIX shell word; an embedded apostrophe closes, escapes, then reopens the quote. */
|
|
16
|
+
export function shellQuote(word) {
|
|
17
|
+
return `'${word.replaceAll("'", "'\\''")}'`;
|
|
18
|
+
}
|
|
19
|
+
/** Always wrap, including commands that already resemble a wrapper. */
|
|
20
|
+
export function wrapForSandbox(prefix, command) {
|
|
21
|
+
return prefix + shellQuote(command);
|
|
22
|
+
}
|
|
23
|
+
/** The suffix must be exactly one POSIX single-quoted word, not shell syntax. */
|
|
24
|
+
export function isSandboxWrapped(prefix, command) {
|
|
25
|
+
return command.startsWith(prefix) && /^'(?:[^']|'\\'')*'$/.test(command.slice(prefix.length));
|
|
26
|
+
}
|
|
27
|
+
/** Reuse the actual quoting implementation in each generated agent hook. */
|
|
28
|
+
export function sandboxWrapSnippet(prefix) {
|
|
29
|
+
return `const NAX_SANDBOX_PREFIX = ${JSON.stringify(prefix)};
|
|
30
|
+
function naxSandboxWrap(command) {
|
|
31
|
+
return NAX_SANDBOX_PREFIX + (${shellQuote.toString()})(command);
|
|
32
|
+
}
|
|
33
|
+
`;
|
|
34
|
+
}
|
|
35
|
+
async function credentialPath(path) {
|
|
36
|
+
try {
|
|
37
|
+
return await _shellSandboxDeps.realpath(path);
|
|
38
|
+
}
|
|
39
|
+
catch (err) {
|
|
40
|
+
// Only a missing file is safe to omit. Permission and other I/O failures refuse planning.
|
|
41
|
+
if (err instanceof Error && "code" in err && err.code === "ENOENT")
|
|
42
|
+
return undefined;
|
|
43
|
+
throw backendUnavailable(`the credential floor "${path}" could not be resolved`, { path, cause: err });
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
async function withFloors(policy, stateDir, home) {
|
|
47
|
+
let state;
|
|
48
|
+
try {
|
|
49
|
+
await _shellSandboxDeps.mkdir(stateDir, { recursive: true, mode: 0o700 });
|
|
50
|
+
state = await _shellSandboxDeps.realpath(stateDir);
|
|
51
|
+
}
|
|
52
|
+
catch (err) {
|
|
53
|
+
throw backendUnavailable(`the shell sandbox state directory "${stateDir}" could not be resolved`, {
|
|
54
|
+
path: stateDir,
|
|
55
|
+
cause: err,
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
const credentials = await Promise.all([
|
|
59
|
+
credentialPath(join(home, ".local", "share", "opencode", "auth.json")),
|
|
60
|
+
credentialPath(join(home, ".pi", "agent", "auth.json")),
|
|
61
|
+
]);
|
|
62
|
+
return {
|
|
63
|
+
...policy,
|
|
64
|
+
denyWrite: [...policy.denyWrite, state],
|
|
65
|
+
denyRead: [...policy.denyRead, ...credentials.filter((path) => path !== undefined)],
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
function credentialEnvNames(options) {
|
|
69
|
+
const secrets = new Set(options.secrets);
|
|
70
|
+
return [
|
|
71
|
+
...new Set([
|
|
72
|
+
...(options.entry?.authEnv ?? []),
|
|
73
|
+
...Object.keys(options.env).filter((name) => secrets.has(options.env[name] ?? "")),
|
|
74
|
+
]),
|
|
75
|
+
].sort();
|
|
76
|
+
}
|
|
77
|
+
/** Plans only opted-in review commands with an available policy; does not write the policy file. */
|
|
78
|
+
export async function shellSandboxPlan(profile, options, sandbox, workdir) {
|
|
79
|
+
const settings = options.shellSandbox;
|
|
80
|
+
const agent = options.agentName;
|
|
81
|
+
if (profile !== "review" || settings === undefined || sandbox?.kind !== "policy")
|
|
82
|
+
return undefined;
|
|
83
|
+
if (agent !== "opencode" && agent !== "cursor" && agent !== "pi")
|
|
84
|
+
return undefined;
|
|
85
|
+
if (agent === "opencode" && settings.opencodeProjectConfig === "keep")
|
|
86
|
+
return undefined;
|
|
87
|
+
const home = _shellSandboxDeps.homedir();
|
|
88
|
+
const policy = await withFloors(sandbox.policy, options.stateDir, home);
|
|
89
|
+
const stripEnv = credentialEnvNames(options);
|
|
90
|
+
const policyContent = JSON.stringify({ version: 1, home, stripEnv, policy });
|
|
91
|
+
const policyFile = join(options.stateDir, "sandbox", `policy-${digest(policyContent)}.json`);
|
|
92
|
+
const prefix = `${[settings.runtime, ...settings.runner, policyFile].map(shellQuote).join(" ")} `;
|
|
93
|
+
return {
|
|
94
|
+
agent,
|
|
95
|
+
policy,
|
|
96
|
+
policyContent,
|
|
97
|
+
policyFile,
|
|
98
|
+
prefix,
|
|
99
|
+
home,
|
|
100
|
+
runtime: settings.runtime,
|
|
101
|
+
workdir,
|
|
102
|
+
verify: agent === "cursor",
|
|
103
|
+
onUnwrapped: settings.cursorOnUnwrapped,
|
|
104
|
+
piExtensions: settings.piExtensions,
|
|
105
|
+
stripEnv,
|
|
106
|
+
};
|
|
107
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function startupBannerOf(response: unknown): string | undefined;
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* An agent's startup banner (nax#2591). pi-acp answers session/new with
|
|
3
|
+
* `_meta.piAcp.startupInfo` and then sends that same text as one message chunk,
|
|
4
|
+
* which lands in the session's first turn. The collector drops a chunk of exactly
|
|
5
|
+
* this text, so the banner is never mistaken for the agent's reply. The answer
|
|
6
|
+
* is agent data: anything but a non-empty string is no banner.
|
|
7
|
+
*/
|
|
8
|
+
import { isRecord } from "#src/client/text";
|
|
9
|
+
export function startupBannerOf(response) {
|
|
10
|
+
if (!isRecord(response) || !isRecord(response._meta))
|
|
11
|
+
return undefined;
|
|
12
|
+
const pi = response._meta.piAcp;
|
|
13
|
+
if (!isRecord(pi))
|
|
14
|
+
return undefined;
|
|
15
|
+
return typeof pi.startupInfo === "string" && pi.startupInfo !== "" ? pi.startupInfo : undefined;
|
|
16
|
+
}
|
package/dist/client/turn.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { attachTurnSpend, NaxError } from "@nathapp/nax-agent";
|
|
2
|
-
import { promptRequestError, rpcErrorOf, stopReasonError } from "#src/client/errors";
|
|
2
|
+
import { emptyTurnError, promptRequestError, rpcErrorOf, stopReasonError } from "#src/client/errors";
|
|
3
3
|
import { agentGoneError } from "#src/client/launch";
|
|
4
4
|
import { race } from "#src/client/race";
|
|
5
5
|
import { sumUsage, tokenUsageOf } from "#src/client/usage";
|
|
@@ -63,8 +63,9 @@ async function promptOnce(state, input, text, carried) {
|
|
|
63
63
|
}
|
|
64
64
|
function resultOf(response, collector, prompts) {
|
|
65
65
|
const spend = collector.settle(response);
|
|
66
|
-
|
|
67
|
-
|
|
66
|
+
const idle = !collector.worked() && spend.tokenUsage.inputTokens === 0 && spend.tokenUsage.outputTokens === 0;
|
|
67
|
+
if (response.stopReason !== "end_turn" || idle) {
|
|
68
|
+
const error = response.stopReason === "end_turn" ? emptyTurnError() : stopReasonError(String(response.stopReason));
|
|
68
69
|
attachTurnSpend(error, spend);
|
|
69
70
|
throw error;
|
|
70
71
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nathapp/nax-agent-acp",
|
|
3
|
-
"version": "0.90.
|
|
3
|
+
"version": "0.90.2",
|
|
4
4
|
"description": "ACP (Agent Client Protocol) backend for @nathapp/nax-agent sessions: drive Claude Code and other ACP agents through the nax-agent session API.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "William Khoo",
|
|
@@ -49,7 +49,7 @@
|
|
|
49
49
|
"zod": "^4.3.6"
|
|
50
50
|
},
|
|
51
51
|
"peerDependencies": {
|
|
52
|
-
"@nathapp/nax-agent": "^0.90.
|
|
52
|
+
"@nathapp/nax-agent": "^0.90.2"
|
|
53
53
|
},
|
|
54
54
|
"publishConfig": {
|
|
55
55
|
"access": "public",
|