@nathapp/nax-agent-acp 0.90.0 → 0.90.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +29 -0
- package/README.md +3 -1
- package/dist/client/backend.js +30 -6
- package/dist/client/capabilities.d.ts +35 -2
- package/dist/client/capabilities.js +61 -4
- package/dist/client/connection.d.ts +10 -1
- package/dist/client/connection.js +4 -0
- 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 +13 -0
- package/dist/client/events.js +34 -3
- 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.d.ts +2 -0
- package/dist/client/open.js +82 -34
- package/dist/client/opencode-sandbox.d.ts +15 -0
- package/dist/client/opencode-sandbox.js +94 -0
- package/dist/client/options.d.ts +38 -0
- package/dist/client/options.js +54 -2
- package/dist/client/permissions.d.ts +25 -1
- package/dist/client/permissions.js +79 -12
- package/dist/client/pi-sandbox.d.ts +2 -0
- package/dist/client/pi-sandbox.js +22 -0
- package/dist/client/policy-files.d.ts +21 -0
- package/dist/client/policy-files.js +73 -0
- package/dist/client/registry.d.ts +33 -9
- package/dist/client/registry.js +130 -9
- package/dist/client/resume.d.ts +5 -3
- package/dist/client/resume.js +3 -2
- package/dist/client/rule-policy.d.ts +55 -0
- package/dist/client/rule-policy.js +181 -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 +22 -0
- package/dist/client/shell-rules.js +134 -0
- 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.d.ts +3 -0
- package/dist/client/turn.js +40 -9
- package/dist/client/usage.d.ts +3 -1
- package/dist/client/usage.js +23 -0
- package/package.json +2 -2
|
@@ -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,22 @@
|
|
|
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
|
+
/** 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";
|
|
6
|
+
/**
|
|
7
|
+
* The pi extension that gives pi a permission system (SPEC US-003): pi-acp hands
|
|
8
|
+
* the confirm prompt to nax as an ACP permission request, and nax answers it with
|
|
9
|
+
* the operator's Bash rules. `pi` has neither a read-only mode nor permission
|
|
10
|
+
* config, so this is its only enforcement path under `review`.
|
|
11
|
+
* US-004 writes this to disk; it is a plain module so pi can load it directly.
|
|
12
|
+
*/
|
|
13
|
+
export declare const PI_SHELL_GATE_SOURCE: string;
|
|
14
|
+
/**
|
|
15
|
+
* The shell command this tool call asks about, from the raw agent fields only
|
|
16
|
+
* (never the masked display text), or undefined when the call is not one.
|
|
17
|
+
*/
|
|
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;
|
|
21
|
+
/** "allow" only when the lexer read the whole command and every segment is allowed. */
|
|
22
|
+
export declare function shellRuleVerdict(command: string, rules: AcpPermissionRules): "allow" | "deny";
|
|
@@ -0,0 +1,134 @@
|
|
|
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
|
+
export 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
|
+
/** 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
|
+
}
|
|
128
|
+
/** "allow" only when the lexer read the whole command and every segment is allowed. */
|
|
129
|
+
export function shellRuleVerdict(command, rules) {
|
|
130
|
+
const lexed = lexBashCommand(command);
|
|
131
|
+
if (lexed.kind !== "ok" || lexed.segments.length === 0)
|
|
132
|
+
return "deny";
|
|
133
|
+
return lexed.segments.every((segment) => segmentAllowed(segment, rules)) ? "allow" : "deny";
|
|
134
|
+
}
|
|
@@ -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.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
|
@@ -1,40 +1,71 @@
|
|
|
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
|
+
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
|
-
|
|
37
|
-
|
|
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));
|
|
38
69
|
attachTurnSpend(error, spend);
|
|
39
70
|
throw error;
|
|
40
71
|
}
|
|
@@ -43,7 +74,7 @@ function resultOf(response, collector) {
|
|
|
43
74
|
tokenUsage: spend.tokenUsage,
|
|
44
75
|
estimatedCostUsd: spend.costUsd,
|
|
45
76
|
costSource: spend.costSource,
|
|
46
|
-
internalRoundTrips:
|
|
77
|
+
internalRoundTrips: prompts,
|
|
47
78
|
};
|
|
48
79
|
}
|
|
49
80
|
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.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",
|