@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.
Files changed (56) hide show
  1. package/CHANGELOG.md +63 -0
  2. package/LICENSE +21 -0
  3. package/README.md +227 -0
  4. package/dist/client/backend.d.ts +30 -0
  5. package/dist/client/backend.js +238 -0
  6. package/dist/client/capabilities.d.ts +42 -0
  7. package/dist/client/capabilities.js +60 -0
  8. package/dist/client/connection.d.ts +31 -0
  9. package/dist/client/connection.js +32 -0
  10. package/dist/client/elicitation.d.ts +34 -0
  11. package/dist/client/elicitation.js +184 -0
  12. package/dist/client/env.d.ts +8 -0
  13. package/dist/client/env.js +21 -0
  14. package/dist/client/errors.d.ts +36 -0
  15. package/dist/client/errors.js +92 -0
  16. package/dist/client/events.d.ts +33 -0
  17. package/dist/client/events.js +96 -0
  18. package/dist/client/inbound.d.ts +40 -0
  19. package/dist/client/inbound.js +100 -0
  20. package/dist/client/index.d.ts +14 -0
  21. package/dist/client/index.js +12 -0
  22. package/dist/client/launch.d.ts +47 -0
  23. package/dist/client/launch.js +145 -0
  24. package/dist/client/open.d.ts +35 -0
  25. package/dist/client/open.js +154 -0
  26. package/dist/client/options.d.ts +46 -0
  27. package/dist/client/options.js +91 -0
  28. package/dist/client/permissions.d.ts +36 -0
  29. package/dist/client/permissions.js +92 -0
  30. package/dist/client/pre-approval.d.ts +24 -0
  31. package/dist/client/pre-approval.js +22 -0
  32. package/dist/client/race.d.ts +22 -0
  33. package/dist/client/race.js +20 -0
  34. package/dist/client/registry.d.ts +35 -0
  35. package/dist/client/registry.js +43 -0
  36. package/dist/client/resume.d.ts +37 -0
  37. package/dist/client/resume.js +93 -0
  38. package/dist/client/stream-scrub.d.ts +7 -0
  39. package/dist/client/stream-scrub.js +37 -0
  40. package/dist/client/text.d.ts +29 -0
  41. package/dist/client/text.js +62 -0
  42. package/dist/client/tool-calls.d.ts +42 -0
  43. package/dist/client/tool-calls.js +147 -0
  44. package/dist/client/tool-display.d.ts +23 -0
  45. package/dist/client/tool-display.js +90 -0
  46. package/dist/client/tool-events.d.ts +35 -0
  47. package/dist/client/tool-events.js +177 -0
  48. package/dist/client/tool-host.d.ts +25 -0
  49. package/dist/client/tool-host.js +178 -0
  50. package/dist/client/turn.d.ts +19 -0
  51. package/dist/client/turn.js +52 -0
  52. package/dist/client/usage.d.ts +36 -0
  53. package/dist/client/usage.js +65 -0
  54. package/dist/server/index.d.ts +5 -0
  55. package/dist/server/index.js +1 -0
  56. package/package.json +57 -0
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Messages the agent initiates (S4 spec §6.3, §6.4, §6.8). While a turn runs the
3
+ * router holds one binding: the agent session the turn prompts, its collector and
4
+ * its signal. session/update reaches that collector only when it names the bound
5
+ * session; anything else is dropped. session/request_permission and
6
+ * elicitation/create for the bound session go to the backend's decider and
7
+ * elicitation handler with the binding's signal, which aborts when the turn is
8
+ * cancelled, times out or loses its process, and when the binding is released
9
+ * (D3-d, D5-k). A permission request first announces its tool call on the turn's
10
+ * events (D5-c). Any other request (no turn, another session, a request-scoped
11
+ * elicitation, more than MAX_PENDING_DECISIONS pending at once) is answered locally,
12
+ * a permission rejected and an elicitation cancelled, and raises no event; each
13
+ * reason is logged once per session and kind (D3-c). Releasing a binding aborts its
14
+ * pending requests and waits for their answers, so approval_resolved always
15
+ * precedes turn_end.
16
+ */
17
+ import type { CreateElicitationRequest, CreateElicitationResponse, RequestPermissionRequest, RequestPermissionResponse } from "@agentclientprotocol/sdk";
18
+ import type { InboundHandlers } from "#src/client/connection";
19
+ import type { TurnCollector } from "#src/client/events";
20
+ /** Concurrent permission requests and elicitations one turn may hold; further ones are answered locally. */
21
+ export declare const MAX_PENDING_DECISIONS = 16;
22
+ export type PermissionDecider = (request: RequestPermissionRequest, signal: AbortSignal) => Promise<RequestPermissionResponse>;
23
+ export type ElicitationHandler = (request: CreateElicitationRequest, signal: AbortSignal) => Promise<CreateElicitationResponse>;
24
+ export interface InboundRouter {
25
+ readonly handlers: InboundHandlers;
26
+ /**
27
+ * Routes `agentSessionId`'s updates, permission requests and elicitations to this
28
+ * turn. `turnSignal` aborts the turn's requests (cancel, timeout, process gone).
29
+ * The returned function detaches the turn, aborts its pending requests and
30
+ * resolves once each has been answered.
31
+ */
32
+ attach(agentSessionId: string, collector: TurnCollector, turnSignal: AbortSignal): () => Promise<void>;
33
+ /**
34
+ * The running turn's binding signal, or undefined between turns: what an
35
+ * embedder tool call runs under (S4-4 D4-f). It aborts on cancel, timeout,
36
+ * close and process exit, and when the binding is released.
37
+ */
38
+ activeSignal(): AbortSignal | undefined;
39
+ }
40
+ export declare function createInboundRouter(decide: PermissionDecider, elicit?: ElicitationHandler): InboundRouter;
@@ -0,0 +1,100 @@
1
+ import { getLogger } from "@nathapp/nax-agent";
2
+ import { rejectLocally } from "#src/client/permissions";
3
+ import { isRecord } from "#src/client/text";
4
+ /** Concurrent permission requests and elicitations one turn may hold; further ones are answered locally. */
5
+ export const MAX_PENDING_DECISIONS = 16;
6
+ const LOG_MESSAGES = {
7
+ permission: "Rejected a permission request locally",
8
+ elicitation: "Cancelled an elicitation locally",
9
+ };
10
+ const cancelled = () => ({ outcome: { outcome: "cancelled" } });
11
+ const CANCEL_ELICITATION = { action: "cancel" };
12
+ const cancelElicitation = async () => CANCEL_ELICITATION;
13
+ async function track(binding, answer) {
14
+ binding.pending.add(answer);
15
+ try {
16
+ return await answer;
17
+ }
18
+ finally {
19
+ binding.pending.delete(answer);
20
+ }
21
+ }
22
+ /** The session an elicitation names; undefined for a request-scoped one. */
23
+ function sessionOf(request) {
24
+ return isRecord(request) && typeof request.sessionId === "string" ? request.sessionId : undefined;
25
+ }
26
+ export function createInboundRouter(decide, elicit = cancelElicitation) {
27
+ let active;
28
+ const logged = new Set();
29
+ const log = (kind, reason) => {
30
+ const key = `${kind}:${reason}`;
31
+ if (logged.has(key))
32
+ return;
33
+ logged.add(key);
34
+ try {
35
+ getLogger().warn("acp", LOG_MESSAGES[kind], { reason });
36
+ }
37
+ catch {
38
+ // A throwing host logger must not change the answer.
39
+ }
40
+ };
41
+ /** The binding a request may use, or why not. */
42
+ const admit = (sessionId) => {
43
+ const binding = active;
44
+ if (binding === undefined)
45
+ return "no-turn";
46
+ if (sessionId !== binding.sessionId)
47
+ return "foreign-session";
48
+ return binding.pending.size >= MAX_PENDING_DECISIONS ? "too-many" : binding;
49
+ };
50
+ /** A request refused while the turn is being aborted is answered as cancelled, not rejected (S4-3). */
51
+ const aborting = (reason) => reason !== "no-turn" && active?.signal.aborted === true;
52
+ return {
53
+ handlers: {
54
+ onUpdate(notification) {
55
+ if (active !== undefined && notification.sessionId === active.sessionId) {
56
+ active.collector.onUpdate(notification.update);
57
+ }
58
+ },
59
+ onPermission: async (request) => {
60
+ const admitted = admit(request.sessionId);
61
+ if (typeof admitted === "string") {
62
+ if (aborting(admitted))
63
+ return cancelled();
64
+ log("permission", admitted);
65
+ return rejectLocally(request);
66
+ }
67
+ if (!admitted.signal.aborted)
68
+ admitted.collector.announce(request.toolCall);
69
+ return track(admitted, decide(request, admitted.signal).catch(cancelled));
70
+ },
71
+ onElicitation: async (request) => {
72
+ const admitted = admit(sessionOf(request));
73
+ if (typeof admitted === "string") {
74
+ if (!aborting(admitted))
75
+ log("elicitation", admitted);
76
+ return CANCEL_ELICITATION;
77
+ }
78
+ return track(admitted, elicit(request, admitted.signal).catch(cancelElicitation));
79
+ },
80
+ },
81
+ activeSignal: () => active?.signal,
82
+ attach(sessionId, collector, turnSignal) {
83
+ const scope = new AbortController();
84
+ const binding = {
85
+ sessionId,
86
+ collector,
87
+ scope,
88
+ signal: AbortSignal.any([scope.signal, turnSignal]),
89
+ pending: new Set(),
90
+ };
91
+ active = binding;
92
+ return async () => {
93
+ if (active === binding)
94
+ active = undefined;
95
+ scope.abort();
96
+ await Promise.allSettled([...binding.pending]);
97
+ };
98
+ },
99
+ };
100
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * `@nathapp/nax-agent-acp/client`: the ACP backend for nax-agent sessions.
3
+ *
4
+ * Sessions under all four profiles: permission requests decided by profile
5
+ * (approved through answer() under `ask`), embedder tools through a per-session
6
+ * loopback MCP tool host that Claude's adapter pre-approves, thinking, tool and
7
+ * usage events, the agent's form elicitations as questions, resume of a stored
8
+ * session in a new process (session/resume, else session/load), and one reconnect
9
+ * after the agent process dies (S4-6).
10
+ */
11
+ export { acpBackend } from "#src/client/backend";
12
+ export { ACP_STOP_CODES, type AcpStopCode } from "#src/client/errors";
13
+ export type { AcpAgentSpec, AcpBackendOptions } from "#src/client/options";
14
+ export type { AcpAgentName } from "#src/client/registry";
@@ -0,0 +1,12 @@
1
+ /**
2
+ * `@nathapp/nax-agent-acp/client`: the ACP backend for nax-agent sessions.
3
+ *
4
+ * Sessions under all four profiles: permission requests decided by profile
5
+ * (approved through answer() under `ask`), embedder tools through a per-session
6
+ * loopback MCP tool host that Claude's adapter pre-approves, thinking, tool and
7
+ * usage events, the agent's form elicitations as questions, resume of a stored
8
+ * session in a new process (session/resume, else session/load), and one reconnect
9
+ * after the agent process dies (S4-6).
10
+ */
11
+ export { acpBackend } from "#src/client/backend";
12
+ export { ACP_STOP_CODES } from "#src/client/errors";
@@ -0,0 +1,47 @@
1
+ import { type AgentApp, type Stream } from "@agentclientprotocol/sdk";
2
+ import { type AgentSessionError, type StderrTail } from "@nathapp/nax-agent";
3
+ import type { LaunchCandidate } from "#src/client/registry";
4
+ export type LaunchTarget = {
5
+ readonly kind: "stream";
6
+ readonly stream: Stream;
7
+ }
8
+ /** An in-process agent: the unit suite's fake (D-k). */
9
+ | {
10
+ readonly kind: "app";
11
+ readonly agent: AgentApp;
12
+ };
13
+ export interface AgentExit {
14
+ readonly code: number | null;
15
+ readonly signal: string | null;
16
+ /** Set when the process never started (for example ENOENT). */
17
+ readonly spawnError?: string;
18
+ }
19
+ export interface LaunchedAgent {
20
+ readonly target: LaunchTarget;
21
+ readonly pid: number | undefined;
22
+ readonly stderr: StderrTail;
23
+ /** Resolves once, when the process is gone. Never rejects. */
24
+ readonly exited: Promise<AgentExit>;
25
+ /** The exit once the process has exited (and its stderr drained), or undefined after `waitMs`. */
26
+ whenGone(waitMs: number): Promise<AgentExit | undefined>;
27
+ /** Closes stdin, SIGTERMs the group, SIGKILLs it after `graceMs`; resolves once exited. */
28
+ terminate(graceMs: number): Promise<void>;
29
+ /** SIGKILLs the group now. */
30
+ kill(): void;
31
+ }
32
+ export interface LaunchRequest {
33
+ readonly command: string;
34
+ readonly args: readonly string[];
35
+ readonly cwd: string;
36
+ readonly env: Readonly<Record<string, string>>;
37
+ /** The SDK default when absent. */
38
+ readonly maxMessageBytes?: number;
39
+ }
40
+ export type LaunchFn = (request: LaunchRequest) => LaunchedAgent;
41
+ /** True when `command` is an absolute executable path, or a bare name found on `pathVar`. */
42
+ export declare function findExecutable(command: string, pathVar: string | undefined): boolean;
43
+ /** The first candidate whose command is found (§6.10: tried in order). */
44
+ export declare function pickCandidate(candidates: readonly LaunchCandidate[], pathVar: string | undefined): LaunchCandidate | undefined;
45
+ export declare function launchAgent(request: LaunchRequest): LaunchedAgent;
46
+ /** The agent process died or its stream closed: BACKEND_UNAVAILABLE with the exit and a redacted stderr excerpt. */
47
+ export declare function agentGoneError(during: string, launched: LaunchedAgent, secrets: readonly string[]): Promise<AgentSessionError>;
@@ -0,0 +1,145 @@
1
+ /**
2
+ * Spawning an ACP agent (S4 spec §6.1 launch). The agent is a process-group
3
+ * leader, so a kill reaches its children (npx, node, the adapter's own tools).
4
+ * Its stdio becomes an ndjson ACP stream and its stderr feeds a bounded tail.
5
+ * A spawn failure is never thrown: `exited` resolves with spawnError. Pipe
6
+ * errors (EPIPE after the agent died) are absorbed so they cannot crash the host.
7
+ */
8
+ import { spawn } from "node:child_process";
9
+ import { accessSync, constants, statSync } from "node:fs";
10
+ import { delimiter, isAbsolute, join } from "node:path";
11
+ import { Readable, Writable } from "node:stream";
12
+ import { ndJsonStream } from "@agentclientprotocol/sdk";
13
+ import { createStderrTail, killProcessGroup } from "@nathapp/nax-agent";
14
+ import { agentTextExcerpt, backendUnavailable, EXCERPT_BYTES } from "#src/client/errors";
15
+ import { race } from "#src/client/race";
16
+ /** How long a transport failure waits for the exit status. */
17
+ const GONE_WAIT_MS = 1_000;
18
+ /** How long, after the exit, the last stderr may take to arrive. */
19
+ const STDERR_DRAIN_MS = 200;
20
+ function isExecutableFile(path) {
21
+ try {
22
+ if (!statSync(path).isFile())
23
+ return false;
24
+ accessSync(path, constants.X_OK);
25
+ return true;
26
+ }
27
+ catch {
28
+ return false;
29
+ }
30
+ }
31
+ /** True when `command` is an absolute executable path, or a bare name found on `pathVar`. */
32
+ export function findExecutable(command, pathVar) {
33
+ if (command.includes("/"))
34
+ return isAbsolute(command) && isExecutableFile(command);
35
+ return (pathVar ?? "").split(delimiter).some((dir) => dir !== "" && isExecutableFile(join(dir, command)));
36
+ }
37
+ /** The first candidate whose command is found (§6.10: tried in order). */
38
+ export function pickCandidate(candidates, pathVar) {
39
+ return candidates.find((candidate) => findExecutable(candidate.command, pathVar));
40
+ }
41
+ function ignore() { }
42
+ function failedLaunch(stderr, error) {
43
+ const exit = {
44
+ code: null,
45
+ signal: null,
46
+ spawnError: error instanceof Error ? error.message : String(error),
47
+ };
48
+ const stream = {
49
+ readable: new ReadableStream({ start: (controller) => controller.close() }),
50
+ writable: new WritableStream(),
51
+ };
52
+ return {
53
+ target: { kind: "stream", stream },
54
+ pid: undefined,
55
+ stderr,
56
+ exited: Promise.resolve(exit),
57
+ whenGone: async () => exit,
58
+ terminate: async () => { },
59
+ kill: ignore,
60
+ };
61
+ }
62
+ function trySpawn(request) {
63
+ try {
64
+ return spawn(request.command, [...request.args], {
65
+ cwd: request.cwd,
66
+ env: { ...request.env },
67
+ stdio: "pipe",
68
+ detached: true,
69
+ });
70
+ }
71
+ catch (error) {
72
+ return { error };
73
+ }
74
+ }
75
+ export function launchAgent(request) {
76
+ const stderr = createStderrTail();
77
+ const child = trySpawn(request);
78
+ if ("error" in child)
79
+ return failedLaunch(stderr, child.error);
80
+ return startedLaunch(child, stderr, request.maxMessageBytes);
81
+ }
82
+ function startedLaunch(child, stderr, maxMessageBytes) {
83
+ const exited = new Promise((resolve) => {
84
+ child.once("error", (error) => resolve({ code: null, signal: null, spawnError: error.message }));
85
+ child.once("exit", (code, signal) => resolve({ code, signal }));
86
+ });
87
+ const stderrEnded = new Promise((resolve) => child.stderr.once("close", () => resolve()));
88
+ child.stdin.on("error", ignore);
89
+ child.stdout.on("error", ignore);
90
+ child.stderr.on("error", ignore);
91
+ child.stderr.on("data", (chunk) => stderr.push(chunk));
92
+ const stream = ndJsonStream(Writable.toWeb(child.stdin), Readable.toWeb(child.stdout), maxMessageBytes === undefined ? undefined : { maxMessageBytes });
93
+ const pid = child.pid;
94
+ let gone = false;
95
+ void exited.then(() => {
96
+ gone = true;
97
+ });
98
+ const kill = () => {
99
+ if (!gone && pid !== undefined)
100
+ killProcessGroup(pid, "SIGKILL");
101
+ };
102
+ return {
103
+ target: { kind: "stream", stream },
104
+ pid,
105
+ stderr,
106
+ exited,
107
+ kill,
108
+ async whenGone(waitMs) {
109
+ const exit = await race(exited, { timeoutMs: waitMs });
110
+ if (exit.kind !== "ok")
111
+ return undefined;
112
+ await race(stderrEnded, { timeoutMs: STDERR_DRAIN_MS });
113
+ return exit.value;
114
+ },
115
+ async terminate(graceMs) {
116
+ if (!gone && pid !== undefined) {
117
+ child.stdin.end();
118
+ killProcessGroup(pid, "SIGTERM");
119
+ const timer = setTimeout(kill, graceMs);
120
+ await exited;
121
+ clearTimeout(timer);
122
+ }
123
+ await exited;
124
+ },
125
+ };
126
+ }
127
+ function describeExit(exit, during, secrets) {
128
+ if (exit === undefined)
129
+ return `its connection closed during ${during}`;
130
+ if (exit.spawnError !== undefined)
131
+ return `it could not be started (${agentTextExcerpt(exit.spawnError, secrets)})`;
132
+ if (exit.signal !== null)
133
+ return `it was killed by ${exit.signal} during ${during}`;
134
+ return `it exited with code ${String(exit.code)} during ${during}`;
135
+ }
136
+ /** The agent process died or its stream closed: BACKEND_UNAVAILABLE with the exit and a redacted stderr excerpt. */
137
+ export async function agentGoneError(during, launched, secrets) {
138
+ const exit = await launched.whenGone(GONE_WAIT_MS);
139
+ const stderr = launched.stderr.excerpt({ maxBytes: EXCERPT_BYTES, secrets });
140
+ const what = describeExit(exit, during, secrets);
141
+ const exitDetails = exit === undefined
142
+ ? {}
143
+ : { exitCode: exit.code, signal: exit.signal, ...(exit.spawnError === undefined ? {} : { spawnError: true }) };
144
+ return backendUnavailable(stderr === "" ? what : `${what}; stderr: ${stderr}`, { during, ...exitDetails, stderr });
145
+ }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Opening an ACP session (S4 spec §6.3 step 1, §6.9): spawn, initialize (form
3
+ * elicitation advertised under ask and full, S4-5 D5-l), capability check, the
4
+ * tool host when the session has tools, then session/new (with the host's server
5
+ * entry and the pre-approval _meta, §6.6) or, for a stored session, session/resume
6
+ * or session/load with the same entry and _meta (resume.ts), then the profile's
7
+ * mode and the model. A new session writes its initial transcript document; a
8
+ * restored one leaves the document as it is (D6-f). Every failure after the spawn
9
+ * kills the agent's process group before it propagates, so a failed open leaves
10
+ * no process behind; the caller stops the tool host. Each agent request is
11
+ * bounded by initializeTimeoutMs (D-c) and by openSignal: close() during open
12
+ * rejects AGENT_SESSION_CLOSED.
13
+ */
14
+ import { type ClientCapabilities } from "@agentclientprotocol/sdk";
15
+ import { type AgentSessionProfile, type BackendOpenContext } from "@nathapp/nax-agent";
16
+ import { type CapabilityRecord } from "#src/client/capabilities";
17
+ import { type AcpLink, type InboundHandlers } from "#src/client/connection";
18
+ import { type LaunchedAgent, type LaunchFn } from "#src/client/launch";
19
+ import type { ResolvedAcpOptions } from "#src/client/options";
20
+ import { type Restore, type RestoredWith } from "#src/client/resume";
21
+ import type { ToolHost } from "#src/client/tool-host";
22
+ export interface OpenedAcp {
23
+ readonly launched: LaunchedAgent;
24
+ readonly link: AcpLink;
25
+ readonly record: CapabilityRecord;
26
+ readonly agentSessionId: string;
27
+ /** The cwd the agent session was created with; a reconnect restores it with this spelling (D6-c). */
28
+ readonly cwd: string;
29
+ /** How a stored session was restored (§6.9); undefined for a new session. */
30
+ readonly restoredWith?: RestoredWith;
31
+ }
32
+ /** `restore`: restore that stored agent session instead of creating one (§6.9). */
33
+ export declare function openAcpSession(options: ResolvedAcpOptions, ctx: BackendOpenContext, handlers: InboundHandlers, launch: LaunchFn, host?: ToolHost, restore?: Restore): Promise<OpenedAcp>;
34
+ /** §6.3 step 1.1: no fs and no terminal (R11); form elicitation under ask and full (§6.8, D5-l). */
35
+ export declare function clientCapabilitiesFor(profile: AgentSessionProfile): ClientCapabilities;
@@ -0,0 +1,154 @@
1
+ /**
2
+ * Opening an ACP session (S4 spec §6.3 step 1, §6.9): spawn, initialize (form
3
+ * elicitation advertised under ask and full, S4-5 D5-l), capability check, the
4
+ * tool host when the session has tools, then session/new (with the host's server
5
+ * entry and the pre-approval _meta, §6.6) or, for a stored session, session/resume
6
+ * or session/load with the same entry and _meta (resume.ts), then the profile's
7
+ * mode and the model. A new session writes its initial transcript document; a
8
+ * restored one leaves the document as it is (D6-f). Every failure after the spawn
9
+ * kills the agent's process group before it propagates, so a failed open leaves
10
+ * no process behind; the caller stops the tool host. Each agent request is
11
+ * bounded by initializeTimeoutMs (D-c) and by openSignal: close() during open
12
+ * rejects AGENT_SESSION_CLOSED.
13
+ */
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";
17
+ import { openConnection } from "#src/client/connection";
18
+ import { backendUnavailable, capabilityUnsupported, closedDuringOpen, EXCERPT_BYTES, openRequestError, rpcErrorOf, } from "#src/client/errors";
19
+ import { agentGoneError, pickCandidate } from "#src/client/launch";
20
+ import { claudeSessionMeta } from "#src/client/pre-approval";
21
+ import { race } from "#src/client/race";
22
+ import { isUsableSessionId, restoreSession, } from "#src/client/resume";
23
+ function chooseLaunch(options) {
24
+ if (options.launch.kind === "explicit")
25
+ return options.launch.candidate;
26
+ const found = pickCandidate(options.launch.candidates, options.env.PATH);
27
+ if (found !== undefined)
28
+ return found;
29
+ const tried = options.launch.candidates.map((candidate) => candidate.command);
30
+ throw backendUnavailable(`no launch command for "${options.agentName}" was found on PATH (tried ${tried.join(", ")})`, {
31
+ tried,
32
+ });
33
+ }
34
+ /** `restore`: restore that stored agent session instead of creating one (§6.9). */
35
+ export async function openAcpSession(options, ctx, handlers, launch, host, restore) {
36
+ if (ctx.openSignal.aborted)
37
+ throw closedDuringOpen(ctx.sessionId);
38
+ const candidate = chooseLaunch(options);
39
+ const launched = launch({ command: candidate.command, args: candidate.args, cwd: ctx.workdir, env: options.env });
40
+ const link = openConnection(launched.target, handlers);
41
+ void launched.exited.then(() => link.close(new NaxError("The ACP agent process exited", "ACP_AGENT_EXITED", { stage: "acp" })));
42
+ try {
43
+ return await establish({ options, ctx, launched, link, host, restore });
44
+ }
45
+ catch (err) {
46
+ launched.kill();
47
+ link.close();
48
+ throw err;
49
+ }
50
+ }
51
+ async function step(o, label, request) {
52
+ const result = await race(request, { timeoutMs: o.options.initializeTimeoutMs, signal: o.ctx.openSignal });
53
+ switch (result.kind) {
54
+ case "ok":
55
+ return result.value;
56
+ case "aborted":
57
+ throw closedDuringOpen(o.ctx.sessionId);
58
+ case "timeout":
59
+ throw backendUnavailable(`${label} timed out after ${o.options.initializeTimeoutMs} ms`, {
60
+ during: label,
61
+ stderr: o.launched.stderr.excerpt({ maxBytes: EXCERPT_BYTES, secrets: o.options.secrets }),
62
+ });
63
+ case "failed": {
64
+ const rpc = rpcErrorOf(result.error);
65
+ if (rpc !== undefined)
66
+ throw openRequestError(label, rpc, o.options.secrets);
67
+ throw await agentGoneError(label, o.launched, o.options.secrets);
68
+ }
69
+ }
70
+ }
71
+ /** §6.3 step 1.1: no fs and no terminal (R11); form elicitation under ask and full (§6.8, D5-l). */
72
+ export function clientCapabilitiesFor(profile) {
73
+ return profile === "ask" || profile === "full" ? { elicitation: { form: {} } } : {};
74
+ }
75
+ async function establish(o) {
76
+ const init = await step(o, "initialize", o.link.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: clientCapabilitiesFor(o.ctx.profile) }));
77
+ if (init.protocolVersion !== PROTOCOL_VERSION) {
78
+ throw backendUnavailable(`the agent speaks ACP protocol version ${String(init.protocolVersion)}; this client speaks ${PROTOCOL_VERSION}`, { protocolVersion: String(init.protocolVersion).slice(0, 32) });
79
+ }
80
+ const record = buildCapabilityRecord(init, o.options.entry);
81
+ const unmet = unmetRequirement(record, {
82
+ profile: o.ctx.profile,
83
+ toolCount: o.ctx.tools.length,
84
+ resume: o.restore !== undefined,
85
+ });
86
+ if (unmet !== undefined)
87
+ throw capabilityUnsupported(unmet.capability, unmet.reason);
88
+ const setup = await sessionSetup(o);
89
+ const session = o.restore === undefined
90
+ ? await newSession(o, setup)
91
+ : await restoreSession(o.restore, record, setup, o.link, (label, request) => step(o, label, request));
92
+ await applyConfig(o, session.agentSessionId, session.configOptions);
93
+ if (o.restore === undefined) {
94
+ await o.ctx.transcriptStore.save(o.ctx.sessionId, initialDoc(o, record, session.agentSessionId));
95
+ }
96
+ return {
97
+ launched: o.launched,
98
+ link: o.link,
99
+ record,
100
+ agentSessionId: session.agentSessionId,
101
+ cwd: session.cwd,
102
+ ...(session.restoredWith === undefined ? {} : { restoredWith: session.restoredWith }),
103
+ };
104
+ }
105
+ async function newSession(o, setup) {
106
+ const created = await step(o, "session/new", o.link.newSession({ cwd: o.ctx.workdir, ...setup }));
107
+ if (!isUsableSessionId(created.sessionId))
108
+ throw backendUnavailable("session/new returned no usable session id");
109
+ return { agentSessionId: created.sessionId, cwd: o.ctx.workdir, configOptions: created.configOptions ?? [] };
110
+ }
111
+ /** §6.3 step 3: start the tool host when the session has tools; its entry and Claude's `_meta` (§6.6, #2365). */
112
+ async function sessionSetup(o) {
113
+ const kind = o.options.entry?.preApproval;
114
+ const meta = claudeSessionMeta(kind, o.ctx.tools.map((tool) => tool.name), o.ctx.profile);
115
+ if (o.host === undefined)
116
+ return meta === undefined ? { mcpServers: [] } : { mcpServers: [], _meta: { ...meta } };
117
+ if (meta === undefined)
118
+ throw capabilityUnsupported("tools", "the agent has no way to pre-approve embedder tools");
119
+ const server = await o.host.start().catch((err) => {
120
+ throw backendUnavailable(`the tool host could not start: ${err instanceof Error ? err.message : String(err)}`);
121
+ });
122
+ return { mcpServers: [server], _meta: { ...meta } };
123
+ }
124
+ /** §6.3 step 5: the profile's mode, then the model. Only values the agent offered are set. */
125
+ async function applyConfig(o, sessionId, offered) {
126
+ const mode = modeFor(o.ctx.profile, o.options.entry);
127
+ if (mode !== undefined && !offersValue(offered, mode.configId, mode.value)) {
128
+ throw capabilityUnsupported("profile", `the agent does not offer ${mode.configId} "${mode.value}"`);
129
+ }
130
+ const afterMode = mode === undefined
131
+ ? offered
132
+ : ((await step(o, "session/set_config_option", o.link.setConfigOption({ sessionId, ...mode }))).configOptions ??
133
+ offered);
134
+ const model = o.options.model;
135
+ if (model === undefined)
136
+ return;
137
+ const configId = modelOptionId(afterMode, model);
138
+ if (configId === undefined)
139
+ throw capabilityUnsupported("model", `the agent offers no model option "${model}"`);
140
+ await step(o, "session/set_config_option", o.link.setConfigOption({ sessionId, configId, value: model }));
141
+ }
142
+ function initialDoc(o, record, agentSessionId) {
143
+ return {
144
+ backend: o.options.kind,
145
+ acp: {
146
+ agentSessionId,
147
+ agent: o.options.agentName,
148
+ ...(record.agentVersion === undefined ? {} : { agentVersion: record.agentVersion }),
149
+ cwd: o.ctx.workdir,
150
+ },
151
+ messages: [],
152
+ savedAt: new Date().toISOString(),
153
+ };
154
+ }
@@ -0,0 +1,46 @@
1
+ import { type AcpAgentName, type AgentRegistryEntry, type LaunchCandidate } from "#src/client/registry";
2
+ export declare const DEFAULT_CANCEL_GRACE_MS = 10000;
3
+ export declare const DEFAULT_INITIALIZE_TIMEOUT_MS = 60000;
4
+ export type AcpAgentSpec = AcpAgentName | {
5
+ readonly name: string;
6
+ readonly command: string;
7
+ readonly args?: readonly string[];
8
+ };
9
+ export interface AcpBackendOptions {
10
+ readonly agent: AcpAgentSpec;
11
+ /** Required: the agent process runs on the host, unsandboxed (R7). */
12
+ readonly allowUnsandboxed: true;
13
+ /** Applied via session/set_config_option (category "model") before open returns. */
14
+ readonly model?: string;
15
+ /** Added to the agent's environment. */
16
+ readonly env?: Readonly<Record<string, string>>;
17
+ /** Default false: the allowlist only. true hands the whole process.env to the agent. */
18
+ readonly inheritEnv?: boolean;
19
+ /** Overrides the registry's launch command (a bare name or an absolute path). */
20
+ readonly command?: string;
21
+ readonly args?: readonly string[];
22
+ readonly cancelGraceMs?: number;
23
+ readonly initializeTimeoutMs?: number;
24
+ }
25
+ export type AcpLaunch = {
26
+ readonly kind: "explicit";
27
+ readonly candidate: LaunchCandidate;
28
+ } | {
29
+ readonly kind: "registry";
30
+ readonly candidates: readonly LaunchCandidate[];
31
+ };
32
+ export interface ResolvedAcpOptions {
33
+ /** "acp:<agent name>". */
34
+ readonly kind: string;
35
+ readonly agentName: string;
36
+ /** Undefined for a custom agent: no modes, no pre-approval, no auth variables. */
37
+ readonly entry: AgentRegistryEntry | undefined;
38
+ readonly launch: AcpLaunch;
39
+ readonly model: string | undefined;
40
+ readonly env: Readonly<Record<string, string>>;
41
+ /** Values redacted from every agent excerpt (D-g). */
42
+ readonly secrets: readonly string[];
43
+ readonly cancelGraceMs: number;
44
+ readonly initializeTimeoutMs: number;
45
+ }
46
+ export declare function resolveAcpOptions(input: unknown, source?: Readonly<Record<string, string | undefined>>): ResolvedAcpOptions;