@nathapp/nax-agent-acp 0.3.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 +63 -0
- package/LICENSE +21 -0
- package/README.md +227 -0
- package/dist/client/backend.d.ts +30 -0
- package/dist/client/backend.js +238 -0
- package/dist/client/capabilities.d.ts +42 -0
- package/dist/client/capabilities.js +60 -0
- package/dist/client/connection.d.ts +31 -0
- package/dist/client/connection.js +32 -0
- package/dist/client/elicitation.d.ts +34 -0
- package/dist/client/elicitation.js +184 -0
- package/dist/client/env.d.ts +8 -0
- package/dist/client/env.js +21 -0
- package/dist/client/errors.d.ts +36 -0
- package/dist/client/errors.js +92 -0
- package/dist/client/events.d.ts +33 -0
- package/dist/client/events.js +96 -0
- package/dist/client/inbound.d.ts +40 -0
- package/dist/client/inbound.js +100 -0
- package/dist/client/index.d.ts +14 -0
- package/dist/client/index.js +12 -0
- package/dist/client/launch.d.ts +47 -0
- package/dist/client/launch.js +145 -0
- package/dist/client/open.d.ts +35 -0
- package/dist/client/open.js +154 -0
- package/dist/client/options.d.ts +46 -0
- package/dist/client/options.js +91 -0
- package/dist/client/permissions.d.ts +36 -0
- package/dist/client/permissions.js +92 -0
- package/dist/client/pre-approval.d.ts +24 -0
- package/dist/client/pre-approval.js +22 -0
- package/dist/client/race.d.ts +22 -0
- package/dist/client/race.js +20 -0
- package/dist/client/registry.d.ts +35 -0
- package/dist/client/registry.js +43 -0
- package/dist/client/resume.d.ts +37 -0
- package/dist/client/resume.js +93 -0
- package/dist/client/stream-scrub.d.ts +7 -0
- package/dist/client/stream-scrub.js +37 -0
- package/dist/client/text.d.ts +29 -0
- package/dist/client/text.js +62 -0
- package/dist/client/tool-calls.d.ts +42 -0
- package/dist/client/tool-calls.js +147 -0
- package/dist/client/tool-display.d.ts +23 -0
- package/dist/client/tool-display.js +90 -0
- package/dist/client/tool-events.d.ts +35 -0
- package/dist/client/tool-events.js +177 -0
- package/dist/client/tool-host.d.ts +25 -0
- package/dist/client/tool-host.js +178 -0
- package/dist/client/turn.d.ts +19 -0
- package/dist/client/turn.js +52 -0
- package/dist/client/usage.d.ts +36 -0
- package/dist/client/usage.js +65 -0
- package/dist/server/index.d.ts +5 -0
- package/dist/server/index.js +1 -0
- package/package.json +57 -0
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* acpBackend options (S4 spec §6.2), validated with zod at the factory, so a bad
|
|
3
|
+
* option fails at acpBackend() and never at open. allowUnsandboxed is checked
|
|
4
|
+
* first: anything but `true` is AGENT_SESSION_SANDBOX_UNAVAILABLE (R7).
|
|
5
|
+
*/
|
|
6
|
+
import { isAbsolute } from "node:path";
|
|
7
|
+
import { AgentSessionError } from "@nathapp/nax-agent";
|
|
8
|
+
import { z } from "zod";
|
|
9
|
+
import { buildAgentEnv, secretValues } from "#src/client/env";
|
|
10
|
+
import { isAcpAgentName, registryEntry, } from "#src/client/registry";
|
|
11
|
+
export const DEFAULT_CANCEL_GRACE_MS = 10_000;
|
|
12
|
+
export const DEFAULT_INITIALIZE_TIMEOUT_MS = 60_000;
|
|
13
|
+
const noNul = (value) => !value.includes("\u0000");
|
|
14
|
+
const plain = z.string().refine(noNul, "must not contain NUL");
|
|
15
|
+
const command = z
|
|
16
|
+
.string()
|
|
17
|
+
.min(1)
|
|
18
|
+
.refine(noNul, "must not contain NUL")
|
|
19
|
+
.refine((c) => !c.includes("/") || isAbsolute(c), "a command is a bare name or an absolute path");
|
|
20
|
+
const customAgent = z.strictObject({
|
|
21
|
+
name: z
|
|
22
|
+
.string()
|
|
23
|
+
.regex(/^[a-z][a-z0-9._-]{0,63}$/, "a lowercase name of at most 64 characters")
|
|
24
|
+
.refine((name) => !isAcpAgentName(name), "a custom agent may not reuse a registered name"),
|
|
25
|
+
command,
|
|
26
|
+
args: z.array(plain).optional(),
|
|
27
|
+
});
|
|
28
|
+
const SCHEMA = z
|
|
29
|
+
.strictObject({
|
|
30
|
+
agent: z.union([z.enum(["claude", "codex", "gemini", "opencode", "pi"]), customAgent]),
|
|
31
|
+
allowUnsandboxed: z.literal(true),
|
|
32
|
+
model: z.string().min(1).optional(),
|
|
33
|
+
env: z.record(z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/), plain).optional(),
|
|
34
|
+
inheritEnv: z.boolean().optional(),
|
|
35
|
+
command: command.optional(),
|
|
36
|
+
args: z.array(plain).optional(),
|
|
37
|
+
cancelGraceMs: z.number().int().positive().max(600_000).optional(),
|
|
38
|
+
initializeTimeoutMs: z.number().int().positive().max(3_600_000).optional(),
|
|
39
|
+
})
|
|
40
|
+
.superRefine((value, ctx) => {
|
|
41
|
+
if (value.args !== undefined && value.command === undefined) {
|
|
42
|
+
ctx.addIssue({ code: "custom", path: ["args"], message: "args needs command" });
|
|
43
|
+
}
|
|
44
|
+
if (typeof value.agent === "object" && value.command !== undefined) {
|
|
45
|
+
ctx.addIssue({ code: "custom", path: ["command"], message: "a custom agent carries its own command" });
|
|
46
|
+
}
|
|
47
|
+
});
|
|
48
|
+
function isRecord(value) {
|
|
49
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
50
|
+
}
|
|
51
|
+
function launchOf(data, entry) {
|
|
52
|
+
if (data.command !== undefined)
|
|
53
|
+
return { kind: "explicit", candidate: { command: data.command, args: data.args ?? [] } };
|
|
54
|
+
if (typeof data.agent === "object") {
|
|
55
|
+
return { kind: "explicit", candidate: { command: data.agent.command, args: data.agent.args ?? [] } };
|
|
56
|
+
}
|
|
57
|
+
return { kind: "registry", candidates: entry?.launch ?? [] };
|
|
58
|
+
}
|
|
59
|
+
function resolved(data, source) {
|
|
60
|
+
const agentName = typeof data.agent === "string" ? data.agent : data.agent.name;
|
|
61
|
+
const entry = typeof data.agent === "string" ? registryEntry(data.agent) : undefined;
|
|
62
|
+
const env = buildAgentEnv({
|
|
63
|
+
source,
|
|
64
|
+
inheritEnv: data.inheritEnv ?? false,
|
|
65
|
+
authEnv: entry?.authEnv ?? [],
|
|
66
|
+
extra: data.env ?? {},
|
|
67
|
+
});
|
|
68
|
+
return Object.freeze({
|
|
69
|
+
kind: `acp:${agentName}`,
|
|
70
|
+
agentName,
|
|
71
|
+
entry,
|
|
72
|
+
launch: launchOf(data, entry),
|
|
73
|
+
model: data.model,
|
|
74
|
+
env: Object.freeze(env),
|
|
75
|
+
secrets: Object.freeze([...secretValues(env)]),
|
|
76
|
+
cancelGraceMs: data.cancelGraceMs ?? DEFAULT_CANCEL_GRACE_MS,
|
|
77
|
+
initializeTimeoutMs: data.initializeTimeoutMs ?? DEFAULT_INITIALIZE_TIMEOUT_MS,
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
export function resolveAcpOptions(input, source = process.env) {
|
|
81
|
+
if (!isRecord(input) || input.allowUnsandboxed !== true) {
|
|
82
|
+
throw new AgentSessionError("acpBackend requires allowUnsandboxed: true: the agent process runs on the host, unsandboxed", "AGENT_SESSION_SANDBOX_UNAVAILABLE", { path: "allowUnsandboxed" });
|
|
83
|
+
}
|
|
84
|
+
const parsed = SCHEMA.safeParse(input);
|
|
85
|
+
if (!parsed.success) {
|
|
86
|
+
const issue = parsed.error.issues[0];
|
|
87
|
+
const path = issue === undefined ? "" : issue.path.map(String).join(".");
|
|
88
|
+
throw new AgentSessionError(`Invalid acpBackend options: ${path === "" ? "(options)" : path}: ${issue?.message ?? "invalid"}`, "AGENT_SESSION_INVALID_OPTIONS", { path });
|
|
89
|
+
}
|
|
90
|
+
return resolved(parsed.data, source);
|
|
91
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* session/request_permission by profile (S4 spec §6.4 layer 2). none and read
|
|
3
|
+
* reject every request; full allows it; ask puts it in front of the caller through
|
|
4
|
+
* asks.requestApproval and answer(). Only options the agent offered are chosen,
|
|
5
|
+
* and only the *_once kinds: allow_always would outlive the session. Auto-decisions
|
|
6
|
+
* are recorded with decidedBy "profile". Fail closed: a deny or deadline answers
|
|
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) and listed
|
|
9
|
+
* read-only for plan mode (#2365), so they are normally never asked about; if an agent asks anyway, the request is decided
|
|
10
|
+
* like any other, because its title is display data (S4-4 D4-c).
|
|
11
|
+
*/
|
|
12
|
+
import type { RequestPermissionRequest, RequestPermissionResponse } from "@agentclientprotocol/sdk";
|
|
13
|
+
import type { AgentSessionProfile, SessionAskPort } from "@nathapp/nax-agent";
|
|
14
|
+
export declare const NO_ALLOW_ONCE_REASON = "agent offered no allow-once option";
|
|
15
|
+
export declare const UNSHOWABLE_REASON = "the request could not be shown safely";
|
|
16
|
+
export declare const ASK_REASON = "the ACP agent asks permission";
|
|
17
|
+
export declare const FULL_REASON = "profile \"full\" allows every permission request";
|
|
18
|
+
export declare const UNKNOWN_PROFILE_REASON = "unknown profile";
|
|
19
|
+
export declare function readOnlyReason(profile: AgentSessionProfile): string;
|
|
20
|
+
export interface PermissionContext {
|
|
21
|
+
readonly profile: AgentSessionProfile;
|
|
22
|
+
readonly asks: SessionAskPort;
|
|
23
|
+
readonly secrets: readonly string[];
|
|
24
|
+
/** Aborts when the turn's binding is released or the agent process exits (D3-d). */
|
|
25
|
+
readonly signal: AbortSignal;
|
|
26
|
+
}
|
|
27
|
+
export interface OfferedOptions {
|
|
28
|
+
readonly allowOnce?: string;
|
|
29
|
+
readonly rejectOnce?: string;
|
|
30
|
+
}
|
|
31
|
+
export declare function offeredOptions(request: RequestPermissionRequest): OfferedOptions;
|
|
32
|
+
/** A deny: the agent's reject_once, or `cancelled` when it offered none. */
|
|
33
|
+
export declare function rejectWith(offered: OfferedOptions): RequestPermissionResponse;
|
|
34
|
+
/** The answer to a request outside the running turn (spec §6.3): a deny, never an event. */
|
|
35
|
+
export declare function rejectLocally(request: RequestPermissionRequest): RequestPermissionResponse;
|
|
36
|
+
export declare function decidePermission(request: RequestPermissionRequest, ctx: PermissionContext): Promise<RequestPermissionResponse>;
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { isRecord } from "#src/client/text";
|
|
2
|
+
import { describeToolCall } from "#src/client/tool-display";
|
|
3
|
+
export const NO_ALLOW_ONCE_REASON = "agent offered no allow-once option";
|
|
4
|
+
export const UNSHOWABLE_REASON = "the request could not be shown safely";
|
|
5
|
+
export const ASK_REASON = "the ACP agent asks permission";
|
|
6
|
+
export const FULL_REASON = 'profile "full" allows every permission request';
|
|
7
|
+
export const UNKNOWN_PROFILE_REASON = "unknown profile";
|
|
8
|
+
export function readOnlyReason(profile) {
|
|
9
|
+
return `profile "${profile}" rejects every permission request`;
|
|
10
|
+
}
|
|
11
|
+
function optionIdOf(options, kind) {
|
|
12
|
+
const found = options.find((option) => isRecord(option) && option.kind === kind && typeof option.optionId === "string" && option.optionId !== "");
|
|
13
|
+
return isRecord(found) && typeof found.optionId === "string" ? found.optionId : undefined;
|
|
14
|
+
}
|
|
15
|
+
export function offeredOptions(request) {
|
|
16
|
+
const options = Array.isArray(request.options) ? request.options : [];
|
|
17
|
+
const allowOnce = optionIdOf(options, "allow_once");
|
|
18
|
+
const rejectOnce = optionIdOf(options, "reject_once");
|
|
19
|
+
return {
|
|
20
|
+
...(allowOnce === undefined ? {} : { allowOnce }),
|
|
21
|
+
...(rejectOnce === undefined ? {} : { rejectOnce }),
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
const cancelled = () => ({ outcome: { outcome: "cancelled" } });
|
|
25
|
+
const selected = (optionId) => ({ outcome: { outcome: "selected", optionId } });
|
|
26
|
+
/** A deny: the agent's reject_once, or `cancelled` when it offered none. */
|
|
27
|
+
export function rejectWith(offered) {
|
|
28
|
+
return offered.rejectOnce === undefined ? cancelled() : selected(offered.rejectOnce);
|
|
29
|
+
}
|
|
30
|
+
/** The answer to a request outside the running turn (spec §6.3): a deny, never an event. */
|
|
31
|
+
export function rejectLocally(request) {
|
|
32
|
+
return rejectWith(offeredOptions(request));
|
|
33
|
+
}
|
|
34
|
+
function eventFields(display) {
|
|
35
|
+
return {
|
|
36
|
+
...(display.callId === undefined ? {} : { callId: display.callId }),
|
|
37
|
+
tool: display.tool,
|
|
38
|
+
summary: display.summary,
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
export async function decidePermission(request, ctx) {
|
|
42
|
+
// The turn was cancelled, timed out or lost its process: nothing is decided, no event (D3-d).
|
|
43
|
+
if (ctx.signal.aborted)
|
|
44
|
+
return cancelled();
|
|
45
|
+
const offered = offeredOptions(request);
|
|
46
|
+
const display = describeToolCall(request.toolCall, ctx.secrets);
|
|
47
|
+
const auto = (reason, decision) => ctx.asks.recordAutoDecision({ ...eventFields(display), reason }, decision);
|
|
48
|
+
switch (ctx.profile) {
|
|
49
|
+
case "none":
|
|
50
|
+
case "read":
|
|
51
|
+
auto(readOnlyReason(ctx.profile), "deny");
|
|
52
|
+
return rejectWith(offered);
|
|
53
|
+
case "full":
|
|
54
|
+
if (offered.allowOnce === undefined)
|
|
55
|
+
return denyNoAllowOnce(offered, auto);
|
|
56
|
+
auto(FULL_REASON, "allow");
|
|
57
|
+
return selected(offered.allowOnce);
|
|
58
|
+
case "ask":
|
|
59
|
+
if (offered.allowOnce === undefined)
|
|
60
|
+
return denyNoAllowOnce(offered, auto);
|
|
61
|
+
if (!display.showable) {
|
|
62
|
+
auto(UNSHOWABLE_REASON, "deny");
|
|
63
|
+
return rejectWith(offered);
|
|
64
|
+
}
|
|
65
|
+
return askCaller(display, offered.allowOnce, offered, ctx);
|
|
66
|
+
default:
|
|
67
|
+
// A profile this build does not know: fail closed.
|
|
68
|
+
auto(UNKNOWN_PROFILE_REASON, "deny");
|
|
69
|
+
return rejectWith(offered);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
function denyNoAllowOnce(offered, auto) {
|
|
73
|
+
auto(NO_ALLOW_ONCE_REASON, "deny");
|
|
74
|
+
return rejectWith(offered);
|
|
75
|
+
}
|
|
76
|
+
async function askCaller(display, allowOnce, offered, ctx) {
|
|
77
|
+
try {
|
|
78
|
+
const answer = await ctx.asks.requestApproval({
|
|
79
|
+
...eventFields(display),
|
|
80
|
+
...(display.command === undefined ? {} : { command: display.command }),
|
|
81
|
+
reason: ASK_REASON,
|
|
82
|
+
signal: ctx.signal,
|
|
83
|
+
});
|
|
84
|
+
if (answer.decision === "allow")
|
|
85
|
+
return selected(allowOnce);
|
|
86
|
+
return answer.decidedBy === "cancelled" ? cancelled() : rejectWith(offered);
|
|
87
|
+
}
|
|
88
|
+
catch {
|
|
89
|
+
// The turn ended between routing and asking (the port's "no-turn"): fail closed (D3-f).
|
|
90
|
+
return cancelled();
|
|
91
|
+
}
|
|
92
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Adapter pre-approval of embedder tools (S4 spec R12, §6.6; D4-a). Claude's
|
|
3
|
+
* adapter (claude-agent-acp 0.85.1) keys an ACP MCP server by its `name` and
|
|
4
|
+
* passes `_meta.claudeCode.options` through to the Claude Agent SDK, whose
|
|
5
|
+
* `allowedTools` rules allow a tool without a permission request. One exact rule
|
|
6
|
+
* per tool, `mcp__nax__<tool>`, so only the session's own tools are allowed. Tool
|
|
7
|
+
* names are already restricted by the facade, so a rule never needs escaping.
|
|
8
|
+
* Plan mode (profiles none/read) asks before any MCP tool not marked read-only,
|
|
9
|
+
* ahead of these rules; tool-calls.ts lists every tool with readOnlyHint (#2365).
|
|
10
|
+
*/
|
|
11
|
+
import type { AgentSessionProfile } from "@nathapp/nax-agent";
|
|
12
|
+
import type { AgentRegistryEntry } from "#src/client/registry";
|
|
13
|
+
/** The ACP MCP server name; the agent sees the tools as `mcp__nax__<tool>`. */
|
|
14
|
+
export declare const TOOL_HOST_SERVER_NAME = "nax";
|
|
15
|
+
export declare function mcpToolRule(toolName: string): string;
|
|
16
|
+
/**
|
|
17
|
+
* Claude tools a session under `none` or `read` never gets (#2365). Asked to change
|
|
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;
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/** The ACP MCP server name; the agent sees the tools as `mcp__nax__<tool>`. */
|
|
2
|
+
export const TOOL_HOST_SERVER_NAME = "nax";
|
|
3
|
+
export function mcpToolRule(toolName) {
|
|
4
|
+
return `mcp__${TOOL_HOST_SERVER_NAME}__${toolName}`;
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* Claude tools a session under `none` or `read` never gets (#2365). Asked to change
|
|
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) {
|
|
15
|
+
if (kind !== "claudeCode.allowedTools")
|
|
16
|
+
return undefined;
|
|
17
|
+
const options = {
|
|
18
|
+
...(toolNames.length === 0 ? {} : { allowedTools: toolNames.map(mcpToolRule) }),
|
|
19
|
+
...(profile === "none" || profile === "read" ? { disallowedTools: [...READ_ONLY_DISALLOWED_TOOLS] } : {}),
|
|
20
|
+
};
|
|
21
|
+
return Object.keys(options).length === 0 ? undefined : { claudeCode: { options } };
|
|
22
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Settles a promise against an optional deadline and an optional abort signal,
|
|
3
|
+
* and reports which came first instead of throwing. The ACP backend bounds every
|
|
4
|
+
* open step, the cancel grace and the close with it. The raced promise's own
|
|
5
|
+
* rejection is always observed, so a late failure is never unhandled.
|
|
6
|
+
*/
|
|
7
|
+
export type Raced<T> = {
|
|
8
|
+
readonly kind: "ok";
|
|
9
|
+
readonly value: T;
|
|
10
|
+
} | {
|
|
11
|
+
readonly kind: "failed";
|
|
12
|
+
readonly error: unknown;
|
|
13
|
+
} | {
|
|
14
|
+
readonly kind: "timeout";
|
|
15
|
+
} | {
|
|
16
|
+
readonly kind: "aborted";
|
|
17
|
+
};
|
|
18
|
+
export interface RaceOptions {
|
|
19
|
+
readonly timeoutMs?: number;
|
|
20
|
+
readonly signal?: AbortSignal;
|
|
21
|
+
}
|
|
22
|
+
export declare function race<T>(promise: Promise<T>, opts: RaceOptions): Promise<Raced<T>>;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
export function race(promise, opts) {
|
|
2
|
+
return new Promise((resolve) => {
|
|
3
|
+
let timer;
|
|
4
|
+
const onAbort = () => finish({ kind: "aborted" });
|
|
5
|
+
function finish(result) {
|
|
6
|
+
if (timer !== undefined)
|
|
7
|
+
clearTimeout(timer);
|
|
8
|
+
opts.signal?.removeEventListener("abort", onAbort);
|
|
9
|
+
resolve(result);
|
|
10
|
+
}
|
|
11
|
+
promise.then((value) => finish({ kind: "ok", value }), (error) => finish({ kind: "failed", error }));
|
|
12
|
+
if (opts.signal?.aborted === true) {
|
|
13
|
+
finish({ kind: "aborted" });
|
|
14
|
+
return;
|
|
15
|
+
}
|
|
16
|
+
opts.signal?.addEventListener("abort", onAbort, { once: true });
|
|
17
|
+
if (opts.timeoutMs !== undefined)
|
|
18
|
+
timer = setTimeout(() => finish({ kind: "timeout" }), opts.timeoutMs);
|
|
19
|
+
});
|
|
20
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Launch and policy data per registered ACP agent (S4 spec §6.10).
|
|
3
|
+
*
|
|
4
|
+
* The capability record built from `initialize` is authoritative at runtime and
|
|
5
|
+
* only narrows what this table allows. Versions are bumped deliberately. Custom
|
|
6
|
+
* agents (`{ name, command }`) have no entry: no mode ids, no pre-approval and no
|
|
7
|
+
* auth variables, so their requirements fail closed.
|
|
8
|
+
*/
|
|
9
|
+
export type AcpAgentName = "claude" | "codex" | "gemini" | "opencode" | "pi";
|
|
10
|
+
export interface LaunchCandidate {
|
|
11
|
+
readonly command: string;
|
|
12
|
+
readonly args: readonly string[];
|
|
13
|
+
}
|
|
14
|
+
/** A session config option and the value that selects a mode (Claude: option `mode`). */
|
|
15
|
+
export interface ModeSetting {
|
|
16
|
+
readonly configId: string;
|
|
17
|
+
readonly value: string;
|
|
18
|
+
}
|
|
19
|
+
export interface AgentRegistryEntry {
|
|
20
|
+
readonly name: AcpAgentName;
|
|
21
|
+
/** Tried in order; the first command found wins (S4-2 launch). */
|
|
22
|
+
readonly launch: readonly LaunchCandidate[];
|
|
23
|
+
/** Mode for profiles `none` and `read`; undefined means those profiles are unsupported (§6.4). */
|
|
24
|
+
readonly readOnlyMode: ModeSetting | undefined;
|
|
25
|
+
/** Mode for profiles `ask` and `full`; undefined means the agent's own default is kept. */
|
|
26
|
+
readonly defaultMode: ModeSetting | undefined;
|
|
27
|
+
/** How embedder tools are pre-approved at the adapter (R12); undefined means tools are unsupported. */
|
|
28
|
+
readonly preApproval: "claudeCode.allowedTools" | undefined;
|
|
29
|
+
/** Variables passed through the env allowlist so the adapter can authenticate itself (§6.2). */
|
|
30
|
+
readonly authEnv: readonly string[];
|
|
31
|
+
}
|
|
32
|
+
export declare const ACP_AGENT_NAMES: readonly AcpAgentName[];
|
|
33
|
+
export declare function isAcpAgentName(name: string): name is AcpAgentName;
|
|
34
|
+
/** The registry entry for a registered agent name; undefined for anything else (custom agents included). */
|
|
35
|
+
export declare function registryEntry(name: string): AgentRegistryEntry | undefined;
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Launch and policy data per registered ACP agent (S4 spec §6.10).
|
|
3
|
+
*
|
|
4
|
+
* The capability record built from `initialize` is authoritative at runtime and
|
|
5
|
+
* only narrows what this table allows. Versions are bumped deliberately. Custom
|
|
6
|
+
* agents (`{ name, command }`) have no entry: no mode ids, no pre-approval and no
|
|
7
|
+
* auth variables, so their requirements fail closed.
|
|
8
|
+
*/
|
|
9
|
+
const local = (command, ...args) => ({ command, args });
|
|
10
|
+
const npx = (spec) => ({ command: "npx", args: ["-y", spec] });
|
|
11
|
+
function entry(name, launch, authEnv, claude) {
|
|
12
|
+
return Object.freeze({
|
|
13
|
+
name,
|
|
14
|
+
launch: Object.freeze(launch.map((c) => Object.freeze({ command: c.command, args: Object.freeze([...c.args]) }))),
|
|
15
|
+
readOnlyMode: claude?.readOnlyMode === undefined ? undefined : Object.freeze({ ...claude.readOnlyMode }),
|
|
16
|
+
defaultMode: claude?.defaultMode === undefined ? undefined : Object.freeze({ ...claude.defaultMode }),
|
|
17
|
+
preApproval: claude?.preApproval,
|
|
18
|
+
authEnv: Object.freeze([...authEnv]),
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
const REGISTRY = new Map([
|
|
22
|
+
[
|
|
23
|
+
"claude",
|
|
24
|
+
entry("claude", [local("claude-agent-acp"), npx("@agentclientprotocol/claude-agent-acp@~0.85.1")], ["ANTHROPIC_API_KEY", "CLAUDE_CODE_OAUTH_TOKEN"], {
|
|
25
|
+
readOnlyMode: { configId: "mode", value: "plan" },
|
|
26
|
+
defaultMode: { configId: "mode", value: "default" },
|
|
27
|
+
preApproval: "claudeCode.allowedTools",
|
|
28
|
+
}),
|
|
29
|
+
],
|
|
30
|
+
["codex", entry("codex", [local("codex-acp"), npx("@agentclientprotocol/codex-acp@~2.1.1")], ["OPENAI_API_KEY"])],
|
|
31
|
+
["gemini", entry("gemini", [local("gemini", "--acp")], ["GEMINI_API_KEY"])],
|
|
32
|
+
["opencode", entry("opencode", [local("opencode", "acp")], [])],
|
|
33
|
+
// Exact pin: a tilde range does not pin 0.0.x.
|
|
34
|
+
["pi", entry("pi", [local("pi-acp"), npx("pi-acp@0.0.34")], [])],
|
|
35
|
+
]);
|
|
36
|
+
export const ACP_AGENT_NAMES = Object.freeze([...REGISTRY.keys()]);
|
|
37
|
+
export function isAcpAgentName(name) {
|
|
38
|
+
return ACP_AGENT_NAMES.includes(name);
|
|
39
|
+
}
|
|
40
|
+
/** The registry entry for a registered agent name; undefined for anything else (custom agents included). */
|
|
41
|
+
export function registryEntry(name) {
|
|
42
|
+
return isAcpAgentName(name) ? REGISTRY.get(name) : undefined;
|
|
43
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import type { LoadSessionResponse, McpServer, ResumeSessionResponse, SessionConfigOption } from "@agentclientprotocol/sdk";
|
|
2
|
+
import { type BackendOpenContext, type TranscriptDoc } from "@nathapp/nax-agent";
|
|
3
|
+
import type { CapabilityRecord } from "#src/client/capabilities";
|
|
4
|
+
import type { AcpLink } from "#src/client/connection";
|
|
5
|
+
import type { ResolvedAcpOptions } from "#src/client/options";
|
|
6
|
+
/** An agent session id longer than this is not trusted (S4-2 Review Focus 5). */
|
|
7
|
+
export declare const MAX_SESSION_ID_CHARS = 512;
|
|
8
|
+
/** A stored agent session to restore: from the document (resume) or the live session (reconnect). */
|
|
9
|
+
export interface Restore {
|
|
10
|
+
readonly agentSessionId: string;
|
|
11
|
+
/** The cwd the agent session was created with, spelled as stored. */
|
|
12
|
+
readonly cwd: string;
|
|
13
|
+
/** The meter's starting baseline (D6-a). */
|
|
14
|
+
readonly costUsd: number;
|
|
15
|
+
}
|
|
16
|
+
export type RestoredWith = "resume" | "load";
|
|
17
|
+
export interface RestoredSession {
|
|
18
|
+
readonly agentSessionId: string;
|
|
19
|
+
readonly cwd: string;
|
|
20
|
+
readonly configOptions: readonly SessionConfigOption[];
|
|
21
|
+
readonly restoredWith: RestoredWith;
|
|
22
|
+
}
|
|
23
|
+
/** What session/new, session/resume and session/load add to `cwd`: the tool host's entry and Claude's `_meta` (§6.6, #2365). */
|
|
24
|
+
export interface SessionSetup {
|
|
25
|
+
readonly mcpServers: McpServer[];
|
|
26
|
+
readonly _meta?: Record<string, unknown>;
|
|
27
|
+
}
|
|
28
|
+
/** One open-phase request, bounded by initializeTimeoutMs and openSignal (open.ts). */
|
|
29
|
+
export type OpenStep = <T>(label: string, request: Promise<T>) => Promise<T>;
|
|
30
|
+
export declare function isUsableSessionId(value: unknown): value is string;
|
|
31
|
+
export declare function canRestore(record: CapabilityRecord): boolean;
|
|
32
|
+
/** §6.9 step 1 (D6-b, D6-c). Throws before anything is spawned. */
|
|
33
|
+
export declare function storedSessionOf(doc: TranscriptDoc, ctx: BackendOpenContext, options: ResolvedAcpOptions): Restore;
|
|
34
|
+
/** §6.9 step 3 (D6-d): an echoed id must be the stored one. A null answer (D6-k) has no config options. */
|
|
35
|
+
export declare function checkRestored(restore: Restore, via: RestoredWith, response: ResumeSessionResponse | LoadSessionResponse): RestoredSession;
|
|
36
|
+
/** §6.9 step 2: session/resume when advertised, else session/load; never a fresh session. */
|
|
37
|
+
export declare function restoreSession(restore: Restore, record: CapabilityRecord, setup: SessionSetup, link: AcpLink, step: OpenStep): Promise<RestoredSession>;
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Resume and reconnect (S4 spec §6.9). Before anything is spawned, the stored
|
|
3
|
+
* document's ACP record is checked against this backend and workdir (step 1).
|
|
4
|
+
* After initialize, the agent session is restored with session/resume when the
|
|
5
|
+
* agent advertises it (no replay), else session/load (its replayed updates and
|
|
6
|
+
* requests reach no turn and are dropped or refused by the router), never as a
|
|
7
|
+
* fresh session (step 2). Claude's adapter echoes the restored session's id
|
|
8
|
+
* outside the protocol's schema; another id than the stored one is refused
|
|
9
|
+
* (step 3, D6-d). The cwd is compared canonically and sent to the agent as
|
|
10
|
+
* stored, because Claude keys its session store by it (D6-c). The stored cost
|
|
11
|
+
* baseline seeds the session's meter (D6-a).
|
|
12
|
+
*/
|
|
13
|
+
import { realpathSync } from "node:fs";
|
|
14
|
+
import { resolve } from "node:path";
|
|
15
|
+
import { AgentSessionError, NaxError } from "@nathapp/nax-agent";
|
|
16
|
+
import { capabilityUnsupported } from "#src/client/errors";
|
|
17
|
+
import { isRecord } from "#src/client/text";
|
|
18
|
+
/** An agent session id longer than this is not trusted (S4-2 Review Focus 5). */
|
|
19
|
+
export const MAX_SESSION_ID_CHARS = 512;
|
|
20
|
+
export function isUsableSessionId(value) {
|
|
21
|
+
return typeof value === "string" && value !== "" && value.length <= MAX_SESSION_ID_CHARS;
|
|
22
|
+
}
|
|
23
|
+
export function canRestore(record) {
|
|
24
|
+
return record.resume || record.loadSession;
|
|
25
|
+
}
|
|
26
|
+
function nonEmptyString(value) {
|
|
27
|
+
return typeof value === "string" && value !== "";
|
|
28
|
+
}
|
|
29
|
+
function canonicalDir(path) {
|
|
30
|
+
const absolute = resolve(path);
|
|
31
|
+
try {
|
|
32
|
+
return realpathSync.native(absolute);
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
return absolute;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
function costOf(value) {
|
|
39
|
+
return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0;
|
|
40
|
+
}
|
|
41
|
+
function corrupt(sessionId, reason) {
|
|
42
|
+
return new NaxError(`transcript for session "${sessionId}" is unreadable: ${reason}`, "TRANSCRIPT_CORRUPT", {
|
|
43
|
+
stage: "acp",
|
|
44
|
+
sessionId,
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
/** §6.9 step 1 (D6-b, D6-c). Throws before anything is spawned. */
|
|
48
|
+
export function storedSessionOf(doc, ctx, options) {
|
|
49
|
+
const sessionId = ctx.sessionId;
|
|
50
|
+
const stored = doc.backend ?? "native";
|
|
51
|
+
if (stored !== options.kind) {
|
|
52
|
+
throw new AgentSessionError(`Session "${sessionId}" was written by backend "${stored}"; it cannot be resumed with "${options.kind}"`, "AGENT_SESSION_BACKEND_MISMATCH", { sessionId, stored, kind: options.kind });
|
|
53
|
+
}
|
|
54
|
+
const acp = doc.acp;
|
|
55
|
+
if (!isRecord(acp) ||
|
|
56
|
+
!isUsableSessionId(acp.agentSessionId) ||
|
|
57
|
+
!nonEmptyString(acp.agent) ||
|
|
58
|
+
!nonEmptyString(acp.cwd)) {
|
|
59
|
+
throw corrupt(sessionId, "its ACP record is missing or malformed");
|
|
60
|
+
}
|
|
61
|
+
if (acp.agent !== options.agentName)
|
|
62
|
+
throw corrupt(sessionId, "its ACP record names another agent");
|
|
63
|
+
if (canonicalDir(acp.cwd) !== canonicalDir(ctx.workdir)) {
|
|
64
|
+
throw new AgentSessionError(`Invalid agent session options: workdir "${ctx.workdir}" is not the directory session "${sessionId}" was created in; resume it with that workdir`, "AGENT_SESSION_INVALID_OPTIONS", { path: "workdir" });
|
|
65
|
+
}
|
|
66
|
+
return { agentSessionId: acp.agentSessionId, cwd: acp.cwd, costUsd: costOf(acp.costUsd) };
|
|
67
|
+
}
|
|
68
|
+
/** §6.9 step 3 (D6-d): an echoed id must be the stored one. A null answer (D6-k) has no config options. */
|
|
69
|
+
export function checkRestored(restore, via, response) {
|
|
70
|
+
const raw = response;
|
|
71
|
+
const echoed = isRecord(raw) ? raw.sessionId : undefined;
|
|
72
|
+
if (echoed !== undefined && echoed !== restore.agentSessionId) {
|
|
73
|
+
throw new NaxError("The ACP agent restored a different session than the stored one", "AGENT_SESSION_TURN_FAILED", {
|
|
74
|
+
stage: "acp",
|
|
75
|
+
detail: "identity",
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
return {
|
|
79
|
+
agentSessionId: restore.agentSessionId,
|
|
80
|
+
cwd: restore.cwd,
|
|
81
|
+
configOptions: isRecord(raw) ? (response.configOptions ?? []) : [],
|
|
82
|
+
restoredWith: via,
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
/** §6.9 step 2: session/resume when advertised, else session/load; never a fresh session. */
|
|
86
|
+
export async function restoreSession(restore, record, setup, link, step) {
|
|
87
|
+
const params = { sessionId: restore.agentSessionId, cwd: restore.cwd, ...setup };
|
|
88
|
+
if (record.resume)
|
|
89
|
+
return checkRestored(restore, "resume", await step("session/resume", link.resumeSession(params)));
|
|
90
|
+
if (record.loadSession)
|
|
91
|
+
return checkRestored(restore, "load", await step("session/load", link.loadSession(params)));
|
|
92
|
+
throw capabilityUnsupported("resume", "the agent supports neither session/resume nor session/load");
|
|
93
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export interface StreamScrubber {
|
|
2
|
+
/** Adds a chunk; returns the text that is safe to emit now (possibly ""). */
|
|
3
|
+
push(chunk: string): string;
|
|
4
|
+
/** Returns everything held back, scrubbed, and empties the hold. */
|
|
5
|
+
flush(): string;
|
|
6
|
+
}
|
|
7
|
+
export declare function createStreamScrubber(secrets: readonly string[]): StreamScrubber;
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Agent text as a stream, scrubbed of the session's secret values (S4-5 D5-g). A
|
|
3
|
+
* secret can arrive split across two chunks, so each push scrubs the held tail plus
|
|
4
|
+
* the new chunk and then holds back the last (longest secret length - 1)
|
|
5
|
+
* characters: any secret not yet complete must start inside them. flush() releases
|
|
6
|
+
* the rest. With no secret of MIN_SECRET_LENGTH or more, nothing is held: each
|
|
7
|
+
* chunk passes through unchanged.
|
|
8
|
+
*/
|
|
9
|
+
import { MIN_SECRET_LENGTH, scrubSecrets } from "#src/client/text";
|
|
10
|
+
const PASS_THROUGH = { push: (chunk) => chunk, flush: () => "" };
|
|
11
|
+
/** `at`, moved back one when it would split a surrogate pair. */
|
|
12
|
+
function safeCut(text, at) {
|
|
13
|
+
if (at <= 0)
|
|
14
|
+
return 0;
|
|
15
|
+
const code = text.charCodeAt(at - 1);
|
|
16
|
+
return code >= 0xd800 && code <= 0xdbff ? at - 1 : at;
|
|
17
|
+
}
|
|
18
|
+
export function createStreamScrubber(secrets) {
|
|
19
|
+
const active = secrets.filter((secret) => secret.length >= MIN_SECRET_LENGTH);
|
|
20
|
+
if (active.length === 0)
|
|
21
|
+
return PASS_THROUGH;
|
|
22
|
+
const hold = Math.max(...active.map((secret) => secret.length)) - 1;
|
|
23
|
+
let held = "";
|
|
24
|
+
return {
|
|
25
|
+
push(chunk) {
|
|
26
|
+
const text = scrubSecrets(held + chunk, active);
|
|
27
|
+
const cut = safeCut(text, text.length - hold);
|
|
28
|
+
held = text.slice(cut);
|
|
29
|
+
return text.slice(0, cut);
|
|
30
|
+
},
|
|
31
|
+
flush() {
|
|
32
|
+
const rest = scrubSecrets(held, active);
|
|
33
|
+
held = "";
|
|
34
|
+
return rest;
|
|
35
|
+
},
|
|
36
|
+
};
|
|
37
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Agent text made safe to show (S4 spec §6.4 "untrusted fields", §7): control
|
|
3
|
+
* characters stripped, the session's secret values scrubbed, byte caps that never
|
|
4
|
+
* split a character. Shared by error excerpts (errors.ts), the approval display
|
|
5
|
+
* (tool-display.ts), turn events (stream-scrub.ts, tool-events.ts) and questions
|
|
6
|
+
* (elicitation.ts).
|
|
7
|
+
*/
|
|
8
|
+
/** Shorter secret values are not replaced verbatim: they would garble ordinary text. */
|
|
9
|
+
export declare const MIN_SECRET_LENGTH = 8;
|
|
10
|
+
export declare function isRecord(value: unknown): value is Readonly<Record<string, unknown>>;
|
|
11
|
+
/** Control characters removed, except newline and tab. */
|
|
12
|
+
export declare function stripControl(text: string): string;
|
|
13
|
+
/** Invisible format characters removed (bidi overrides, zero-width): they can hide text from a person. */
|
|
14
|
+
export declare function stripInvisible(text: string): string;
|
|
15
|
+
/** Each known secret value of 8 or more characters replaced by [REDACTED]. */
|
|
16
|
+
export declare function scrubSecrets(text: string, secrets: readonly string[]): string;
|
|
17
|
+
export declare function capBytes(text: string, maxBytes: number): string;
|
|
18
|
+
/**
|
|
19
|
+
* `value` with every string, keys included, scrubbed of the session's secret values.
|
|
20
|
+
* Expects acyclic JSON-like data (capStrings output). Keys are written as data, so a
|
|
21
|
+
* `__proto__` key stays an own property.
|
|
22
|
+
*/
|
|
23
|
+
export declare function scrubDeep(value: unknown, secrets: readonly string[]): unknown;
|
|
24
|
+
/**
|
|
25
|
+
* A one-line label from agent text: control and invisible characters removed,
|
|
26
|
+
* whitespace collapsed, secrets scrubbed, at most `maxChars` code points. Undefined
|
|
27
|
+
* for a non-string or a label that is empty after cleaning.
|
|
28
|
+
*/
|
|
29
|
+
export declare function cleanLabel(value: unknown, secrets: readonly string[], maxChars: number): string | undefined;
|