zapagent 1.14.26 → 1.14.28

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 (53) 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 +187 -187
  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/agent/loop.ts +3 -1
  44. package/zapsdk/agent/single-call.ts +4 -2
  45. package/zapsdk/builtin-tools/acp-agent.ts +188 -0
  46. package/zapsdk/builtin-tools/delegate-detect.ts +1 -1
  47. package/zapsdk/builtin-tools/index.ts +9 -0
  48. package/zapsdk/core/llm.ts +2 -0
  49. package/zapsdk/core/providers/openai-responses.ts +25 -7
  50. package/zapsdk/execution/process.ts +1 -1
  51. package/zapsdk/execution/sandbox.ts +6 -4
  52. package/zapsdk/execution/types.ts +3 -0
  53. 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
+ }
@@ -516,6 +516,7 @@ export class LoopAgent {
516
516
  private storageSessionId: string;
517
517
  private storageProjectCwd: string;
518
518
  private sessionId: string;
519
+ private readonly providerSessionId: string;
519
520
  private onRunStart?: LoopAgentOptions["onRunStart"];
520
521
  private onRunEnd?: (ctx: { turnStartIndex: number; sessionId: string }) => Promise<void>;
521
522
  // onRetry surfaces a system log via the observation event bus so the
@@ -601,6 +602,7 @@ export class LoopAgent {
601
602
  this.storageSessionId = options.storageSessionId ?? randomUUID();
602
603
  this.storageProjectCwd = options.storageProjectCwd ?? process.cwd();
603
604
  this.sessionId = options.sessionId ?? "default";
605
+ this.providerSessionId = options.sessionId ?? this.storageSessionId;
604
606
  this.onRunStart = options.onRunStart;
605
607
  this.onRunEnd = options.onRunEnd;
606
608
  this.contextWindow = nonNegativeInteger(options.contextWindow);
@@ -2270,7 +2272,7 @@ export class LoopAgent {
2270
2272
  private providerCallOptions(step: number, maxOutputTokens: number | undefined, signal?: AbortSignal): LLMCallOptions {
2271
2273
  const requestId = nextContentId("request");
2272
2274
  let observedAttempt: number | undefined;
2273
- const options: LLMCallOptions = { maxOutputTokens, signal,
2275
+ const options: LLMCallOptions = { maxOutputTokens, signal, sessionId: this.providerSessionId,
2274
2276
  deadline: signal ? this.providerDeadlines.get(signal) : undefined, onRequestEvent: request => {
2275
2277
  if (request.cacheShape && observedAttempt !== request.attempt) {
2276
2278
  observedAttempt = request.attempt;
@@ -1,3 +1,4 @@
1
+ import { randomUUID } from "node:crypto";
1
2
  import type { LLMProvider } from "../core/llm.js";
2
3
  import type { Message, TokenUsage } from "../core/types.js";
3
4
  import {
@@ -52,7 +53,8 @@ export class SingleCallAgent {
52
53
 
53
54
  // First LLM call
54
55
  const tools = this.registry.definitions();
55
- const response = await this.provider.call(messages, tools);
56
+ const options = { sessionId: this.sessionId ?? randomUUID() };
57
+ const response = await this.provider.call(messages, tools, options);
56
58
  accumulateTokenUsage(totalUsage, response.usage);
57
59
 
58
60
  // If no tool calls, return directly
@@ -82,7 +84,7 @@ export class SingleCallAgent {
82
84
  }
83
85
 
84
86
  // Second LLM call with tool results
85
- const finalResponse = await this.provider.call(messages, tools);
87
+ const finalResponse = await this.provider.call(messages, tools, options);
86
88
  accumulateTokenUsage(totalUsage, finalResponse.usage);
87
89
 
88
90
  return { text: finalResponse.text, toolResults, totalUsage };