zapagent 1.14.26 → 1.14.27

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 (49) hide show
  1. package/LICENSE +2 -3
  2. package/README.md +3 -3
  3. package/README.zh-CN.md +3 -3
  4. package/SECURITY.md +3 -2
  5. package/THIRD_PARTY_NOTICES.md +4 -8
  6. package/bundled-dependencies.json +204 -204
  7. package/package.json +1 -1
  8. package/src/App.tsx +19 -6
  9. package/src/agent/remote-agent.ts +150 -0
  10. package/src/agent/remote-turn.ts +72 -0
  11. package/src/agent/wireRunHandlers.ts +5 -2
  12. package/src/agent-factory.ts +19 -2
  13. package/src/approval-facts.ts +20 -3
  14. package/src/commands/dispatcher.ts +47 -3
  15. package/src/commands.ts +4 -0
  16. package/src/config.ts +13 -2
  17. package/src/execution-environment.ts +20 -2
  18. package/src/goal-command.ts +6 -3
  19. package/src/goal-session.ts +1 -1
  20. package/src/goal-turn.ts +1 -1
  21. package/src/headless/runHeadless.ts +2 -1
  22. package/src/hooks/useAgentObjects.ts +8 -0
  23. package/src/hooks/useAgentRunner.ts +50 -1
  24. package/src/permission-policy.ts +5 -2
  25. package/src/permissions.ts +19 -12
  26. package/src/singletons.ts +21 -3
  27. package/src/tool-grants.ts +2 -2
  28. package/src/ui/Transcript.tsx +2 -1
  29. package/src/ui/dialog-approval.tsx +1 -1
  30. package/src/ui/dialog-tool-grant.tsx +2 -2
  31. package/src/ui/footer.tsx +4 -1
  32. package/src/ui/group-logs.ts +1 -1
  33. package/src/ui/live-activity.tsx +1 -1
  34. package/src/ui/slash-palette.tsx +1 -0
  35. package/src/ui/transcript-format.ts +5 -1
  36. package/zapsdk/acp-client/connection.ts +228 -0
  37. package/zapsdk/acp-client/detect.ts +28 -0
  38. package/zapsdk/acp-client/event-mapper.ts +231 -0
  39. package/zapsdk/acp-client/host-handlers.ts +225 -0
  40. package/zapsdk/acp-client/index.ts +6 -0
  41. package/zapsdk/acp-client/run.ts +169 -0
  42. package/zapsdk/acp-client/types.ts +52 -0
  43. package/zapsdk/builtin-tools/acp-agent.ts +188 -0
  44. package/zapsdk/builtin-tools/delegate-detect.ts +1 -1
  45. package/zapsdk/builtin-tools/index.ts +9 -0
  46. package/zapsdk/execution/process.ts +1 -1
  47. package/zapsdk/execution/sandbox.ts +6 -4
  48. package/zapsdk/execution/types.ts +3 -0
  49. package/zapsdk/goal/git-history-snapshot.ts +3 -1
