@nathapp/nax-agent-acp 0.3.0 → 0.84.0
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 +33 -0
- package/README.md +117 -22
- package/bin/nax-agent.js +4 -0
- package/dist/client/backend.js +11 -2
- package/dist/client/capabilities.d.ts +9 -3
- package/dist/client/capabilities.js +26 -5
- package/dist/client/elicitation.d.ts +4 -2
- package/dist/client/elicitation.js +14 -1
- package/dist/client/errors.d.ts +9 -1
- package/dist/client/errors.js +19 -2
- package/dist/client/events.d.ts +5 -1
- package/dist/client/events.js +31 -2
- package/dist/client/index.d.ts +2 -1
- package/dist/client/index.js +1 -0
- package/dist/client/launchable.d.ts +4 -0
- package/dist/client/launchable.js +17 -0
- package/dist/client/open.js +75 -13
- package/dist/client/options.d.ts +11 -0
- package/dist/client/options.js +17 -3
- package/dist/client/permissions.d.ts +2 -2
- package/dist/client/pre-approval.d.ts +5 -13
- package/dist/client/pre-approval.js +3 -10
- package/dist/client/registry.d.ts +15 -2
- package/dist/client/registry.js +22 -2
- package/dist/client/tool-calls.js +0 -4
- package/dist/client/tool-events.d.ts +8 -1
- package/dist/client/tool-events.js +39 -6
- package/dist/client/turn.js +28 -8
- package/dist/server/auth.d.ts +45 -0
- package/dist/server/auth.js +87 -0
- package/dist/server/capabilities.d.ts +7 -0
- package/dist/server/capabilities.js +19 -0
- package/dist/server/cli.d.ts +26 -0
- package/dist/server/cli.js +87 -0
- package/dist/server/client-port.d.ts +39 -0
- package/dist/server/client-port.js +49 -0
- package/dist/server/connection.d.ts +22 -0
- package/dist/server/connection.js +56 -0
- package/dist/server/errors.d.ts +21 -0
- package/dist/server/errors.js +70 -0
- package/dist/server/index.d.ts +4 -3
- package/dist/server/index.js +6 -1
- package/dist/server/logger.d.ts +7 -0
- package/dist/server/logger.js +25 -0
- package/dist/server/login.d.ts +18 -0
- package/dist/server/login.js +29 -0
- package/dist/server/main.d.ts +19 -0
- package/dist/server/main.js +120 -0
- package/dist/server/nax-config.d.ts +30 -0
- package/dist/server/nax-config.js +138 -0
- package/dist/server/open-session.d.ts +37 -0
- package/dist/server/open-session.js +55 -0
- package/dist/server/options.d.ts +27 -0
- package/dist/server/options.js +55 -0
- package/dist/server/permissions.d.ts +44 -0
- package/dist/server/permissions.js +157 -0
- package/dist/server/process-entry.d.ts +15 -0
- package/dist/server/process-entry.js +28 -0
- package/dist/server/prompt.d.ts +8 -0
- package/dist/server/prompt.js +29 -0
- package/dist/server/questions.d.ts +33 -0
- package/dist/server/questions.js +79 -0
- package/dist/server/registry-open.d.ts +33 -0
- package/dist/server/registry-open.js +62 -0
- package/dist/server/registry.d.ts +64 -0
- package/dist/server/registry.js +262 -0
- package/dist/server/server-session.d.ts +43 -0
- package/dist/server/server-session.js +221 -0
- package/dist/server/session-config.d.ts +27 -0
- package/dist/server/session-config.js +93 -0
- package/dist/server/storage.d.ts +49 -0
- package/dist/server/storage.js +191 -0
- package/dist/server/translate/diff.d.ts +30 -0
- package/dist/server/translate/diff.js +81 -0
- package/dist/server/translate/events.d.ts +37 -0
- package/dist/server/translate/events.js +126 -0
- package/dist/server/translate/notice.d.ts +10 -0
- package/dist/server/translate/notice.js +14 -0
- package/dist/server/translate/replay.d.ts +11 -0
- package/dist/server/translate/replay.js +53 -0
- package/dist/server/translate/stop.d.ts +22 -0
- package/dist/server/translate/stop.js +48 -0
- package/dist/server/translate/tool-kind.d.ts +9 -0
- package/dist/server/translate/tool-kind.js +67 -0
- package/dist/server/version.d.ts +1 -0
- package/dist/server/version.js +17 -0
- package/package.json +6 -3
package/dist/client/open.js
CHANGED
|
@@ -12,14 +12,15 @@
|
|
|
12
12
|
* rejects AGENT_SESSION_CLOSED.
|
|
13
13
|
*/
|
|
14
14
|
import { PROTOCOL_VERSION } from "@agentclientprotocol/sdk";
|
|
15
|
-
import { NaxError } from "@nathapp/nax-agent";
|
|
16
|
-
import { buildCapabilityRecord, modeFor, modelOptionId, offersValue, unmetRequirement, } from "#src/client/capabilities";
|
|
15
|
+
import { getLogger, NaxError, } from "@nathapp/nax-agent";
|
|
16
|
+
import { buildCapabilityRecord, effortOptionId, modeFor, modelOptionId, offersValue, readOnlyFor, selectValues, unmetRequirement, } from "#src/client/capabilities";
|
|
17
17
|
import { openConnection } from "#src/client/connection";
|
|
18
18
|
import { backendUnavailable, capabilityUnsupported, closedDuringOpen, EXCERPT_BYTES, openRequestError, rpcErrorOf, } from "#src/client/errors";
|
|
19
19
|
import { agentGoneError, pickCandidate } from "#src/client/launch";
|
|
20
20
|
import { claudeSessionMeta } from "#src/client/pre-approval";
|
|
21
21
|
import { race } from "#src/client/race";
|
|
22
22
|
import { isUsableSessionId, restoreSession, } from "#src/client/resume";
|
|
23
|
+
import { cleanLabel } from "#src/client/text";
|
|
23
24
|
function chooseLaunch(options) {
|
|
24
25
|
if (options.launch.kind === "explicit")
|
|
25
26
|
return options.launch.candidate;
|
|
@@ -37,6 +38,7 @@ export async function openAcpSession(options, ctx, handlers, launch, host, resto
|
|
|
37
38
|
throw closedDuringOpen(ctx.sessionId);
|
|
38
39
|
const candidate = chooseLaunch(options);
|
|
39
40
|
const launched = launch({ command: candidate.command, args: candidate.args, cwd: ctx.workdir, env: options.env });
|
|
41
|
+
watchProcess(options.onProcess, launched);
|
|
40
42
|
const link = openConnection(launched.target, handlers);
|
|
41
43
|
void launched.exited.then(() => link.close(new NaxError("The ACP agent process exited", "ACP_AGENT_EXITED", { stage: "acp" })));
|
|
42
44
|
try {
|
|
@@ -48,6 +50,30 @@ export async function openAcpSession(options, ctx, handlers, launch, host, resto
|
|
|
48
50
|
throw err;
|
|
49
51
|
}
|
|
50
52
|
}
|
|
53
|
+
/** S4b spec §8: report the agent process to the embedder; a throwing hook is logged, never propagated. */
|
|
54
|
+
function watchProcess(hooks, launched) {
|
|
55
|
+
const pid = launched.pid;
|
|
56
|
+
if (hooks === undefined || pid === undefined)
|
|
57
|
+
return;
|
|
58
|
+
const ignored = (name) => (err) => {
|
|
59
|
+
getLogger().warn("acp", `onProcess.${name} threw; ignored`, {
|
|
60
|
+
error: err instanceof Error ? err.message : String(err),
|
|
61
|
+
});
|
|
62
|
+
};
|
|
63
|
+
const call = (name) => {
|
|
64
|
+
try {
|
|
65
|
+
// An async hook's rejection is caught too; the hook is typed void, but async functions satisfy it.
|
|
66
|
+
const result = hooks[name]?.(pid);
|
|
67
|
+
if (result instanceof Promise)
|
|
68
|
+
result.catch(ignored(name));
|
|
69
|
+
}
|
|
70
|
+
catch (err) {
|
|
71
|
+
ignored(name)(err);
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
call("spawned");
|
|
75
|
+
void launched.exited.then(() => call("exited"));
|
|
76
|
+
}
|
|
51
77
|
async function step(o, label, request) {
|
|
52
78
|
const result = await race(request, { timeoutMs: o.options.initializeTimeoutMs, signal: o.ctx.openSignal });
|
|
53
79
|
switch (result.kind) {
|
|
@@ -111,7 +137,7 @@ async function newSession(o, setup) {
|
|
|
111
137
|
/** §6.3 step 3: start the tool host when the session has tools; its entry and Claude's `_meta` (§6.6, #2365). */
|
|
112
138
|
async function sessionSetup(o) {
|
|
113
139
|
const kind = o.options.entry?.preApproval;
|
|
114
|
-
const meta = claudeSessionMeta(kind, o.ctx.tools.map((tool) => tool.name), o.ctx.profile);
|
|
140
|
+
const meta = claudeSessionMeta(kind, o.ctx.tools.map((tool) => tool.name), readOnlyFor(o.ctx.profile, o.options.entry));
|
|
115
141
|
if (o.host === undefined)
|
|
116
142
|
return meta === undefined ? { mcpServers: [] } : { mcpServers: [], _meta: { ...meta } };
|
|
117
143
|
if (meta === undefined)
|
|
@@ -121,23 +147,59 @@ async function sessionSetup(o) {
|
|
|
121
147
|
});
|
|
122
148
|
return { mcpServers: [server], _meta: { ...meta } };
|
|
123
149
|
}
|
|
124
|
-
/** §6.3 step 5: the profile's mode, then the model. Only values the agent offered are set. */
|
|
150
|
+
/** §6.3 step 5: the profile's mode, then the model, then the effort (S4b). Only values the agent offered are set. */
|
|
125
151
|
async function applyConfig(o, sessionId, offered) {
|
|
152
|
+
const afterMode = await applyMode(o, sessionId, offered);
|
|
153
|
+
const afterModel = await applyModel(o, sessionId, afterMode);
|
|
154
|
+
await applyEffort(o, sessionId, afterModel);
|
|
155
|
+
}
|
|
156
|
+
async function applyMode(o, sessionId, offered) {
|
|
126
157
|
const mode = modeFor(o.ctx.profile, o.options.entry);
|
|
127
|
-
if (mode
|
|
158
|
+
if (mode === undefined)
|
|
159
|
+
return offered;
|
|
160
|
+
if (!offersValue(offered, mode.configId, mode.value)) {
|
|
128
161
|
throw capabilityUnsupported("profile", `the agent does not offer ${mode.configId} "${mode.value}"`);
|
|
129
162
|
}
|
|
130
|
-
const
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
163
|
+
const set = await step(o, "session/set_config_option", o.link.setConfigOption({ sessionId, ...mode }));
|
|
164
|
+
return set.configOptions ?? offered;
|
|
165
|
+
}
|
|
166
|
+
/** At most this many offered ids, each cleaned and capped, go into a model refusal (agent-supplied text). */
|
|
167
|
+
const MAX_OFFERED_MODELS = 50;
|
|
168
|
+
const MAX_MODEL_ID_CHARS = 100;
|
|
169
|
+
function offeredModels(offered, secrets) {
|
|
170
|
+
return offered
|
|
171
|
+
.filter((option) => option.category === "model")
|
|
172
|
+
.flatMap((option) => selectValues(option))
|
|
173
|
+
.slice(0, MAX_OFFERED_MODELS)
|
|
174
|
+
.map((id) => cleanLabel(id, secrets, MAX_MODEL_ID_CHARS) ?? "")
|
|
175
|
+
.filter((id) => id !== "");
|
|
176
|
+
}
|
|
177
|
+
async function applyModel(o, sessionId, offered) {
|
|
134
178
|
const model = o.options.model;
|
|
135
179
|
if (model === undefined)
|
|
180
|
+
return offered;
|
|
181
|
+
const configId = modelOptionId(offered, model);
|
|
182
|
+
if (configId === undefined) {
|
|
183
|
+
const ids = offeredModels(offered, o.options.secrets);
|
|
184
|
+
throw capabilityUnsupported("model", `the agent offers no model option "${model}"; offered: ${ids.length === 0 ? "(none)" : ids.join(", ")}`, { offered: ids });
|
|
185
|
+
}
|
|
186
|
+
const set = await step(o, "session/set_config_option", o.link.setConfigOption({ sessionId, configId, value: model }));
|
|
187
|
+
return set.configOptions ?? offered;
|
|
188
|
+
}
|
|
189
|
+
/** S4b spec §6.7: an effort the agent does not offer is skipped with a warning, as acpx does. */
|
|
190
|
+
async function applyEffort(o, sessionId, offered) {
|
|
191
|
+
const effort = o.options.effort;
|
|
192
|
+
if (effort === undefined)
|
|
136
193
|
return;
|
|
137
|
-
const configId =
|
|
138
|
-
if (configId === undefined)
|
|
139
|
-
|
|
140
|
-
|
|
194
|
+
const configId = effortOptionId(offered, o.options.agentName, effort);
|
|
195
|
+
if (configId === undefined) {
|
|
196
|
+
getLogger().warn("acp", "The agent offers no effort option for this value; effort skipped", {
|
|
197
|
+
agent: o.options.agentName,
|
|
198
|
+
effort,
|
|
199
|
+
});
|
|
200
|
+
return;
|
|
201
|
+
}
|
|
202
|
+
await step(o, "session/set_config_option", o.link.setConfigOption({ sessionId, configId, value: effort }));
|
|
141
203
|
}
|
|
142
204
|
function initialDoc(o, record, agentSessionId) {
|
|
143
205
|
return {
|
package/dist/client/options.d.ts
CHANGED
|
@@ -6,12 +6,19 @@ export type AcpAgentSpec = AcpAgentName | {
|
|
|
6
6
|
readonly command: string;
|
|
7
7
|
readonly args?: readonly string[];
|
|
8
8
|
};
|
|
9
|
+
/** Called for every agent process the backend spawns, including a reconnect's (S4b spec §8). Errors are logged and ignored. */
|
|
10
|
+
export interface AcpProcessHooks {
|
|
11
|
+
spawned?(pid: number): void;
|
|
12
|
+
exited?(pid: number): void;
|
|
13
|
+
}
|
|
9
14
|
export interface AcpBackendOptions {
|
|
10
15
|
readonly agent: AcpAgentSpec;
|
|
11
16
|
/** Required: the agent process runs on the host, unsandboxed (R7). */
|
|
12
17
|
readonly allowUnsandboxed: true;
|
|
13
18
|
/** Applied via session/set_config_option (category "model") before open returns. */
|
|
14
19
|
readonly model?: string;
|
|
20
|
+
/** Reasoning effort, set via session/set_config_option after the model (S4b spec 8). Skipped when not offered. */
|
|
21
|
+
readonly effort?: string;
|
|
15
22
|
/** Added to the agent's environment. */
|
|
16
23
|
readonly env?: Readonly<Record<string, string>>;
|
|
17
24
|
/** Default false: the allowlist only. true hands the whole process.env to the agent. */
|
|
@@ -21,6 +28,8 @@ export interface AcpBackendOptions {
|
|
|
21
28
|
readonly args?: readonly string[];
|
|
22
29
|
readonly cancelGraceMs?: number;
|
|
23
30
|
readonly initializeTimeoutMs?: number;
|
|
31
|
+
/** Called with the pid of every agent process, including after a reconnect. Not called when the spawn fails. */
|
|
32
|
+
readonly onProcess?: AcpProcessHooks;
|
|
24
33
|
}
|
|
25
34
|
export type AcpLaunch = {
|
|
26
35
|
readonly kind: "explicit";
|
|
@@ -37,10 +46,12 @@ export interface ResolvedAcpOptions {
|
|
|
37
46
|
readonly entry: AgentRegistryEntry | undefined;
|
|
38
47
|
readonly launch: AcpLaunch;
|
|
39
48
|
readonly model: string | undefined;
|
|
49
|
+
readonly effort: string | undefined;
|
|
40
50
|
readonly env: Readonly<Record<string, string>>;
|
|
41
51
|
/** Values redacted from every agent excerpt (D-g). */
|
|
42
52
|
readonly secrets: readonly string[];
|
|
43
53
|
readonly cancelGraceMs: number;
|
|
44
54
|
readonly initializeTimeoutMs: number;
|
|
55
|
+
readonly onProcess: AcpProcessHooks | undefined;
|
|
45
56
|
}
|
|
46
57
|
export declare function resolveAcpOptions(input: unknown, source?: Readonly<Record<string, string | undefined>>): ResolvedAcpOptions;
|
package/dist/client/options.js
CHANGED
|
@@ -30,6 +30,7 @@ const SCHEMA = z
|
|
|
30
30
|
agent: z.union([z.enum(["claude", "codex", "gemini", "opencode", "pi"]), customAgent]),
|
|
31
31
|
allowUnsandboxed: z.literal(true),
|
|
32
32
|
model: z.string().min(1).optional(),
|
|
33
|
+
effort: z.string().min(1).optional(),
|
|
33
34
|
env: z.record(z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/), plain).optional(),
|
|
34
35
|
inheritEnv: z.boolean().optional(),
|
|
35
36
|
command: command.optional(),
|
|
@@ -56,7 +57,13 @@ function launchOf(data, entry) {
|
|
|
56
57
|
}
|
|
57
58
|
return { kind: "registry", candidates: entry?.launch ?? [] };
|
|
58
59
|
}
|
|
59
|
-
function
|
|
60
|
+
function isProcessHooks(value) {
|
|
61
|
+
if (!isRecord(value))
|
|
62
|
+
return false;
|
|
63
|
+
const fnOrAbsent = (v) => v === undefined || typeof v === "function";
|
|
64
|
+
return fnOrAbsent(value.spawned) && fnOrAbsent(value.exited);
|
|
65
|
+
}
|
|
66
|
+
function resolved(data, source, onProcess) {
|
|
60
67
|
const agentName = typeof data.agent === "string" ? data.agent : data.agent.name;
|
|
61
68
|
const entry = typeof data.agent === "string" ? registryEntry(data.agent) : undefined;
|
|
62
69
|
const env = buildAgentEnv({
|
|
@@ -71,21 +78,28 @@ function resolved(data, source) {
|
|
|
71
78
|
entry,
|
|
72
79
|
launch: launchOf(data, entry),
|
|
73
80
|
model: data.model,
|
|
81
|
+
effort: data.effort,
|
|
74
82
|
env: Object.freeze(env),
|
|
75
83
|
secrets: Object.freeze([...secretValues(env)]),
|
|
76
84
|
cancelGraceMs: data.cancelGraceMs ?? DEFAULT_CANCEL_GRACE_MS,
|
|
77
85
|
initializeTimeoutMs: data.initializeTimeoutMs ?? DEFAULT_INITIALIZE_TIMEOUT_MS,
|
|
86
|
+
onProcess,
|
|
78
87
|
});
|
|
79
88
|
}
|
|
80
89
|
export function resolveAcpOptions(input, source = process.env) {
|
|
81
90
|
if (!isRecord(input) || input.allowUnsandboxed !== true) {
|
|
82
91
|
throw new AgentSessionError("acpBackend requires allowUnsandboxed: true: the agent process runs on the host, unsandboxed", "AGENT_SESSION_SANDBOX_UNAVAILABLE", { path: "allowUnsandboxed" });
|
|
83
92
|
}
|
|
84
|
-
|
|
93
|
+
// Functions are checked by hand: the zod schema validates plain data only.
|
|
94
|
+
const { onProcess, ...rest } = input;
|
|
95
|
+
if (onProcess !== undefined && !isProcessHooks(onProcess)) {
|
|
96
|
+
throw new AgentSessionError("Invalid acpBackend options: onProcess: spawned and exited must be functions", "AGENT_SESSION_INVALID_OPTIONS", { path: "onProcess" });
|
|
97
|
+
}
|
|
98
|
+
const parsed = SCHEMA.safeParse(rest);
|
|
85
99
|
if (!parsed.success) {
|
|
86
100
|
const issue = parsed.error.issues[0];
|
|
87
101
|
const path = issue === undefined ? "" : issue.path.map(String).join(".");
|
|
88
102
|
throw new AgentSessionError(`Invalid acpBackend options: ${path === "" ? "(options)" : path}: ${issue?.message ?? "invalid"}`, "AGENT_SESSION_INVALID_OPTIONS", { path });
|
|
89
103
|
}
|
|
90
|
-
return resolved(parsed.data, source);
|
|
104
|
+
return resolved(parsed.data, source, onProcess);
|
|
91
105
|
}
|
|
@@ -5,8 +5,8 @@
|
|
|
5
5
|
* and only the *_once kinds: allow_always would outlive the session. Auto-decisions
|
|
6
6
|
* are recorded with decidedBy "profile". Fail closed: a deny or deadline answers
|
|
7
7
|
* reject_once; a turn abort, process death or ask-port failure answers
|
|
8
|
-
* `cancelled`. Embedder tools are pre-approved at the adapter (S4-4)
|
|
9
|
-
*
|
|
8
|
+
* `cancelled`. Embedder tools are pre-approved at the adapter (S4-4), so they are
|
|
9
|
+
* normally never asked about; if an agent asks anyway, the request is decided
|
|
10
10
|
* like any other, because its title is display data (S4-4 D4-c).
|
|
11
11
|
*/
|
|
12
12
|
import type { RequestPermissionRequest, RequestPermissionResponse } from "@agentclientprotocol/sdk";
|
|
@@ -5,20 +5,12 @@
|
|
|
5
5
|
* `allowedTools` rules allow a tool without a permission request. One exact rule
|
|
6
6
|
* per tool, `mcp__nax__<tool>`, so only the session's own tools are allowed. Tool
|
|
7
7
|
* names are already restricted by the facade, so a rule never needs escaping.
|
|
8
|
-
*
|
|
9
|
-
*
|
|
8
|
+
* Under none/read the entry's read-only enforcement adds the removed tools and its
|
|
9
|
+
* session options (#2366).
|
|
10
10
|
*/
|
|
11
|
-
import type {
|
|
12
|
-
import type { AgentRegistryEntry } from "#src/client/registry";
|
|
11
|
+
import type { AgentRegistryEntry, ReadOnlyEnforcement } from "#src/client/registry";
|
|
13
12
|
/** The ACP MCP server name; the agent sees the tools as `mcp__nax__<tool>`. */
|
|
14
13
|
export declare const TOOL_HOST_SERVER_NAME = "nax";
|
|
15
14
|
export declare function mcpToolRule(toolName: string): string;
|
|
16
|
-
/**
|
|
17
|
-
|
|
18
|
-
* something in plan mode, Claude calls ExitPlanMode; the adapter turns its reject into
|
|
19
|
-
* an interrupt, so the turn ended ACP_STOP_CANCELLED instead of meeting the profile's
|
|
20
|
-
* refusal. Without it Claude reaches for Write or Edit, which layer 2 rejects.
|
|
21
|
-
*/
|
|
22
|
-
export declare const READ_ONLY_DISALLOWED_TOOLS: readonly string[];
|
|
23
|
-
/** The session/new, resume and load `_meta` for Claude: tool rules and the read-only lock; undefined when empty. */
|
|
24
|
-
export declare function claudeSessionMeta(kind: AgentRegistryEntry["preApproval"], toolNames: readonly string[], profile: AgentSessionProfile): Readonly<Record<string, unknown>> | undefined;
|
|
15
|
+
/** The session/new, resume and load `_meta` for Claude: tool rules and the read-only enforcement; undefined when empty. */
|
|
16
|
+
export declare function claudeSessionMeta(kind: AgentRegistryEntry["preApproval"], toolNames: readonly string[], readOnly: ReadOnlyEnforcement | undefined): Readonly<Record<string, unknown>> | undefined;
|
|
@@ -3,20 +3,13 @@ export const TOOL_HOST_SERVER_NAME = "nax";
|
|
|
3
3
|
export function mcpToolRule(toolName) {
|
|
4
4
|
return `mcp__${TOOL_HOST_SERVER_NAME}__${toolName}`;
|
|
5
5
|
}
|
|
6
|
-
/**
|
|
7
|
-
|
|
8
|
-
* something in plan mode, Claude calls ExitPlanMode; the adapter turns its reject into
|
|
9
|
-
* an interrupt, so the turn ended ACP_STOP_CANCELLED instead of meeting the profile's
|
|
10
|
-
* refusal. Without it Claude reaches for Write or Edit, which layer 2 rejects.
|
|
11
|
-
*/
|
|
12
|
-
export const READ_ONLY_DISALLOWED_TOOLS = Object.freeze(["ExitPlanMode"]);
|
|
13
|
-
/** The session/new, resume and load `_meta` for Claude: tool rules and the read-only lock; undefined when empty. */
|
|
14
|
-
export function claudeSessionMeta(kind, toolNames, profile) {
|
|
6
|
+
/** The session/new, resume and load `_meta` for Claude: tool rules and the read-only enforcement; undefined when empty. */
|
|
7
|
+
export function claudeSessionMeta(kind, toolNames, readOnly) {
|
|
15
8
|
if (kind !== "claudeCode.allowedTools")
|
|
16
9
|
return undefined;
|
|
17
10
|
const options = {
|
|
18
11
|
...(toolNames.length === 0 ? {} : { allowedTools: toolNames.map(mcpToolRule) }),
|
|
19
|
-
...(
|
|
12
|
+
...(readOnly === undefined ? {} : { disallowedTools: [...readOnly.disallowedTools], ...readOnly.sessionOptions }),
|
|
20
13
|
};
|
|
21
14
|
return Object.keys(options).length === 0 ? undefined : { claudeCode: { options } };
|
|
22
15
|
}
|
|
@@ -16,12 +16,25 @@ export interface ModeSetting {
|
|
|
16
16
|
readonly configId: string;
|
|
17
17
|
readonly value: string;
|
|
18
18
|
}
|
|
19
|
+
/**
|
|
20
|
+
* How profiles none and read are enforced on this agent (§6.4 layer 1, as revised
|
|
21
|
+
* by the 2026-10-07 fix bundle). Applied through the agent's pre-approval channel,
|
|
22
|
+
* so only an agent with one may declare it.
|
|
23
|
+
*/
|
|
24
|
+
export interface ReadOnlyEnforcement {
|
|
25
|
+
/** The mode set for none/read. */
|
|
26
|
+
readonly mode: ModeSetting;
|
|
27
|
+
/** Agent tools removed from the session under none/read. */
|
|
28
|
+
readonly disallowedTools: readonly string[];
|
|
29
|
+
/** Extra agent options under none/read, merged into the pre-approval channel's options. */
|
|
30
|
+
readonly sessionOptions: Readonly<Record<string, unknown>>;
|
|
31
|
+
}
|
|
19
32
|
export interface AgentRegistryEntry {
|
|
20
33
|
readonly name: AcpAgentName;
|
|
21
34
|
/** Tried in order; the first command found wins (S4-2 launch). */
|
|
22
35
|
readonly launch: readonly LaunchCandidate[];
|
|
23
|
-
/**
|
|
24
|
-
readonly
|
|
36
|
+
/** How profiles `none` and `read` are enforced; undefined means those profiles are unsupported (§6.4). */
|
|
37
|
+
readonly readOnly: ReadOnlyEnforcement | undefined;
|
|
25
38
|
/** Mode for profiles `ask` and `full`; undefined means the agent's own default is kept. */
|
|
26
39
|
readonly defaultMode: ModeSetting | undefined;
|
|
27
40
|
/** How embedder tools are pre-approved at the adapter (R12); undefined means tools are unsupported. */
|
package/dist/client/registry.js
CHANGED
|
@@ -8,11 +8,24 @@
|
|
|
8
8
|
*/
|
|
9
9
|
const local = (command, ...args) => ({ command, args });
|
|
10
10
|
const npx = (spec) => ({ command: "npx", args: ["-y", spec] });
|
|
11
|
+
function freezeReadOnly(readOnly) {
|
|
12
|
+
if (readOnly === undefined)
|
|
13
|
+
return undefined;
|
|
14
|
+
const options = Object.entries(readOnly.sessionOptions).map(([key, value]) => [
|
|
15
|
+
key,
|
|
16
|
+
Array.isArray(value) ? Object.freeze([...value]) : value,
|
|
17
|
+
]);
|
|
18
|
+
return Object.freeze({
|
|
19
|
+
mode: Object.freeze({ ...readOnly.mode }),
|
|
20
|
+
disallowedTools: Object.freeze([...readOnly.disallowedTools]),
|
|
21
|
+
sessionOptions: Object.freeze(Object.fromEntries(options)),
|
|
22
|
+
});
|
|
23
|
+
}
|
|
11
24
|
function entry(name, launch, authEnv, claude) {
|
|
12
25
|
return Object.freeze({
|
|
13
26
|
name,
|
|
14
27
|
launch: Object.freeze(launch.map((c) => Object.freeze({ command: c.command, args: Object.freeze([...c.args]) }))),
|
|
15
|
-
|
|
28
|
+
readOnly: freezeReadOnly(claude?.readOnly),
|
|
16
29
|
defaultMode: claude?.defaultMode === undefined ? undefined : Object.freeze({ ...claude.defaultMode }),
|
|
17
30
|
preApproval: claude?.preApproval,
|
|
18
31
|
authEnv: Object.freeze([...authEnv]),
|
|
@@ -22,7 +35,14 @@ const REGISTRY = new Map([
|
|
|
22
35
|
[
|
|
23
36
|
"claude",
|
|
24
37
|
entry("claude", [local("claude-agent-acp"), npx("@agentclientprotocol/claude-agent-acp@~0.85.1")], ["ANTHROPIC_API_KEY", "CLAUDE_CODE_OAUTH_TOKEN"], {
|
|
25
|
-
|
|
38
|
+
// #2366: no plan mode (it wrote its plan file without asking). The write tools are
|
|
39
|
+
// removed instead, and no Claude settings file loads: their allow rules, hooks and
|
|
40
|
+
// MCP servers act without a permission request.
|
|
41
|
+
readOnly: {
|
|
42
|
+
mode: { configId: "mode", value: "default" },
|
|
43
|
+
disallowedTools: ["Write", "Edit", "MultiEdit", "NotebookEdit", "EnterPlanMode"],
|
|
44
|
+
sessionOptions: { settingSources: [], allowDangerouslySkipPermissions: false },
|
|
45
|
+
},
|
|
26
46
|
defaultMode: { configId: "mode", value: "default" },
|
|
27
47
|
preApproval: "claudeCode.allowedTools",
|
|
28
48
|
}),
|
|
@@ -116,10 +116,6 @@ export function createToolCalls(deps) {
|
|
|
116
116
|
name: tool.name,
|
|
117
117
|
description: tool.description,
|
|
118
118
|
inputSchema: { ...tool.inputSchema, type: "object" },
|
|
119
|
-
// #2365: this host is the tools' only approval point. Claude's plan mode
|
|
120
|
-
// (profiles none/read) asks before any MCP tool not marked read-only,
|
|
121
|
-
// ahead of the mcp__nax__<tool> pre-approval.
|
|
122
|
-
annotations: { readOnlyHint: true },
|
|
123
119
|
})),
|
|
124
120
|
async call(name, args, requestSignal) {
|
|
125
121
|
const tool = byName.get(name);
|
|
@@ -32,4 +32,11 @@ export declare function previewOf(call: {
|
|
|
32
32
|
readonly content?: unknown;
|
|
33
33
|
readonly rawOutput?: unknown;
|
|
34
34
|
}, secrets: readonly string[]): string;
|
|
35
|
-
|
|
35
|
+
/** UTF-8 byte length of the full result text, before any cap (S4b spec §7.4). */
|
|
36
|
+
export declare function resultBytesOf(call: {
|
|
37
|
+
readonly content?: unknown;
|
|
38
|
+
readonly rawOutput?: unknown;
|
|
39
|
+
}): number;
|
|
40
|
+
/** At most one tool_progress per call per this interval (S4b-0 finding f). */
|
|
41
|
+
export declare const TOOL_PROGRESS_MIN_INTERVAL_MS = 30000;
|
|
42
|
+
export declare function createToolEvents(emit: (event: TurnEvent) => void, secrets: readonly string[], now?: () => number): ToolEvents;
|
|
@@ -120,11 +120,34 @@ export function previewOf(call, secrets) {
|
|
|
120
120
|
const visible = stripInvisible(stripControl(capBytes(raw, REDACTION_SCAN_BYTES)));
|
|
121
121
|
return capBytes(redactSecrets(scrubSecrets(visible, secrets)), TOOL_RESULT_PREVIEW_BYTES);
|
|
122
122
|
}
|
|
123
|
+
const UTF8 = new TextEncoder();
|
|
124
|
+
/** UTF-8 byte length of the full result text, before any cap (S4b spec §7.4). */
|
|
125
|
+
export function resultBytesOf(call) {
|
|
126
|
+
const fromContent = contentText(call.content);
|
|
127
|
+
const raw = fromContent !== "" ? fromContent : typeof call.rawOutput === "string" ? call.rawOutput : "";
|
|
128
|
+
return UTF8.encode(raw).byteLength;
|
|
129
|
+
}
|
|
130
|
+
/** At most one tool_progress per call per this interval (S4b-0 finding f). */
|
|
131
|
+
export const TOOL_PROGRESS_MIN_INTERVAL_MS = 30_000;
|
|
123
132
|
function isStarted(status) {
|
|
124
133
|
return status === "in_progress" || status === "completed" || status === "failed";
|
|
125
134
|
}
|
|
126
|
-
export function createToolEvents(emit, secrets) {
|
|
135
|
+
export function createToolEvents(emit, secrets, now = Date.now) {
|
|
127
136
|
const calls = new Map();
|
|
137
|
+
const lastBeat = new Map();
|
|
138
|
+
/** Calls whose tool has started (their first in_progress); only these send liveness beats. */
|
|
139
|
+
const running = new Set();
|
|
140
|
+
/** A non-terminal update on a running call: a throttled liveness beat (the agent's heartbeat). */
|
|
141
|
+
const beat = (state) => {
|
|
142
|
+
if (!running.has(state.id) || state.resolved)
|
|
143
|
+
return;
|
|
144
|
+
const at = now();
|
|
145
|
+
const last = lastBeat.get(state.id);
|
|
146
|
+
if (last !== undefined && at - last < TOOL_PROGRESS_MIN_INTERVAL_MS)
|
|
147
|
+
return;
|
|
148
|
+
lastBeat.set(state.id, at);
|
|
149
|
+
emit({ type: "tool_progress", callId: state.id });
|
|
150
|
+
};
|
|
128
151
|
const merge = (update) => {
|
|
129
152
|
if (!isRecord(update))
|
|
130
153
|
return undefined;
|
|
@@ -146,21 +169,31 @@ export function createToolEvents(emit, secrets) {
|
|
|
146
169
|
emit({ type: "tool_call", callId: state.id, name: nameOf(state), input: inputOf(state.rawInput, secrets) });
|
|
147
170
|
return next;
|
|
148
171
|
};
|
|
149
|
-
const resolve = (state, isError, preview) => {
|
|
172
|
+
const resolve = (state, isError, preview, resultBytes) => {
|
|
150
173
|
if (state.resolved)
|
|
151
174
|
return;
|
|
152
175
|
calls.set(state.id, { ...state, resolved: true });
|
|
153
|
-
|
|
176
|
+
lastBeat.delete(state.id);
|
|
177
|
+
running.delete(state.id);
|
|
178
|
+
emit({ type: "tool_result", callId: state.id, isError, preview, resultBytes });
|
|
154
179
|
};
|
|
155
180
|
return {
|
|
156
181
|
onUpdate(update) {
|
|
157
182
|
const state = merge(update);
|
|
158
183
|
const status = isRecord(update) ? update.status : undefined;
|
|
159
|
-
if (state === undefined
|
|
184
|
+
if (state === undefined)
|
|
185
|
+
return;
|
|
186
|
+
if (status === undefined || (status === "in_progress" && running.has(state.id))) {
|
|
187
|
+
beat(state);
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
if (!isStarted(status))
|
|
160
191
|
return;
|
|
192
|
+
if (status === "in_progress")
|
|
193
|
+
running.add(state.id);
|
|
161
194
|
const shown = announce(state);
|
|
162
195
|
if (status !== "in_progress")
|
|
163
|
-
resolve(shown, status === "failed", previewOf(shown, secrets));
|
|
196
|
+
resolve(shown, status === "failed", previewOf(shown, secrets), resultBytesOf(shown));
|
|
164
197
|
},
|
|
165
198
|
announce(toolCall) {
|
|
166
199
|
const state = merge(toolCall);
|
|
@@ -170,7 +203,7 @@ export function createToolEvents(emit, secrets) {
|
|
|
170
203
|
flush() {
|
|
171
204
|
for (const state of [...calls.values()]) {
|
|
172
205
|
if (state.announced)
|
|
173
|
-
resolve(state, true, UNANSWERED_PREVIEW);
|
|
206
|
+
resolve(state, true, UNANSWERED_PREVIEW, 0);
|
|
174
207
|
}
|
|
175
208
|
},
|
|
176
209
|
};
|
package/dist/client/turn.js
CHANGED
|
@@ -1,7 +1,13 @@
|
|
|
1
|
-
import { NaxError } from "@nathapp/nax-agent";
|
|
1
|
+
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
|
+
/** A turn that ended with no prompt response reports nothing it can price; its reading moves to the next turn. */
|
|
6
|
+
const NO_RESPONSE_SPEND = Object.freeze({
|
|
7
|
+
tokenUsage: Object.freeze({ inputTokens: 0, outputTokens: 0 }),
|
|
8
|
+
costUsd: 0,
|
|
9
|
+
costSource: "unpriced",
|
|
10
|
+
});
|
|
5
11
|
export async function runPromptTurn(state, input) {
|
|
6
12
|
const pending = state.link.prompt({
|
|
7
13
|
sessionId: state.agentSessionId,
|
|
@@ -11,17 +17,27 @@ export async function runPromptTurn(state, input) {
|
|
|
11
17
|
switch (outcome.kind) {
|
|
12
18
|
case "ok":
|
|
13
19
|
return resultOf(outcome.value, input.collector);
|
|
14
|
-
case "failed":
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
20
|
+
case "failed": {
|
|
21
|
+
const error = await promptFailure(state, outcome.error);
|
|
22
|
+
attachTurnSpend(error, NO_RESPONSE_SPEND);
|
|
23
|
+
throw error;
|
|
24
|
+
}
|
|
25
|
+
default: {
|
|
26
|
+
const response = await cancelTurn(state, pending);
|
|
27
|
+
const reason = abortReason(input.signal);
|
|
28
|
+
// #2367: an answer inside the grace still reports what the turn spent.
|
|
29
|
+
attachTurnSpend(reason, response === undefined ? NO_RESPONSE_SPEND : input.collector.settle(response));
|
|
30
|
+
throw reason;
|
|
31
|
+
}
|
|
19
32
|
}
|
|
20
33
|
}
|
|
21
34
|
function resultOf(response, collector) {
|
|
22
35
|
const spend = collector.settle(response);
|
|
23
|
-
if (response.stopReason !== "end_turn")
|
|
24
|
-
|
|
36
|
+
if (response.stopReason !== "end_turn") {
|
|
37
|
+
const error = stopReasonError(String(response.stopReason));
|
|
38
|
+
attachTurnSpend(error, spend);
|
|
39
|
+
throw error;
|
|
40
|
+
}
|
|
25
41
|
return {
|
|
26
42
|
output: collector.output(),
|
|
27
43
|
tokenUsage: spend.tokenUsage,
|
|
@@ -37,13 +53,17 @@ async function promptFailure(state, error) {
|
|
|
37
53
|
state.disconnect();
|
|
38
54
|
return agentGoneError("session/prompt", state.launched, state.secrets);
|
|
39
55
|
}
|
|
56
|
+
/** session/cancel, then cancelGraceMs for the prompt to answer; past that the process is killed. */
|
|
40
57
|
async function cancelTurn(state, pending) {
|
|
41
58
|
await state.link.cancel(state.agentSessionId).catch(() => undefined);
|
|
42
59
|
const settled = await race(pending, { timeoutMs: state.cancelGraceMs });
|
|
60
|
+
if (settled.kind === "ok")
|
|
61
|
+
return settled.value;
|
|
43
62
|
if (settled.kind === "timeout") {
|
|
44
63
|
state.launched.kill();
|
|
45
64
|
state.disconnect();
|
|
46
65
|
}
|
|
66
|
+
return undefined;
|
|
47
67
|
}
|
|
48
68
|
function abortReason(signal) {
|
|
49
69
|
return signal.reason instanceof Error
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Credentials for the ACP server (S5 spec §6.3, S5-4): the nax-agent auth API
|
|
3
|
+
* behind one port, so the server and `login` are testable without a store.
|
|
4
|
+
*/
|
|
5
|
+
import type { AuthMethod as AcpAuthMethod, AuthenticateResponse } from "@agentclientprotocol/sdk";
|
|
6
|
+
import { type AgentLogger, type AuthInteraction, type AuthMethod, type AuthResult, type NativeCatalogOverrides } from "@nathapp/nax-agent";
|
|
7
|
+
import type { ServerOptions } from "#src/server/options";
|
|
8
|
+
export interface AuthPorts {
|
|
9
|
+
/** Providers `runLogin` can serve (M-33). */
|
|
10
|
+
loginProviderIds(): Promise<readonly string[]>;
|
|
11
|
+
/** Of these providers, those with neither a stored nor an ambient credential (M-29). */
|
|
12
|
+
providersWithoutCredentials(providerIds: readonly string[]): Promise<readonly string[]>;
|
|
13
|
+
runLogin(providerId: string, interaction: AuthInteraction, method?: AuthMethod): Promise<AuthResult>;
|
|
14
|
+
/** The terminal login UI, writing its lines through `log`. */
|
|
15
|
+
interaction(log: (line: string) => void): AuthInteraction;
|
|
16
|
+
}
|
|
17
|
+
export declare const NAX_AGENT_AUTH: AuthPorts;
|
|
18
|
+
/** The provider prefix of a native model id, or undefined when it has none (never guessed). */
|
|
19
|
+
export declare function providerOf(model: string): string | undefined;
|
|
20
|
+
/** Terminal login methods (spec §6.3, M-33): loginable, non-override providers, in order. */
|
|
21
|
+
export declare function terminalAuthMethods(input: {
|
|
22
|
+
readonly models: readonly string[];
|
|
23
|
+
readonly overridden: ReadonlySet<string>;
|
|
24
|
+
readonly loginProviders: readonly string[];
|
|
25
|
+
}): AcpAuthMethod[];
|
|
26
|
+
export interface ServerAuth {
|
|
27
|
+
readonly methods: readonly AcpAuthMethod[];
|
|
28
|
+
/** Spec §6.3, M-29/M-31. */
|
|
29
|
+
authenticate(methodId: string): Promise<AuthenticateResponse>;
|
|
30
|
+
/** M-30: throws auth_required when the model's provider has no credential. */
|
|
31
|
+
ensureCredentials(model: string): Promise<void>;
|
|
32
|
+
}
|
|
33
|
+
export declare function createServerAuth(deps: {
|
|
34
|
+
readonly methods: readonly AcpAuthMethod[];
|
|
35
|
+
readonly overridden: ReadonlySet<string>;
|
|
36
|
+
readonly missing: AuthPorts["providersWithoutCredentials"];
|
|
37
|
+
}): ServerAuth;
|
|
38
|
+
/** No login methods and no checks: the default for an app built without auth. */
|
|
39
|
+
export declare const NO_SERVER_AUTH: ServerAuth;
|
|
40
|
+
export declare function loadServerAuth(input: {
|
|
41
|
+
readonly options: ServerOptions;
|
|
42
|
+
readonly overrides: NativeCatalogOverrides;
|
|
43
|
+
readonly ports: AuthPorts;
|
|
44
|
+
readonly logger: AgentLogger;
|
|
45
|
+
}): Promise<ServerAuth>;
|