@nathapp/nax-agent-acp 0.90.0 → 0.90.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +4 -0
- package/dist/client/backend.js +16 -5
- package/dist/client/capabilities.d.ts +20 -0
- package/dist/client/capabilities.js +39 -1
- package/dist/client/connection.d.ts +10 -1
- package/dist/client/connection.js +4 -0
- package/dist/client/events.d.ts +4 -0
- package/dist/client/events.js +5 -0
- package/dist/client/inbound.d.ts +2 -1
- package/dist/client/inbound.js +11 -2
- package/dist/client/index.d.ts +1 -0
- package/dist/client/open.js +73 -33
- package/dist/client/options.d.ts +15 -0
- package/dist/client/options.js +33 -2
- package/dist/client/permissions.d.ts +13 -1
- package/dist/client/permissions.js +45 -12
- package/dist/client/policy-files.d.ts +17 -0
- package/dist/client/policy-files.js +65 -0
- package/dist/client/registry.d.ts +26 -9
- package/dist/client/registry.js +124 -9
- package/dist/client/resume.d.ts +5 -3
- package/dist/client/resume.js +3 -2
- package/dist/client/rule-policy.d.ts +66 -0
- package/dist/client/rule-policy.js +161 -0
- package/dist/client/session-offers.d.ts +18 -0
- package/dist/client/session-offers.js +32 -0
- package/dist/client/shell-rules.d.ts +18 -0
- package/dist/client/shell-rules.js +124 -0
- package/dist/client/turn.d.ts +3 -0
- package/dist/client/turn.js +36 -6
- package/dist/client/usage.d.ts +3 -1
- package/dist/client/usage.js +23 -0
- package/package.json +2 -2
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import { isReadOnlyProfile, launchEnvFor } from "#src/client/capabilities";
|
|
2
|
+
import { writeCursorPolicy, writePiFile } from "#src/client/policy-files";
|
|
3
|
+
import { OPENCODE_NONE_CONFIG, OPENCODE_READ_CONFIG, OPENCODE_REVIEW_CONFIG } from "#src/client/registry";
|
|
4
|
+
import { PI_SHELL_GATE_SOURCE } from "#src/client/shell-rules";
|
|
5
|
+
const NONE = Object.freeze([]);
|
|
6
|
+
/** The rules of a caller that has none: every list empty. */
|
|
7
|
+
export const NO_RULES = Object.freeze({ allow: NONE, deny: NONE, ask: NONE });
|
|
8
|
+
/** A rule denies this tool outright: nax's own "unconditional" test, a pattern holding `*`. */
|
|
9
|
+
function denied(rules, tool) {
|
|
10
|
+
return rules.deny.some((rule) => rule.tool === tool && rule.patterns.includes("*"));
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* opencode's `permission` entries and the read tool each one serves, in the order
|
|
14
|
+
* the registry's own configs list them: the catch-all deny first, then each
|
|
15
|
+
* allowance, because opencode's rules are last-match-wins. `list` belongs to
|
|
16
|
+
* `Read`: without the read tool opencode has no reason to list directories either.
|
|
17
|
+
*/
|
|
18
|
+
const OPENCODE_ENTRIES = Object.freeze([
|
|
19
|
+
Object.freeze(["read", "Read"]),
|
|
20
|
+
Object.freeze(["glob", "Glob"]),
|
|
21
|
+
Object.freeze(["grep", "Grep"]),
|
|
22
|
+
Object.freeze(["list", "Read"]),
|
|
23
|
+
]);
|
|
24
|
+
/**
|
|
25
|
+
* opencode's permission config for a read-only profile (SPEC US-002). An
|
|
26
|
+
* unconditional deny of a read tool removes its entries, so opencode drops the
|
|
27
|
+
* tool from the model's catalog; with no such rule the result is byte-identical
|
|
28
|
+
* to the registry's OPENCODE_*_CONFIG. `none` ignores the rules: every tool is
|
|
29
|
+
* denied there and no rule can widen it. Bash rules are never translated (an
|
|
30
|
+
* agent matching command text knows nothing of redirects), and `read` keeps no
|
|
31
|
+
* shell tool while `review` asks nax about every command.
|
|
32
|
+
*/
|
|
33
|
+
export function opencodePermissionConfig(profile, rules) {
|
|
34
|
+
if (profile === "none")
|
|
35
|
+
return OPENCODE_NONE_CONFIG;
|
|
36
|
+
const kept = OPENCODE_ENTRIES.filter(([, tool]) => !denied(rules, tool));
|
|
37
|
+
// No read tool is denied: the operator default, byte for byte.
|
|
38
|
+
if (kept.length === OPENCODE_ENTRIES.length) {
|
|
39
|
+
return profile === "review" ? OPENCODE_REVIEW_CONFIG : OPENCODE_READ_CONFIG;
|
|
40
|
+
}
|
|
41
|
+
const permission = { "*": "deny" };
|
|
42
|
+
for (const [key] of kept)
|
|
43
|
+
permission[key] = "allow";
|
|
44
|
+
if (profile === "review")
|
|
45
|
+
permission.bash = "ask";
|
|
46
|
+
return JSON.stringify({ permission });
|
|
47
|
+
}
|
|
48
|
+
/** The only tool whose rules can allow a shell command (shell-rules.ts, US-003). */
|
|
49
|
+
const BASH_TOOL = "Bash";
|
|
50
|
+
/** Cursor's write and web tools, denied in every read-only profile and in this order. */
|
|
51
|
+
const CURSOR_DENIES = Object.freeze(["Write(**)", "Delete(**)", "Mcp(*:*)", "WebFetch(*)"]);
|
|
52
|
+
/**
|
|
53
|
+
* Cursor's isolated permission config (SPEC US-004). Cursor's own modes enforce
|
|
54
|
+
* nothing, so this file is the whole enforcement: `Read(**)` is allowed unless an
|
|
55
|
+
* unconditional Read deny removes it (and then joins the deny list), writes, MCP
|
|
56
|
+
* and the web are denied, and shell is denied under `read` and absent under
|
|
57
|
+
* `review`, where Cursor asks the client about every command and nax decides it
|
|
58
|
+
* (shell-rules.ts). `none` ignores the rules: everything is denied there, and no
|
|
59
|
+
* rule can widen it.
|
|
60
|
+
*/
|
|
61
|
+
export function cursorCliConfig(profile, rules) {
|
|
62
|
+
const readDenied = profile === "none" || denied(rules, "Read");
|
|
63
|
+
/** review leaves shell unlisted: every command is asked of the client, and nax answers (US-003). */
|
|
64
|
+
const deny = [...CURSOR_DENIES, ...(profile === "review" ? [] : ["Shell(*)"]), ...(readDenied ? ["Read(**)"] : [])];
|
|
65
|
+
return JSON.stringify({
|
|
66
|
+
version: 1,
|
|
67
|
+
permissions: { allow: readDenied ? [] : ["Read(**)"], deny },
|
|
68
|
+
approvalMode: "allowlist",
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
/** pi's tools in the order `--tools` lists them, and the read tool each one serves. */
|
|
72
|
+
const PI_TOOLS = Object.freeze([
|
|
73
|
+
Object.freeze(["read", "Read"]),
|
|
74
|
+
Object.freeze(["grep", "Grep"]),
|
|
75
|
+
Object.freeze(["find", "Glob"]),
|
|
76
|
+
Object.freeze(["ls", "Glob"]),
|
|
77
|
+
]);
|
|
78
|
+
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
|
+
/**
|
|
90
|
+
* pi's `--tools` arguments (SPEC US-004): `--no-tools` under `none`, else pi's
|
|
91
|
+
* read tools in a fixed order minus the ones an unconditional deny removed.
|
|
92
|
+
* `Glob` owns pi's `find` and `ls`. Under `review` with a Bash allow rule, `bash`
|
|
93
|
+
* is appended after the read tools and the gate extension is loaded first, so
|
|
94
|
+
* every command goes through the nax shell gate.
|
|
95
|
+
*/
|
|
96
|
+
export function piToolArgs(profile, rules, gatePath) {
|
|
97
|
+
if (profile === "none")
|
|
98
|
+
return ["--no-tools"];
|
|
99
|
+
const readTools = PI_TOOLS.filter(([, tool]) => !denied(rules, tool)).map(([name]) => name);
|
|
100
|
+
const gated = usesShellGate(profile, rules);
|
|
101
|
+
const tools = gated ? [...readTools, "bash"] : readTools;
|
|
102
|
+
if (tools.length === 0)
|
|
103
|
+
return ["--no-tools"];
|
|
104
|
+
return [...(gated ? [PI_GATE_ARG, gatePath] : []), "--tools", tools.join(",")];
|
|
105
|
+
}
|
|
106
|
+
/** The gate extension is nax's own source, readable by the user alone; the wrapper has to be executable. */
|
|
107
|
+
const PI_GATE_MODE = 0o600;
|
|
108
|
+
const PI_WRAPPER_MODE = 0o700;
|
|
109
|
+
/** pi-acp's own default when the caller names no executable. */
|
|
110
|
+
const PI_DEFAULT_COMMAND = "pi";
|
|
111
|
+
/** One `sh` word, single-quoted; a `'` inside becomes `'\''`. */
|
|
112
|
+
function shQuote(word) {
|
|
113
|
+
return `'${word.replaceAll("'", "'\\''")}'`;
|
|
114
|
+
}
|
|
115
|
+
/** The wrapper `PI_ACP_PI_COMMAND` names: exec pi with the profile's arguments, forwarding the caller's own. */
|
|
116
|
+
function piWrapper(command, args) {
|
|
117
|
+
return `#!/bin/sh\nexec ${[command, ...args].map(shQuote).join(" ")} "$@"\n`;
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* pi's launch env: the gate extension when one is needed, then the wrapper that
|
|
121
|
+
* runs pi with the profile's `--tools` (or `--no-tools`). The caller's own
|
|
122
|
+
* `PI_ACP_PI_COMMAND` names the executable to wrap, so a caller can point nax at
|
|
123
|
+
* a pi build without weakening the enforcement.
|
|
124
|
+
*/
|
|
125
|
+
async function piLaunchEnv(options, profile) {
|
|
126
|
+
const rules = options.rules;
|
|
127
|
+
const gate = usesShellGate(profile, rules)
|
|
128
|
+
? await writePiFile(options.stateDir, "shell-gate", PI_SHELL_GATE_SOURCE, PI_GATE_MODE)
|
|
129
|
+
: "";
|
|
130
|
+
const command = options.env.PI_ACP_PI_COMMAND ?? PI_DEFAULT_COMMAND;
|
|
131
|
+
const body = piWrapper(command, piToolArgs(profile, rules, gate));
|
|
132
|
+
return Object.freeze({ PI_ACP_PI_COMMAND: await writePiFile(options.stateDir, "wrapper", body, PI_WRAPPER_MODE) });
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* The environment the profile's rules add to the agent process (SPEC US-002,
|
|
136
|
+
* extended by US-004), the one seam every launch goes through — a new session, a
|
|
137
|
+
* resume and a reconnect. An agent whose entry names no policy keeps its
|
|
138
|
+
* `launchEnv` untouched, so its env is exactly what it was before rules existed;
|
|
139
|
+
* a custom agent has no entry and gets nothing. Cursor and pi read their policy
|
|
140
|
+
* from files under the state directory, written here before anything is spawned:
|
|
141
|
+
* a file that cannot be written refuses the open (policy-files.ts). The caller
|
|
142
|
+
* spreads this over its own env, so neither the caller nor a model can weaken the
|
|
143
|
+
* enforcement value.
|
|
144
|
+
*/
|
|
145
|
+
export async function policyLaunchEnv(profile, options) {
|
|
146
|
+
const entry = options.entry;
|
|
147
|
+
if (!isReadOnlyProfile(profile))
|
|
148
|
+
return launchEnvFor(profile, entry);
|
|
149
|
+
switch (entry?.readOnly?.policy) {
|
|
150
|
+
case "opencode":
|
|
151
|
+
return Object.freeze({ OPENCODE_CONFIG_CONTENT: opencodePermissionConfig(profile, options.rules) });
|
|
152
|
+
case "cursor":
|
|
153
|
+
return Object.freeze({
|
|
154
|
+
CURSOR_CONFIG_DIR: await writeCursorPolicy(options.stateDir, cursorCliConfig(profile, options.rules)),
|
|
155
|
+
});
|
|
156
|
+
case "pi":
|
|
157
|
+
return piLaunchEnv(options, profile);
|
|
158
|
+
default:
|
|
159
|
+
return launchEnvFor(profile, entry);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What a session/new, session/resume or session/load answer offers a profile
|
|
3
|
+
* (S4 spec §6.3 step 5). An agent may offer its modes and models as config
|
|
4
|
+
* options (`configOptions`, the ACP 1.x way) or as the legacy `modes` and
|
|
5
|
+
* `models` blocks (Gemini); a mode or model the agent offers only in a legacy
|
|
6
|
+
* block is set with `session/set_mode` / `session/set_model` (open.ts). The
|
|
7
|
+
* answer is agent data, so every read here is checked: a missing, malformed or
|
|
8
|
+
* non-string block offers nothing.
|
|
9
|
+
*/
|
|
10
|
+
import type { SessionConfigOption } from "@agentclientprotocol/sdk";
|
|
11
|
+
export interface SessionOffers {
|
|
12
|
+
readonly configOptions: readonly SessionConfigOption[];
|
|
13
|
+
/** `modes.availableModes[].id`: the mode ids set with session/set_mode. */
|
|
14
|
+
readonly modeIds: readonly string[];
|
|
15
|
+
/** `models.availableModels[].modelId`: the model ids set with session/set_model. */
|
|
16
|
+
readonly modelIds: readonly string[];
|
|
17
|
+
}
|
|
18
|
+
export declare function sessionOffers(response: unknown): SessionOffers;
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { isRecord } from "#src/client/text";
|
|
2
|
+
const NOTHING = Object.freeze({
|
|
3
|
+
configOptions: Object.freeze([]),
|
|
4
|
+
modeIds: Object.freeze([]),
|
|
5
|
+
modelIds: Object.freeze([]),
|
|
6
|
+
});
|
|
7
|
+
function configOptionsOf(response) {
|
|
8
|
+
const value = response.configOptions;
|
|
9
|
+
return Array.isArray(value) ? value : [];
|
|
10
|
+
}
|
|
11
|
+
/** The non-empty string ids of `block[listKey][idKey]`, skipping anything else. */
|
|
12
|
+
function idsOf(block, listKey, idKey) {
|
|
13
|
+
if (!isRecord(block))
|
|
14
|
+
return [];
|
|
15
|
+
const list = block[listKey];
|
|
16
|
+
if (!Array.isArray(list))
|
|
17
|
+
return [];
|
|
18
|
+
return list.flatMap((entry) => {
|
|
19
|
+
const id = isRecord(entry) ? entry[idKey] : undefined;
|
|
20
|
+
return typeof id === "string" && id !== "" ? [id] : [];
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
export function sessionOffers(response) {
|
|
24
|
+
if (!isRecord(response))
|
|
25
|
+
return NOTHING;
|
|
26
|
+
const configOptions = configOptionsOf(response);
|
|
27
|
+
const modeIds = idsOf(response.modes, "availableModes", "id");
|
|
28
|
+
const modelIds = idsOf(response.models, "availableModels", "modelId");
|
|
29
|
+
if (configOptions.length === 0 && modeIds.length === 0 && modelIds.length === 0)
|
|
30
|
+
return NOTHING;
|
|
31
|
+
return { configOptions, modeIds, modelIds };
|
|
32
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { AcpPermissionRules } from "#src/client/rule-policy";
|
|
2
|
+
export declare const SHELL_RULE_REASON = "an operator Bash rule allows this command";
|
|
3
|
+
export declare const PI_SHELL_GATE_TITLE = "nax: run shell command";
|
|
4
|
+
/**
|
|
5
|
+
* The pi extension that gives pi a permission system (SPEC US-003): pi-acp hands
|
|
6
|
+
* the confirm prompt to nax as an ACP permission request, and nax answers it with
|
|
7
|
+
* the operator's Bash rules. `pi` has neither a read-only mode nor permission
|
|
8
|
+
* config, so this is its only enforcement path under `review`.
|
|
9
|
+
* US-004 writes this to disk; it is a plain module so pi can load it directly.
|
|
10
|
+
*/
|
|
11
|
+
export declare const PI_SHELL_GATE_SOURCE: string;
|
|
12
|
+
/**
|
|
13
|
+
* The shell command this tool call asks about, from the raw agent fields only
|
|
14
|
+
* (never the masked display text), or undefined when the call is not one.
|
|
15
|
+
*/
|
|
16
|
+
export declare function shellCommandOf(agentName: string, toolCall: unknown): string | undefined;
|
|
17
|
+
/** "allow" only when the lexer read the whole command and every segment is allowed. */
|
|
18
|
+
export declare function shellRuleVerdict(command: string, rules: AcpPermissionRules): "allow" | "deny";
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ACP shell commands, adjudicated by the operator's own Bash rules
|
|
3
|
+
* (SPEC-cursor-pi-acp-read-only US-003). Under `review` an agent process runs
|
|
4
|
+
* unsandboxed, so a shell command it asks about would otherwise be denied
|
|
5
|
+
* outright. Here nax reads the RAW command — never the secret-masked display
|
|
6
|
+
* text a person would see, and never the agent's own reading of it — and checks
|
|
7
|
+
* it against the same `execution.permissions.<stage>.allow / deny / ask` rules a
|
|
8
|
+
* native session uses.
|
|
9
|
+
*
|
|
10
|
+
* Fail closed, four ways (the native lexer's guarantee, reused whole):
|
|
11
|
+
* a command the lexer refuses, one with no segment, one with any redirect, and
|
|
12
|
+
* one with any opaque token (a `$`-expansion, whose runtime value nax cannot
|
|
13
|
+
* know) are all denied, whatever the rules say. A redirect is denied even when
|
|
14
|
+
* an allow rule names the command: the agents that translate Bash rules match
|
|
15
|
+
* command TEXT and know nothing of redirects, which is why the decision belongs
|
|
16
|
+
* here rather than in an agent's own config.
|
|
17
|
+
*
|
|
18
|
+
* `ask` counts as a deny: nobody answers an ACP read-only session.
|
|
19
|
+
*/
|
|
20
|
+
import { compileArgvPattern, lexBashCommand, matchesArgvPattern } from "@nathapp/nax-agent";
|
|
21
|
+
import { isRecord } from "#src/client/text";
|
|
22
|
+
export const SHELL_RULE_REASON = "an operator Bash rule allows this command";
|
|
23
|
+
export const PI_SHELL_GATE_TITLE = "nax: run shell command";
|
|
24
|
+
/** The only tool whose rules can allow a command: `Exec` and `RunCommand` are not applied to ACP agents. */
|
|
25
|
+
const BASH_TOOL = "Bash";
|
|
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";
|
|
28
|
+
/**
|
|
29
|
+
* The pi extension that gives pi a permission system (SPEC US-003): pi-acp hands
|
|
30
|
+
* the confirm prompt to nax as an ACP permission request, and nax answers it with
|
|
31
|
+
* the operator's Bash rules. `pi` has neither a read-only mode nor permission
|
|
32
|
+
* config, so this is its only enforcement path under `review`.
|
|
33
|
+
* US-004 writes this to disk; it is a plain module so pi can load it directly.
|
|
34
|
+
*/
|
|
35
|
+
export const PI_SHELL_GATE_SOURCE = `/**
|
|
36
|
+
* nax's pi shell gate. pi has no permission system of its own, so this extension
|
|
37
|
+
* turns every bash call into a confirm prompt: pi-acp hands that prompt to nax as
|
|
38
|
+
* an ACP permission request, and nax answers it with the operator's Bash rules.
|
|
39
|
+
* Written by nax; do not edit in place.
|
|
40
|
+
*/
|
|
41
|
+
export default function naxShellGate(pi) {
|
|
42
|
+
const blocked = { block: true, reason: ${JSON.stringify(PI_SHELL_GATE_REJECTED)} };
|
|
43
|
+
|
|
44
|
+
pi.on("tool_call", async (event, ctx) => {
|
|
45
|
+
if (!event || event.toolName !== "bash") return undefined;
|
|
46
|
+
const command = event.input && typeof event.input.command === "string" ? event.input.command : "";
|
|
47
|
+
const ui = ctx && ctx.hasUI === true ? ctx.ui : undefined;
|
|
48
|
+
// Fail closed: nothing readable to ask about, and nobody able to answer.
|
|
49
|
+
if (command === "" || !ui || typeof ui.confirm !== "function") return blocked;
|
|
50
|
+
return (await ui.confirm(${JSON.stringify(PI_SHELL_GATE_TITLE)}, command)) === true ? undefined : blocked;
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
`;
|
|
54
|
+
function nonEmpty(value) {
|
|
55
|
+
return typeof value === "string" && value !== "" ? value : undefined;
|
|
56
|
+
}
|
|
57
|
+
/** pi speaks through its own extension prompt: a confirm method, the gate's title and the command as the message. */
|
|
58
|
+
function piGateCommand(call, kind) {
|
|
59
|
+
if (kind !== "other" || !isRecord(call.rawInput))
|
|
60
|
+
return undefined;
|
|
61
|
+
const raw = call.rawInput;
|
|
62
|
+
if (raw.method !== "confirm" || raw.title !== PI_SHELL_GATE_TITLE)
|
|
63
|
+
return undefined;
|
|
64
|
+
return nonEmpty(raw.message);
|
|
65
|
+
}
|
|
66
|
+
/** Cursor carries the command in the title, in backticks (its own hooks rewrite it first). */
|
|
67
|
+
function cursorCommand(call, kind) {
|
|
68
|
+
if (kind !== "execute")
|
|
69
|
+
return undefined;
|
|
70
|
+
const title = nonEmpty(call.title);
|
|
71
|
+
if (title === undefined)
|
|
72
|
+
return undefined;
|
|
73
|
+
const enclosed = title.length >= 2 && title.startsWith("`") && title.endsWith("`");
|
|
74
|
+
return enclosed ? title.slice(1, -1) : title;
|
|
75
|
+
}
|
|
76
|
+
/** Every other agent carries it in rawInput.command. */
|
|
77
|
+
function rawCommand(call, kind) {
|
|
78
|
+
if (kind !== "execute" || !isRecord(call.rawInput))
|
|
79
|
+
return undefined;
|
|
80
|
+
return nonEmpty(call.rawInput.command);
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* The shell command this tool call asks about, from the raw agent fields only
|
|
84
|
+
* (never the masked display text), or undefined when the call is not one.
|
|
85
|
+
*/
|
|
86
|
+
export function shellCommandOf(agentName, toolCall) {
|
|
87
|
+
if (!isRecord(toolCall))
|
|
88
|
+
return undefined;
|
|
89
|
+
if (agentName === "pi")
|
|
90
|
+
return piGateCommand(toolCall, toolCall.kind);
|
|
91
|
+
if (agentName === "cursor")
|
|
92
|
+
return cursorCommand(toolCall, toolCall.kind);
|
|
93
|
+
return rawCommand(toolCall, toolCall.kind);
|
|
94
|
+
}
|
|
95
|
+
/** nax's native matcher, plus the rule that the pattern `*` alone is unconditional. */
|
|
96
|
+
function patternMatches(pattern, argv) {
|
|
97
|
+
return pattern === "*" || matchesArgvPattern(compileArgvPattern(pattern), argv);
|
|
98
|
+
}
|
|
99
|
+
function anyPatternMatches(rules, argv) {
|
|
100
|
+
return rules.some((rule) => rule.tool === BASH_TOOL && rule.patterns.some((pattern) => patternMatches(pattern, argv)));
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* One command between control operators: allowed only when an allow rule matches
|
|
104
|
+
* its argv and no deny or ask rule does. The payload checks a native session runs
|
|
105
|
+
* (denied flags, path containment) have no equivalent here: an ACP command has no
|
|
106
|
+
* resolved paths, and the rules are the whole decision.
|
|
107
|
+
*/
|
|
108
|
+
function segmentAllowed(segment, rules) {
|
|
109
|
+
if (segment.redirects.length > 0)
|
|
110
|
+
return false;
|
|
111
|
+
if (segment.tokens.some((token) => token.opaque))
|
|
112
|
+
return false;
|
|
113
|
+
const argv = segment.tokens.map((token) => token.text);
|
|
114
|
+
if (!anyPatternMatches(rules.allow, argv))
|
|
115
|
+
return false;
|
|
116
|
+
return !anyPatternMatches(rules.deny, argv) && !anyPatternMatches(rules.ask, argv);
|
|
117
|
+
}
|
|
118
|
+
/** "allow" only when the lexer read the whole command and every segment is allowed. */
|
|
119
|
+
export function shellRuleVerdict(command, rules) {
|
|
120
|
+
const lexed = lexBashCommand(command);
|
|
121
|
+
if (lexed.kind !== "ok" || lexed.segments.length === 0)
|
|
122
|
+
return "deny";
|
|
123
|
+
return lexed.segments.every((segment) => segmentAllowed(segment, rules)) ? "allow" : "deny";
|
|
124
|
+
}
|
package/dist/client/turn.d.ts
CHANGED
|
@@ -16,4 +16,7 @@ export interface TurnInput {
|
|
|
16
16
|
readonly signal: AbortSignal;
|
|
17
17
|
readonly collector: TurnCollector;
|
|
18
18
|
}
|
|
19
|
+
/** Follow-up prompts one turn may send after a deny made the agent cancel (nax#2582). */
|
|
20
|
+
export declare const MAX_DENIED_CONTINUATIONS = 2;
|
|
21
|
+
export declare const DENIED_CONTINUATION_PROMPT: string;
|
|
19
22
|
export declare function runPromptTurn(state: TurnState, input: TurnInput): Promise<TurnResult>;
|
package/dist/client/turn.js
CHANGED
|
@@ -2,36 +2,66 @@ import { attachTurnSpend, NaxError } from "@nathapp/nax-agent";
|
|
|
2
2
|
import { promptRequestError, rpcErrorOf, stopReasonError } from "#src/client/errors";
|
|
3
3
|
import { agentGoneError } from "#src/client/launch";
|
|
4
4
|
import { race } from "#src/client/race";
|
|
5
|
+
import { sumUsage, tokenUsageOf } from "#src/client/usage";
|
|
5
6
|
/** A turn that ended with no prompt response reports nothing it can price; its reading moves to the next turn. */
|
|
6
7
|
const NO_RESPONSE_SPEND = Object.freeze({
|
|
7
8
|
tokenUsage: Object.freeze({ inputTokens: 0, outputTokens: 0 }),
|
|
8
9
|
costUsd: 0,
|
|
9
10
|
costSource: "unpriced",
|
|
10
11
|
});
|
|
12
|
+
/** Follow-up prompts one turn may send after a deny made the agent cancel (nax#2582). */
|
|
13
|
+
export const MAX_DENIED_CONTINUATIONS = 2;
|
|
14
|
+
export const DENIED_CONTINUATION_PROMPT = "A permission request you made was denied by this session's permission policy, and the denial stopped your turn. " +
|
|
15
|
+
"Continue the same task without that action. Do not request that permission again; if the task cannot be " +
|
|
16
|
+
"finished without it, say so in your reply.";
|
|
11
17
|
export async function runPromptTurn(state, input) {
|
|
18
|
+
let text = input.text;
|
|
19
|
+
let carried;
|
|
20
|
+
for (let continuation = 0;; continuation += 1) {
|
|
21
|
+
const denialsBefore = input.collector.denials();
|
|
22
|
+
const response = await promptOnce(state, input, text, carried);
|
|
23
|
+
const usage = sumUsage(carried, response.usage);
|
|
24
|
+
const continueAfterDenial = response.stopReason === "cancelled" &&
|
|
25
|
+
!input.signal.aborted &&
|
|
26
|
+
input.collector.denials() > denialsBefore &&
|
|
27
|
+
continuation < MAX_DENIED_CONTINUATIONS;
|
|
28
|
+
if (!continueAfterDenial)
|
|
29
|
+
return resultOf({ ...response, usage }, input.collector, continuation + 1);
|
|
30
|
+
carried = usage;
|
|
31
|
+
text = DENIED_CONTINUATION_PROMPT;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* One session/prompt. A failed request throws with the tokens of the prompts this turn
|
|
36
|
+
* already answered and no cost (the cost reading moves to the next turn); an abort
|
|
37
|
+
* throws with the spend of every prompt this turn answered.
|
|
38
|
+
*/
|
|
39
|
+
async function promptOnce(state, input, text, carried) {
|
|
12
40
|
const pending = state.link.prompt({
|
|
13
41
|
sessionId: state.agentSessionId,
|
|
14
|
-
prompt: [{ type: "text", text
|
|
42
|
+
prompt: [{ type: "text", text }],
|
|
15
43
|
});
|
|
16
44
|
const outcome = await race(pending, { signal: input.signal });
|
|
17
45
|
switch (outcome.kind) {
|
|
18
46
|
case "ok":
|
|
19
|
-
return
|
|
47
|
+
return outcome.value;
|
|
20
48
|
case "failed": {
|
|
21
49
|
const error = await promptFailure(state, outcome.error);
|
|
22
|
-
attachTurnSpend(error, NO_RESPONSE_SPEND);
|
|
50
|
+
attachTurnSpend(error, carried === undefined ? NO_RESPONSE_SPEND : { ...NO_RESPONSE_SPEND, tokenUsage: tokenUsageOf(carried) });
|
|
23
51
|
throw error;
|
|
24
52
|
}
|
|
25
53
|
default: {
|
|
26
54
|
const response = await cancelTurn(state, pending);
|
|
27
55
|
const reason = abortReason(input.signal);
|
|
28
56
|
// #2367: an answer inside the grace still reports what the turn spent.
|
|
29
|
-
attachTurnSpend(reason, response === undefined
|
|
57
|
+
attachTurnSpend(reason, response === undefined
|
|
58
|
+
? NO_RESPONSE_SPEND
|
|
59
|
+
: input.collector.settle({ ...response, usage: sumUsage(carried, response.usage) }));
|
|
30
60
|
throw reason;
|
|
31
61
|
}
|
|
32
62
|
}
|
|
33
63
|
}
|
|
34
|
-
function resultOf(response, collector) {
|
|
64
|
+
function resultOf(response, collector, prompts) {
|
|
35
65
|
const spend = collector.settle(response);
|
|
36
66
|
if (response.stopReason !== "end_turn") {
|
|
37
67
|
const error = stopReasonError(String(response.stopReason));
|
|
@@ -43,7 +73,7 @@ function resultOf(response, collector) {
|
|
|
43
73
|
tokenUsage: spend.tokenUsage,
|
|
44
74
|
estimatedCostUsd: spend.costUsd,
|
|
45
75
|
costSource: spend.costSource,
|
|
46
|
-
internalRoundTrips:
|
|
76
|
+
internalRoundTrips: prompts,
|
|
47
77
|
};
|
|
48
78
|
}
|
|
49
79
|
async function promptFailure(state, error) {
|
package/dist/client/usage.d.ts
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
* the agent's counter restarted, so the raw reading is the turn's cost. No reading:
|
|
11
11
|
* costUsd 0, "unpriced", baseline kept.
|
|
12
12
|
*/
|
|
13
|
-
import type { PromptResponse } from "@agentclientprotocol/sdk";
|
|
13
|
+
import type { PromptResponse, Usage } from "@agentclientprotocol/sdk";
|
|
14
14
|
import type { TokenUsage, TurnEvent } from "@nathapp/nax-agent";
|
|
15
15
|
export interface TurnCost {
|
|
16
16
|
readonly costUsd: number;
|
|
@@ -32,5 +32,7 @@ export interface CostMeter {
|
|
|
32
32
|
export declare function tokenUsageOf(usage: unknown): TokenUsage;
|
|
33
33
|
/** `initialBaseline`: the stored reading of a resumed session; anything but a finite, non-negative number is 0. */
|
|
34
34
|
export declare function createCostMeter(initialBaseline?: number): CostMeter;
|
|
35
|
+
/** Two prompts' ACP usage as one (nax#2582): each count summed; a count neither reports stays absent. */
|
|
36
|
+
export declare function sumUsage(first: unknown, second: unknown): Usage | undefined;
|
|
35
37
|
export declare function turnSpend(response: PromptResponse, meter: CostMeter): TurnSpend;
|
|
36
38
|
export declare function usageEvent(spend: TurnSpend): TurnEvent;
|
package/dist/client/usage.js
CHANGED
|
@@ -47,6 +47,29 @@ export function createCostMeter(initialBaseline = 0) {
|
|
|
47
47
|
baseline: () => baseline,
|
|
48
48
|
};
|
|
49
49
|
}
|
|
50
|
+
const USAGE_COUNTS = [
|
|
51
|
+
"totalTokens",
|
|
52
|
+
"inputTokens",
|
|
53
|
+
"outputTokens",
|
|
54
|
+
"thoughtTokens",
|
|
55
|
+
"cachedReadTokens",
|
|
56
|
+
"cachedWriteTokens",
|
|
57
|
+
];
|
|
58
|
+
/** Two prompts' ACP usage as one (nax#2582): each count summed; a count neither reports stays absent. */
|
|
59
|
+
export function sumUsage(first, second) {
|
|
60
|
+
if (!isRecord(first))
|
|
61
|
+
return isRecord(second) ? second : undefined;
|
|
62
|
+
if (!isRecord(second))
|
|
63
|
+
return first;
|
|
64
|
+
const sum = {};
|
|
65
|
+
for (const key of USAGE_COUNTS) {
|
|
66
|
+
const a = count(first[key]);
|
|
67
|
+
const b = count(second[key]);
|
|
68
|
+
if (a !== undefined || b !== undefined)
|
|
69
|
+
sum[key] = (a ?? 0) + (b ?? 0);
|
|
70
|
+
}
|
|
71
|
+
return sum;
|
|
72
|
+
}
|
|
50
73
|
export function turnSpend(response, meter) {
|
|
51
74
|
return { tokenUsage: tokenUsageOf(response.usage), ...meter.settle() };
|
|
52
75
|
}
|
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.1",
|
|
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.1"
|
|
53
53
|
},
|
|
54
54
|
"publishConfig": {
|
|
55
55
|
"access": "public",
|