@@ -0,0 +1,225 @@
1
+ import { mkdir, readFile, stat, writeFile } from "node:fs/promises";
2
+ import { dirname, isAbsolute, join, sep } from "node:path";
3
+ import { RequestError, type PermissionOption, type RequestPermissionRequest, type RequestPermissionResponse } from "@agentclientprotocol/sdk";
4
+ import type { ApprovalCallback, ApprovalContext, ApprovalResponse } from "../tools/executor.js";
5
+ import { resolveToolPathCanonical } from "../builtin-tools/filesystem.js";
6
+ import { shellExecutionCommands } from "../utils/shell.js";
7
+ import type { AcpClientHandlers } from "./types.js";
8
+
9
+ export interface AcpHostPolicy {
10
+ agentId: string;
11
+ cwd: string;
12
+ /** Zap's approval gate. Absent → every request is refused. */
13
+ approve?: ApprovalCallback;
14
+ /** Checkpoint hook; called with the canonical path before every write. */
15
+ trackEdit?: (paths: string[]) => Promise<unknown>;
16
+ /** Cancels outstanding approval prompts when the call or turn ends. A
17
+ * function is read per request (session mode: the current turn's signal). */
18
+ signal?: AbortSignal | (() => AbortSignal | undefined);
19
+ }
20
+
21
+ export interface AcpHostHandlers extends AcpClientHandlers {
22
+ /** Canonical paths written through fs/write_text_file. */
23
+ readonly written: Set<string>;
24
+ /** Permission requests answered, for the tool report. */
25
+ readonly decisions: Array<{ title: string; kind?: string; allowed: boolean }>;
26
+ }
27
+
28
+ const READ_MAX_BYTES = 10 * 1024 * 1024;
29
+
30
+ /** The workspace an agent's requests are judged against: inside the cwd,
31
+ * minus zap's protected control directories (as for zap's own file tools). */
32
+ export class AcpWorkspace {
33
+ readonly root: string;
34
+ private readonly protectedRoots: string[];
35
+
36
+ constructor(cwd: string) {
37
+ this.root = resolveToolPathCanonical(cwd, cwd);
38
+ this.protectedRoots = [join(this.root, ".git"), join(this.root, ".zapcode")];
39
+ }
40
+
41
+ /** Canonical absolute path; ACP requires absolute paths. */
42
+ resolve(path: string): string {
43
+ if (!isAbsolute(path)) throw RequestError.invalidParams(undefined, "ACP file paths must be absolute");
44
+ return resolveToolPathCanonical(path, this.root);
45
+ }
46
+
47
+ contains(path: string): boolean { return within(path, this.root); }
48
+ isProtected(path: string): boolean { return this.protectedRoots.some(root => within(path, root)); }
49
+ }
50
+
51
+ function within(path: string, root: string): boolean {
52
+ return path === root || path.startsWith(root.endsWith(sep) ? root : root + sep);
53
+ }
54
+
55
+ /** Requests from an external agent are untrusted. In-workspace file access
56
+ * is approved as zap's own `read_file` / `write_file`, so mode, rules and edit
57
+ * previews apply as for zap's tools. Zap's executor normally confines those
58
+ * tools to the workspace; these handlers bypass the executor, so they
59
+ * enforce that boundary themselves: outside the workspace every access is a
60
+ * one-time prompt, and `.git` / `.zapcode` are never written. */
61
+ export function createAcpHostHandlers(policy: AcpHostPolicy): AcpHostHandlers {
62
+ const written = new Set<string>();
63
+ const decisions: AcpHostHandlers["decisions"] = [];
64
+ const workspace = new AcpWorkspace(policy.cwd);
65
+ const agent = sanitize(policy.agentId);
66
+ const signalFor = (request: AbortSignal) => {
67
+ const outer = typeof policy.signal === "function" ? policy.signal() : policy.signal;
68
+ return outer ? AbortSignal.any([request, outer]) : request;
69
+ };
70
+
71
+ const approve = async (target: ApprovalTarget, signal: AbortSignal): Promise<ApprovalResponse> => {
72
+ if (!policy.approve) return { approved: false, source: "policy", reason: "no approval handler" };
73
+ const pre = policy.approve.precheck?.(target.name, target.args, target.context);
74
+ if (pre !== undefined) return pre;
75
+ return policy.approve(target.name, target.args, signal, target.context);
76
+ };
77
+
78
+ return {
79
+ written,
80
+ decisions,
81
+
82
+ async requestPermission(request: RequestPermissionRequest, signal: AbortSignal): Promise<RequestPermissionResponse> {
83
+ const tool = request.toolCall;
84
+ const title = tool.title ?? "tool call";
85
+ // ACP: once the client cancels the turn, pending permission requests
86
+ // must be answered "cancelled", not rejected.
87
+ const live = signalFor(signal);
88
+ if (live.aborted) return { outcome: { outcome: "cancelled" } };
89
+ const response = await approve(permissionTarget(policy.agentId, request, workspace), live);
90
+ if (live.aborted) return { outcome: { outcome: "cancelled" } };
91
+ const allowed = response === true;
92
+ decisions.push({ title, kind: tool.kind ?? undefined, allowed });
93
+ const option = pickOption(request.options, allowed);
94
+ return option ? { outcome: { outcome: "selected", optionId: option.optionId } } : { outcome: { outcome: "cancelled" } };
95
+ },
96
+
97
+ async readTextFile(request, signal) {
98
+ const path = workspace.resolve(request.path);
99
+ const target: ApprovalTarget = workspace.contains(path)
100
+ ? { name: "read_file", args: { path } }
101
+ : { name: `acp_${agent}_read`, args: { title: "Read a file outside the workspace", paths: [path] } };
102
+ const allowed = await approve(target, signalFor(signal));
103
+ if (allowed !== true) throw RequestError.internalError(undefined, denialText(allowed));
104
+ const info = await stat(path);
105
+ if (!info.isFile()) throw RequestError.invalidParams(undefined, "not a regular file");
106
+ if (info.size > READ_MAX_BYTES) throw RequestError.invalidParams(undefined, `file exceeds ${READ_MAX_BYTES} bytes`);
107
+ let content = (await readFile(path)).toString("utf8");
108
+ if (request.line != null || request.limit != null) {
109
+ const lines = content.split("\n");
110
+ const start = Math.max(0, Math.floor(request.line ?? 1) - 1);
111
+ const limit = request.limit != null ? Math.max(0, Math.floor(request.limit)) : undefined;
112
+ content = lines.slice(start, limit !== undefined ? start + limit : undefined).join("\n");
113
+ }
114
+ return { content };
115
+ },
116
+
117
+ async writeTextFile(request, signal) {
118
+ const path = workspace.resolve(request.path);
119
+ if (workspace.isProtected(path)) {
120
+ throw RequestError.internalError(undefined, "denied by zap: .git and .zapcode are protected and cannot be written");
121
+ }
122
+ const target: ApprovalTarget = workspace.contains(path)
123
+ ? { name: "write_file", args: { path, content: request.content } }
124
+ : { name: `acp_${agent}_edit`, args: { title: "Write a file outside the workspace", paths: [path] } };
125
+ const allowed = await approve(target, signalFor(signal));
126
+ if (allowed !== true) throw RequestError.internalError(undefined, denialText(allowed));
127
+ if (policy.trackEdit) {
128
+ try { await policy.trackEdit([path]); } catch { /* checkpoint coverage is best-effort, as for write_file */ }
129
+ }
130
+ await mkdir(dirname(path), { recursive: true });
131
+ await writeFile(path, request.content, "utf8");
132
+ written.add(path);
133
+ },
134
+ };
135
+ }
136
+
137
+ export interface ApprovalTarget {
138
+ name: string;
139
+ args: Record<string, unknown>;
140
+ context?: ApprovalContext;
141
+ }
142
+
143
+ /** ACP permission requests carry a tool kind and free-form input. Where the
144
+ * request names concrete in-workspace effects, it maps onto zap's own tool so
145
+ * the same policy applies:
146
+ * - commands → `bash` with facts that mark them as running outside zap's
147
+ * sandbox (the agent executes them), so dangerous-command and command rules
148
+ * apply but the sandboxed-command auto-allow does not;
149
+ * - a single in-workspace, unprotected file write with known content →
150
+ * `write_file` (edit preview, acceptEdits, workspace scope);
151
+ * - a single in-workspace delete/read → `delete_file` / `read_file`.
152
+ * Anything else is `acp_<agent>_<kind>`: approved once at a time, read-only
153
+ * only for read/search/think, so plan mode refuses the rest. */
154
+ export function permissionTarget(agentId: string, request: RequestPermissionRequest, workspace: AcpWorkspace): ApprovalTarget {
155
+ const tool = request.toolCall;
156
+ const input = tool.rawInput && typeof tool.rawInput === "object" ? tool.rawInput as Record<string, unknown> : {};
157
+ // codex-acp: `command` (string or argv); agy: `CommandLine`.
158
+ const raw = input.command ?? input.CommandLine;
159
+ const command = typeof raw === "string" ? raw
160
+ : Array.isArray(raw) && raw.length && raw.every(part => typeof part === "string") ? (raw as string[]).map(quoteArg).join(" ")
161
+ : undefined;
162
+ if (tool.kind === "execute" && command) {
163
+ const args = { command, description: tool.title ?? undefined };
164
+ return { name: "bash", args, context: {
165
+ cwd: workspace.root, workspaceRoot: workspace.root,
166
+ shell: { syntax: process.platform === "win32" ? "unknown" : "posix", filesystem: "host" },
167
+ authorization: {
168
+ readOnly: false, editOnly: false,
169
+ // Not zap's sandbox and not zap's sandbox-escape grant: the agent
170
+ // runs it. workspaceShell=false keeps command rules from treating it
171
+ // as a sandboxed workspace command.
172
+ sandboxEscape: false, workspaceShell: false,
173
+ shellCommands: shellExecutionCommands(args),
174
+ },
175
+ } };
176
+ }
177
+
178
+ const paths = [...new Set([
179
+ ...(tool.locations ?? []).map(location => location.path),
180
+ ...(tool.content ?? []).flatMap(item => item.type === "diff" ? [item.path] : []),
181
+ ])].filter(path => isAbsolute(path)).map(path => workspace.resolve(path));
182
+ const only = paths.length === 1 ? paths[0]! : undefined;
183
+ if (only && workspace.contains(only)) {
184
+ const writable = !workspace.isProtected(only);
185
+ if (tool.kind === "edit" && writable) {
186
+ const diff = tool.content?.find(item => item.type === "diff" && workspace.resolve(item.path) === only);
187
+ // agy: { Content, Path }; others: content / new_content.
188
+ const content = diff?.type === "diff" ? diff.newText : [input.Content, input.content, input.new_content].find(value => typeof value === "string");
189
+ if (typeof content === "string") return { name: "write_file", args: { path: only, content } };
190
+ }
191
+ if (tool.kind === "delete" && writable) return { name: "delete_file", args: { path: only } };
192
+ if (tool.kind === "read") return { name: "read_file", args: { path: only } };
193
+ }
194
+ return {
195
+ name: `acp_${sanitize(agentId)}_${tool.kind ?? "other"}`,
196
+ args: {
197
+ title: tool.title ?? "tool call",
198
+ ...(paths.length ? { paths } : {}),
199
+ ...(tool.rawInput !== undefined ? { input: tool.rawInput } : {}),
200
+ },
201
+ };
202
+ }
203
+
204
+ /** POSIX-quote one argv element unless it is plainly safe. */
205
+ function quoteArg(arg: string): string {
206
+ return /^[\w@%+=:,./-]+$/.test(arg) ? arg : `'${arg.replace(/'/g, "'\\''")}'`;
207
+ }
208
+
209
+ function pickOption(options: PermissionOption[], allowed: boolean): PermissionOption | undefined {
210
+ // Never persist a grant inside the external agent: zap owns "always".
211
+ const order = allowed ? ["allow_once", "allow_always"] : ["reject_once", "reject_always"];
212
+ for (const kind of order) {
213
+ const match = options.find(option => option.kind === kind);
214
+ if (match) return match;
215
+ }
216
+ return undefined;
217
+ }
218
+
219
+ function denialText(response: ApprovalResponse): string {
220
+ return typeof response === "object" ? `denied by zap: ${response.reason}` : "denied by zap";
221
+ }
222
+
223
+ function sanitize(value: string): string {
224
+ return value.replace(/[^a-zA-Z0-9_-]/g, "_");
225
+ }
@@ -0,0 +1,6 @@
1
+ export { AcpClientConnection, stdioTransport, inProcessTransport, type AcpTransport, type AcpPromptOptions } from "./connection.js";
2
+ export { AcpEventMapper, acpUsage, contentText } from "./event-mapper.js";
3
+ export { createAcpHostHandlers, type AcpHostPolicy, type AcpHostHandlers } from "./host-handlers.js";
4
+ export { AcpAgentSession, runAcpTask, type AcpSessionStartOptions, type AcpTurnOptions, type AcpTurnResult, type AcpTaskOptions, type AcpTaskResult } from "./run.js";
5
+ export { detectAcpAgents, KNOWN_ACP_AGENTS } from "./detect.js";
6
+ export { AcpClientError, type AcpAgentSpec, type AcpClientHandlers } from "./types.js";
@@ -0,0 +1,169 @@
1
+ import type {
2
+ AvailableCommand, ContentBlock, PlanEntry, SessionConfigOption, SessionModeState, SessionUpdate, StopReason,
3
+ } from "@agentclientprotocol/sdk";
4
+ import type { AgentEvent } from "../agent/events.js";
5
+ import type { TokenUsage } from "../core/types.js";
6
+ import { AcpClientConnection, type AcpTransport } from "./connection.js";
7
+ import { AcpEventMapper, acpUsage } from "./event-mapper.js";
8
+ import { AcpClientError, type AcpAgentSpec, type AcpClientHandlers } from "./types.js";
9
+
10
+ export interface AcpSessionStartOptions {
11
+ spec: AcpAgentSpec;
12
+ cwd: string;
13
+ transport: AcpTransport;
14
+ handlers: AcpClientHandlers;
15
+ /** Resume this agent session when the agent supports session/load. */
16
+ sessionId?: string;
17
+ /** Overrides spec.mode. */
18
+ mode?: string;
19
+ signal?: AbortSignal;
20
+ clientVersion?: string;
21
+ /** Bound for initialize/session setup; prompts are bounded by their signal. */
22
+ setupTimeoutMs?: number;
23
+ }
24
+
25
+ export interface AcpTurnOptions {
26
+ signal?: AbortSignal;
27
+ /** Event path prefix for nested rendering (subagent path). */
28
+ path?: string[];
29
+ onEvent?: (event: AgentEvent) => void;
30
+ }
31
+
32
+ export interface AcpTurnResult {
33
+ stopReason: StopReason;
34
+ report: string;
35
+ toolCalls: number;
36
+ plan: PlanEntry[];
37
+ usage?: TokenUsage;
38
+ }
39
+
40
+ /** A live ACP session on one agent process. Survives across prompts, so a
41
+ * host can hold a multi-turn conversation; dispose with `close()`. */
42
+ export class AcpAgentSession {
43
+ modes?: SessionModeState | null;
44
+ configOptions?: SessionConfigOption[] | null;
45
+ availableCommands: AvailableCommand[] = [];
46
+ /** Setup steps the agent rejected (mode/config/model); the session continues. */
47
+ readonly warnings: string[] = [];
48
+ private turn?: (update: SessionUpdate) => void;
49
+
50
+ private constructor(
51
+ readonly connection: AcpClientConnection,
52
+ readonly spec: AcpAgentSpec,
53
+ readonly sessionId: string,
54
+ readonly resumed: boolean,
55
+ ) {}
56
+
57
+ static async start(options: AcpSessionStartOptions): Promise<AcpAgentSession> {
58
+ const { spec, signal } = options;
59
+ const setup = { signal, timeoutMs: options.setupTimeoutMs ?? 60_000 };
60
+ const connection = await AcpClientConnection.open(options.transport, options.handlers,
61
+ { clientVersion: options.clientVersion, ...setup });
62
+ try {
63
+ let session: AcpAgentSession;
64
+ if (options.sessionId) {
65
+ await connection.loadSession(options.sessionId, options.cwd, setup);
66
+ session = new AcpAgentSession(connection, spec, options.sessionId, true);
67
+ } else {
68
+ const created = await connection.newSession(options.cwd, setup);
69
+ session = new AcpAgentSession(connection, spec, created.sessionId, false);
70
+ session.modes = created.modes;
71
+ session.configOptions = created.configOptions;
72
+ if (spec.model) {
73
+ // Agents expose the model as a "model" config option (agy, codex);
74
+ // the unstable session/set_model is only a fallback.
75
+ const model = spec.model;
76
+ const asOption = created.configOptions?.some(option => option.id === "model");
77
+ await session.attempt(`model ${model}`, () => asOption
78
+ ? connection.setConfigOption(created.sessionId, "model", model)
79
+ : connection.setModel(created.sessionId, model));
80
+ }
81
+ for (const [configId, value] of Object.entries(spec.config ?? {})) {
82
+ await session.attempt(`config ${configId}=${value}`, () => connection.setConfigOption(created.sessionId, configId, value));
83
+ }
84
+ }
85
+ const mode = options.mode ?? spec.mode;
86
+ if (mode) await session.attempt(`mode ${mode}`, () => connection.setMode(session.sessionId, mode));
87
+ return session;
88
+ } catch (error) {
89
+ await connection.close();
90
+ throw error;
91
+ }
92
+ }
93
+
94
+ get agentName(): string { return this.connection.agentName; }
95
+ get resumable(): boolean { return !!this.connection.info.agentCapabilities?.loadSession; }
96
+ get supportsImages(): boolean { return !!this.connection.info.agentCapabilities?.promptCapabilities?.image; }
97
+
98
+ /** One prompt turn. Updates outside a turn (command lists, mode changes)
99
+ * are tracked on the session as well. */
100
+ async prompt(content: string | ContentBlock[], options: AcpTurnOptions = {}): Promise<AcpTurnResult> {
101
+ const mapper = new AcpEventMapper(options.path ?? []);
102
+ const emit = (events: AgentEvent[]) => { for (const event of events) options.onEvent?.(event); };
103
+ this.turn = update => emit(mapper.map(update));
104
+ const blocks = typeof content === "string" ? [{ type: "text" as const, text: content }] : content;
105
+ let response;
106
+ try {
107
+ response = await this.connection.prompt(this.sessionId, blocks, {
108
+ signal: options.signal, onUpdate: update => this.observe(update),
109
+ });
110
+ } catch (error) {
111
+ emit(mapper.finish(error instanceof AcpClientError && error.code === "cancelled" ? "cancelled" : "error"));
112
+ throw error;
113
+ } finally {
114
+ this.turn = undefined;
115
+ }
116
+ emit(mapper.finish(response.stopReason));
117
+ return {
118
+ stopReason: response.stopReason,
119
+ report: mapper.reportText,
120
+ toolCalls: mapper.toolCallCount,
121
+ plan: mapper.plan,
122
+ usage: acpUsage(response.usage),
123
+ };
124
+ }
125
+
126
+ async setMode(modeId: string): Promise<void> {
127
+ await this.connection.setMode(this.sessionId, modeId);
128
+ if (this.modes) this.modes = { ...this.modes, currentModeId: modeId };
129
+ }
130
+
131
+ async close(): Promise<void> { await this.connection.close(); }
132
+
133
+ private observe(update: SessionUpdate): void {
134
+ if (update.sessionUpdate === "available_commands_update") this.availableCommands = update.availableCommands;
135
+ else if (update.sessionUpdate === "current_mode_update" && this.modes) this.modes = { ...this.modes, currentModeId: update.currentModeId };
136
+ else if (update.sessionUpdate === "config_option_update") this.configOptions = update.configOptions;
137
+ this.turn?.(update);
138
+ }
139
+
140
+ private async attempt(label: string, step: () => Promise<void>): Promise<void> {
141
+ try { await step(); }
142
+ catch (error) { this.warnings.push(`${label}: ${error instanceof Error ? error.message.split("\n")[0] : String(error)}`); }
143
+ }
144
+ }
145
+
146
+ export interface AcpTaskOptions extends AcpSessionStartOptions, AcpTurnOptions {
147
+ task: string;
148
+ }
149
+
150
+ export interface AcpTaskResult extends AcpTurnResult {
151
+ agentName: string;
152
+ sessionId: string;
153
+ resumed: boolean;
154
+ /** The agent supports session/load, so `sessionId` can continue later. */
155
+ resumable: boolean;
156
+ warnings: string[];
157
+ }
158
+
159
+ /** One-shot: start a session, run one prompt, always close the transport. */
160
+ export async function runAcpTask(options: AcpTaskOptions): Promise<AcpTaskResult> {
161
+ const session = await AcpAgentSession.start(options);
162
+ try {
163
+ const turn = await session.prompt(options.task, options);
164
+ return { ...turn, agentName: session.agentName, sessionId: session.sessionId, resumed: session.resumed,
165
+ resumable: session.resumable, warnings: [...session.warnings] };
166
+ } finally {
167
+ await session.close();
168
+ }
169
+ }
@@ -0,0 +1,52 @@
1
+ import type {
2
+ ReadTextFileRequest, ReadTextFileResponse, RequestPermissionRequest,
3
+ RequestPermissionResponse, WriteTextFileRequest,
4
+ } from "@agentclientprotocol/sdk";
5
+
6
+ /** One external agent zap can drive over ACP. Mirrors `acpAgents[]` in the
7
+ * app config; the SDK never reads config files itself. */
8
+ export interface AcpAgentSpec {
9
+ id: string;
10
+ /** Executable (absolute or resolved on PATH) that speaks ACP on stdio. */
11
+ command: string;
12
+ args?: string[];
13
+ /** Extra environment values. The agent otherwise inherits zap's
14
+ * environment, like any host process zap starts; zap's provider keys live
15
+ * in its config file, not the environment, and are never passed. */
16
+ env?: Record<string, string>;
17
+ /** Human label for tool descriptions and UI. */
18
+ name?: string;
19
+ description?: string;
20
+ /** The agent edits files or runs commands by itself instead of through ACP
21
+ * fs/terminal requests, so zap permissions and checkpoints do not cover
22
+ * those effects. Git change summaries remain the fallback evidence. */
23
+ selfGoverned?: boolean;
24
+ /** Model id; set through the agent's `model` config option, or the
25
+ * unstable `session/set_model` when the agent has no such option. */
26
+ model?: string;
27
+ /** Session mode to select after session/new (`session/set_mode`). */
28
+ mode?: string;
29
+ /** Session config options to apply after session/new
30
+ * (`session/set_config_option`), e.g. `{ thought_level: "high" }`. */
31
+ config?: Record<string, string>;
32
+ /** Per-call timeout override in ms. */
33
+ timeoutMs?: number;
34
+ }
35
+
36
+ /** Host decisions for requests the agent sends back to zap. Every handler is
37
+ * optional; a missing handler means the capability is not advertised (fs) or
38
+ * the request is refused (permission). */
39
+ export interface AcpClientHandlers {
40
+ requestPermission?(request: RequestPermissionRequest, signal: AbortSignal): Promise<RequestPermissionResponse>;
41
+ readTextFile?(request: ReadTextFileRequest, signal: AbortSignal): Promise<ReadTextFileResponse>;
42
+ writeTextFile?(request: WriteTextFileRequest, signal: AbortSignal): Promise<void>;
43
+ }
44
+
45
+ export class AcpClientError extends Error {
46
+ constructor(message: string, readonly code:
47
+ | "spawn_failed" | "exited" | "initialize_failed" | "session_failed"
48
+ | "prompt_failed" | "timeout" | "cancelled" | "auth_required", readonly detail?: string) {
49
+ super(detail ? `${message}\n${detail}` : message);
50
+ this.name = "AcpClientError";
51
+ }
52
+ }
@@ -0,0 +1,188 @@
1
+ import { z } from "zod";
2
+ import { relative } from "node:path";
3
+ import type { Tool, ToolResult } from "../tools/types.js";
4
+ import type { AgentEventHandler } from "../agent/events.js";
5
+ import type { ApprovalCallback } from "../tools/executor.js";
6
+ import { createLocalProcessBroker } from "../execution/process.js";
7
+ import { integrationGitWriteRoots } from "../execution/workspace-runtime.js";
8
+ import { currentRuntimeObservation, observeRuntime } from "../runtime/observation.js";
9
+ import { resolveToolPath, resolveToolPathCanonical } from "./filesystem.js";
10
+ import { diffSnapshots, formatChangeSummary, gitStatusSnapshot } from "./delegate-changes.js";
11
+ import { stdioTransport, type AcpTransport } from "../acp-client/connection.js";
12
+ import { createAcpHostHandlers } from "../acp-client/host-handlers.js";
13
+ import { runAcpTask, type AcpTaskResult } from "../acp-client/run.js";
14
+ import { AcpClientError, type AcpAgentSpec } from "../acp-client/types.js";
15
+
16
+ export interface AcpAgentToolOptions {
17
+ agents: AcpAgentSpec[];
18
+ onEvent?: AgentEventHandler;
19
+ defaultCwd?: string;
20
+ /** Zap's approval gate for the agent's permission and fs requests. */
21
+ approve?: ApprovalCallback;
22
+ /** Checkpoint hook for writes the agent makes through fs/write_text_file. */
23
+ trackEdit?: (paths: string[]) => Promise<unknown>;
24
+ /** Default 1_200_000 (20 min). */
25
+ timeoutMs?: number;
26
+ clientVersion?: string;
27
+ /** Tests inject an in-process agent instead of spawning. */
28
+ transportFactory?: (spec: AcpAgentSpec, cwd: string) => AcpTransport;
29
+ }
30
+
31
+ const TASK_MAX_CHARS = 100_000;
32
+
33
+ export const ACP_AGENT_TOOL = "acp_agent";
34
+
35
+ export function acpAgentTool(opts: AcpAgentToolOptions): Tool | null {
36
+ if (!opts.agents.length) return null;
37
+ const ids = opts.agents.map(agent => agent.id) as [string, ...string[]];
38
+ const byId = new Map(opts.agents.map(agent => [agent.id, agent]));
39
+ const defaultTimeout = opts.timeoutMs ?? 1_200_000;
40
+ const maxTimeout = Math.max(defaultTimeout, ...opts.agents.map(agent => agent.timeoutMs ?? 0));
41
+
42
+ return {
43
+ definition: {
44
+ name: ACP_AGENT_TOOL,
45
+ checkpointTracking: "unsupported",
46
+ description: [
47
+ "Hand a task to an external coding agent over the Agent Client Protocol and return its report.",
48
+ `Available: ${opts.agents.map(agent => `\`${agent.id}\`${agent.description ? ` (${agent.description})` : ""}`).join(", ")}.`,
49
+ "Use for self-contained work that benefits from a different agent; work directly for small edits.",
50
+ "The agent's file reads, writes and permission requests go through zap's approvals.",
51
+ "Returns the agent's final message, files changed, and a session id for follow-ups.",
52
+ ].join(" "),
53
+ parameters: z.object({
54
+ agent: z.enum(ids),
55
+ task: z.string().describe("Goal, relevant context, and expected deliverable. For a follow-up in an existing session, only the new instruction."),
56
+ cwd: z.string().optional().describe("Working directory. Defaults to zap's cwd."),
57
+ session_id: z.string().optional().describe("Session id from a prior acp_agent result with the same agent, to continue that conversation."),
58
+ mode: z.string().optional().describe("Agent session mode id, when the agent offers modes."),
59
+ }),
60
+ permission: "confirm",
61
+ timeoutMs: maxTimeout + 30_000,
62
+ sandboxAware: true,
63
+ executionLocation: "host",
64
+ resolveEffects: (args, context) => {
65
+ const base = opts.defaultCwd ?? context.cwd;
66
+ const cwd = resolveToolPathCanonical((args.cwd as string | undefined) ?? base, base);
67
+ return {
68
+ filesystem: [
69
+ { kind: "filesystem", operation: "read", paths: [cwd] },
70
+ { kind: "filesystem", operation: "modify", paths: [cwd] },
71
+ ...integrationGitWriteRoots(cwd).map(path => ({ kind: "filesystem" as const, operation: "modify" as const, paths: [path] })),
72
+ ],
73
+ network: [{ kind: "network", operation: "connect", destinations: ["*"], methods: [] }],
74
+ // External agents keep their own state, credentials and endpoints;
75
+ // they run on the host like an approved unsandboxed command. Their
76
+ // fs and permission requests still pass through zap.
77
+ process: [{ kind: "process", operation: "spawn", commandClass: "acp-agent", background: false, unsandboxed: true }],
78
+ external: [],
79
+ workspace: { mode: "root-integration" },
80
+ confidence: "declared",
81
+ };
82
+ },
83
+ },
84
+
85
+ handler: async (args, signal, context): Promise<ToolResult> => {
86
+ const spec = byId.get(String(args.agent));
87
+ if (!spec) return { success: false, output: "", error: `ACP agent ${String(args.agent)} is not configured.` };
88
+ const task = String(args.task ?? "");
89
+ if (!task.trim()) return { success: false, output: "", error: "task is empty" };
90
+ if (task.length > TASK_MAX_CHARS) {
91
+ return { success: false, output: "", error: `Task is too long (${task.length} chars > ${TASK_MAX_CHARS}). Put details in files under cwd and reference them.` };
92
+ }
93
+ const base = opts.defaultCwd ?? process.cwd();
94
+ const cwd = resolveToolPathCanonical(resolveToolPath((args.cwd as string | undefined) ?? base, base), base);
95
+ const timeoutMs = spec.timeoutMs ?? defaultTimeout;
96
+
97
+ const subagentId = `acp_${spec.id}_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 6).padEnd(4, "0")}`;
98
+ const observation = currentRuntimeObservation();
99
+ const observe = (phase: "starting" | "running" | "failed" | "cancelled" | "exited") => {
100
+ if (observation) observeRuntime({ kind: "external_run", scope: observation.scope, childRunId: subagentId,
101
+ toolCallId: context?.toolCallId, step: context?.step, phase, at: Date.now() }, observation);
102
+ };
103
+
104
+ const processBroker = context?.process ?? createLocalProcessBroker(signal);
105
+ const before = await gitStatusSnapshot(cwd, processBroker);
106
+ if (signal?.aborted) return { success: false, output: "", error: "aborted" };
107
+
108
+ const controller = new AbortController();
109
+ const onAbort = () => controller.abort(signal?.reason);
110
+ signal?.addEventListener("abort", onAbort, { once: true });
111
+ let timedOut = false;
112
+ const timer = setTimeout(() => { timedOut = true; controller.abort(new Error("timeout")); }, timeoutMs);
113
+ timer.unref?.();
114
+
115
+ const handlers = createAcpHostHandlers({ agentId: spec.id, cwd, approve: opts.approve,
116
+ trackEdit: opts.trackEdit, signal: controller.signal });
117
+ opts.onEvent?.({ type: "sub_agent_started", subagentId, agentType: spec.id, task, path: [] });
118
+ observe("starting");
119
+
120
+ let result: AcpTaskResult | undefined;
121
+ let failure: unknown;
122
+ const startedAt = Date.now();
123
+ try {
124
+ const transport = opts.transportFactory?.(spec, cwd) ?? stdioTransport(processBroker.spawnCommand(spec.command, spec.args ?? [], {
125
+ cwd, hostHome: true, environment: spec.env, stdin: "pipe",
126
+ }));
127
+ observe("running");
128
+ result = await runAcpTask({
129
+ spec, task, cwd, transport, handlers,
130
+ sessionId: (args.session_id as string | undefined)?.trim() || undefined,
131
+ mode: (args.mode as string | undefined)?.trim() || undefined,
132
+ path: [subagentId],
133
+ onEvent: opts.onEvent,
134
+ signal: controller.signal,
135
+ clientVersion: opts.clientVersion,
136
+ });
137
+ } catch (error) {
138
+ failure = error;
139
+ } finally {
140
+ clearTimeout(timer);
141
+ signal?.removeEventListener("abort", onAbort);
142
+ }
143
+
144
+ const aborted = !!signal?.aborted;
145
+ const after = await gitStatusSnapshot(cwd, processBroker);
146
+ const changes = diffSnapshots(before, after);
147
+ // A timeout or abort the agent honoured still returns a result with
148
+ // stopReason "cancelled"; that is not a completed task.
149
+ const success = !!result && !failure && !aborted && !timedOut
150
+ && result.stopReason !== "refusal" && result.stopReason !== "cancelled";
151
+ observe(aborted ? "cancelled" : success ? "exited" : "failed");
152
+ opts.onEvent?.({ type: "sub_agent_finished", subagentId, agentType: spec.id, success,
153
+ usage: result?.usage, steps: result?.toolCalls, path: [] });
154
+
155
+ const changeText = changes ? formatChangeSummary(spec.id, cwd, changes) : "";
156
+ // subagentId links this row to its nested agent rows in the transcript.
157
+ const meta = { subagentId, agent: spec.id, agentName: result?.agentName, durationMs: Date.now() - startedAt,
158
+ sessionId: result?.sessionId, resumed: result?.resumed, stopReason: result?.stopReason, usage: result?.usage,
159
+ changes, written: [...handlers.written], permissions: handlers.decisions, warnings: result?.warnings };
160
+
161
+ if (!result) {
162
+ const reason = aborted ? "aborted"
163
+ : timedOut ? `${spec.id} timed out after ${Math.round(timeoutMs / 1000)}s`
164
+ : `${spec.id} failed: ${failure instanceof Error ? failure.message : String(failure)}`
165
+ + (failure instanceof AcpClientError && failure.code === "auth_required"
166
+ ? `\nThe agent reported an authentication problem; sign in with its own CLI (\`${spec.command}\`) if needed.` : "");
167
+ return { success: false, output: changeText, error: reason, meta };
168
+ }
169
+
170
+ const sections: string[] = [result.report || "_(The agent ended its turn without a message.)_"];
171
+ if (result.stopReason !== "end_turn") sections.push(`_Stop reason: ${result.stopReason}_`);
172
+ const notes: string[] = [];
173
+ if (handlers.written.size) notes.push(`Written through zap: ${[...handlers.written].map(path => relative(cwd, path) || path).join(", ")}`);
174
+ const denied = handlers.decisions.filter(decision => !decision.allowed);
175
+ if (denied.length) notes.push(`Denied by zap: ${denied.map(decision => decision.title).join("; ")}`);
176
+ if (result.warnings.length) notes.push(`Setup warnings: ${result.warnings.join("; ")}`);
177
+ if (spec.selfGoverned && changeText) notes.push(`${spec.id} edits files directly; zap checkpoints do not cover those changes.`);
178
+ if (changeText) sections.push(`---\n${changeText}`);
179
+ if (notes.length) sections.push(notes.map(note => `_${note}_`).join("\n"));
180
+ if (result.resumable) sections.push(`_Session: pass \`session_id="${result.sessionId}"\` with agent="${spec.id}" to continue._`);
181
+ const error = success ? undefined
182
+ : timedOut ? `${spec.id} timed out after ${Math.round(timeoutMs / 1000)}s; partial report above.`
183
+ : aborted ? "aborted"
184
+ : `stop reason: ${result.stopReason}`;
185
+ return { success, output: sections.join("\n\n"), error, meta };
186
+ },
187
+ };
188
+ }
@@ -12,7 +12,7 @@ export interface DetectProvidersOptions {
12
12
  pathEnv?: string;
13
13
  }
14
14
 
15
- async function which(name: string, pathEnv = process.env.PATH ?? ""): Promise<string | null> {
15
+ export async function which(name: string, pathEnv = process.env.PATH ?? ""): Promise<string | null> {
16
16
  if (isAbsolute(name)) {
17
17
  return await isExecutable(name) ? name : null;
18
18
  }