zapagent 1.14.25 → 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.
- package/LICENSE +2 -3
- package/README.md +3 -3
- package/README.zh-CN.md +3 -3
- package/SECURITY.md +3 -2
- package/THIRD_PARTY_NOTICES.md +4 -8
- package/bundled-dependencies.json +204 -204
- package/package.json +1 -1
- package/src/App.tsx +19 -6
- package/src/agent/contextAttachments.ts +4 -2
- package/src/agent/remote-agent.ts +150 -0
- package/src/agent/remote-turn.ts +72 -0
- package/src/agent/wireRunHandlers.ts +5 -2
- package/src/agent-factory.ts +20 -11
- package/src/approval-facts.ts +20 -3
- package/src/commands/dispatcher.ts +47 -3
- package/src/commands.ts +4 -0
- package/src/config.ts +13 -2
- package/src/execution-environment.ts +20 -2
- package/src/goal-command.ts +6 -3
- package/src/goal-session.ts +1 -1
- package/src/goal-turn.ts +1 -1
- package/src/headless/goalPhase.ts +3 -3
- package/src/headless/runHeadless.ts +6 -6
- package/src/hooks/useAgentObjects.ts +8 -0
- package/src/hooks/useAgentRunner.ts +50 -1
- package/src/permission-policy.ts +5 -2
- package/src/permissions.ts +19 -12
- package/src/singletons.ts +25 -17
- package/src/tool-grants.ts +2 -2
- package/src/ui/Transcript.tsx +2 -1
- package/src/ui/dialog-approval.tsx +1 -1
- package/src/ui/dialog-rewind.tsx +1 -1
- package/src/ui/dialog-tool-grant.tsx +2 -2
- package/src/ui/footer.tsx +4 -1
- package/src/ui/group-logs.ts +1 -1
- package/src/ui/live-activity.tsx +1 -1
- package/src/ui/slash-palette.tsx +1 -0
- package/src/ui/transcript-format.ts +5 -1
- package/zapsdk/acp-client/connection.ts +228 -0
- package/zapsdk/acp-client/detect.ts +28 -0
- package/zapsdk/acp-client/event-mapper.ts +231 -0
- package/zapsdk/acp-client/host-handlers.ts +225 -0
- package/zapsdk/acp-client/index.ts +6 -0
- package/zapsdk/acp-client/run.ts +169 -0
- package/zapsdk/acp-client/types.ts +52 -0
- package/zapsdk/agent/loop.ts +51 -4
- package/zapsdk/agent/tool-execution-guards.ts +23 -37
- package/zapsdk/builtin-tools/acp-agent.ts +188 -0
- package/zapsdk/builtin-tools/delegate-detect.ts +1 -1
- package/zapsdk/builtin-tools/index.ts +20 -16
- package/zapsdk/builtin-tools/plan-mode.ts +1 -1
- package/zapsdk/builtin-tools/subagent.ts +2 -2
- package/zapsdk/execution/process.ts +1 -1
- package/zapsdk/execution/sandbox.ts +6 -4
- package/zapsdk/execution/types.ts +3 -0
- 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
|
+
}
|
package/zapsdk/agent/loop.ts
CHANGED
|
@@ -8,7 +8,7 @@ import { normalizeAssistantText } from "./output-text.js";
|
|
|
8
8
|
import { earliestDeadlineAt } from "../execution/deadline.js";
|
|
9
9
|
import { toolOutputTool } from "../builtin-tools/tool-output.js";
|
|
10
10
|
import { assembleSubagentTool } from "./subagent-assembly.js";
|
|
11
|
-
import { type TaskDecompositionMode, primaryArgSig, stepSignature, createRunToolExecutionHooks, isRepeatFriendlyStep, isLiveTaskWait, progressPollSignature } from "./tool-execution-guards.js";
|
|
11
|
+
import { type TaskDecompositionMode, primaryArgSig, stepSignature, createRunToolExecutionHooks, duplicateQueryKey, isDuplicateQuery, isRepeatFriendlyStep, isLiveTaskWait, progressPollSignature } from "./tool-execution-guards.js";
|
|
12
12
|
import type { LLMProvider, LLMCallOptions } from "../core/llm.js";
|
|
13
13
|
import { hasMeaningfulOutput } from "../core/provider-request.js";
|
|
14
14
|
import { assertProviderRequestAllowed } from "../core/provider-deadline.js";
|
|
@@ -962,6 +962,10 @@ export class LoopAgent {
|
|
|
962
962
|
} else {
|
|
963
963
|
localMessages = msgs;
|
|
964
964
|
}
|
|
965
|
+
// Pruning and compaction shorten earlier results. A duplicate notice
|
|
966
|
+
// must never point the model at output it can no longer see.
|
|
967
|
+
seenFiles.clear();
|
|
968
|
+
toolExecutionHooks.forgetObservations();
|
|
965
969
|
};
|
|
966
970
|
this.recoveryContext = (requestMessages) => {
|
|
967
971
|
let revision: string | undefined;
|
|
@@ -2486,7 +2490,9 @@ export class LoopAgent {
|
|
|
2486
2490
|
seenFiles: SeenFiles,
|
|
2487
2491
|
success: boolean,
|
|
2488
2492
|
): { content: string; suppression?: "duplicate" } {
|
|
2489
|
-
if (!toolCall.name.includes("read_file") && toolCall.name !== "pr_file_content")
|
|
2493
|
+
if (!toolCall.name.includes("read_file") && toolCall.name !== "pr_file_content") {
|
|
2494
|
+
return this.deduplicateQuery(toolCall, resultContent, seenFiles, success);
|
|
2495
|
+
}
|
|
2490
2496
|
if (!(toolCall.arguments as any).path && !(toolCall.arguments as any).ref) return { content: resultContent };
|
|
2491
2497
|
|
|
2492
2498
|
const filePath = String((toolCall.arguments as any).path ?? (toolCall.arguments as any).ref ?? "");
|
|
@@ -2507,6 +2513,36 @@ export class LoopAgent {
|
|
|
2507
2513
|
return { content: resultContent };
|
|
2508
2514
|
}
|
|
2509
2515
|
|
|
2516
|
+
/** Fold a repeated search or read-only shell query whose output has not
|
|
2517
|
+
* changed. The query has already run, so a change made outside the agent's
|
|
2518
|
+
* tools still reaches the model. */
|
|
2519
|
+
private deduplicateQuery(
|
|
2520
|
+
toolCall: ToolCallRequest,
|
|
2521
|
+
resultContent: string,
|
|
2522
|
+
seenFiles: SeenFiles,
|
|
2523
|
+
success: boolean,
|
|
2524
|
+
): { content: string; suppression?: "duplicate" } {
|
|
2525
|
+
const args = (toolCall.arguments ?? {}) as Record<string, unknown>;
|
|
2526
|
+
if (!isDuplicateQuery(toolCall.name, args)) return { content: resultContent };
|
|
2527
|
+
const key = duplicateQueryKey(toolCall.name, args);
|
|
2528
|
+
if (!success) {
|
|
2529
|
+
seenFiles.delete(key);
|
|
2530
|
+
return { content: resultContent };
|
|
2531
|
+
}
|
|
2532
|
+
const contentHash = createHash("sha256").update(resultContent).digest("hex");
|
|
2533
|
+
if (seenFiles.get(key) === contentHash) {
|
|
2534
|
+
const target = primaryArgSig(toolCall.name, args) || "the same arguments";
|
|
2535
|
+
this.emitter.emit({ type: "observation", kind: "duplicate_tool_suppressed", detail: { tool: toolCall.name, target } });
|
|
2536
|
+
return {
|
|
2537
|
+
content: `[Duplicate ${toolCall.name} suppressed for ${target}. It returned the same output as the previous call; ` +
|
|
2538
|
+
"reuse that result and choose the next concrete action.]",
|
|
2539
|
+
suppression: "duplicate",
|
|
2540
|
+
};
|
|
2541
|
+
}
|
|
2542
|
+
seenFiles.set(key, contentHash);
|
|
2543
|
+
return { content: resultContent };
|
|
2544
|
+
}
|
|
2545
|
+
|
|
2510
2546
|
/** Append error classification hints or system notices to the result content. */
|
|
2511
2547
|
private classifyError(
|
|
2512
2548
|
toolCall: ToolCallRequest,
|
|
@@ -2515,12 +2551,23 @@ export class LoopAgent {
|
|
|
2515
2551
|
resultContent: string,
|
|
2516
2552
|
): string {
|
|
2517
2553
|
if (result.success) {
|
|
2518
|
-
|
|
2554
|
+
// A successful change to the workspace makes every earlier failure
|
|
2555
|
+
// worth retrying: rerunning tests after an edit is not a blind retry.
|
|
2556
|
+
const readOnly = this.executor.workspaceGate
|
|
2557
|
+
? !!result.runtime?.effects && isEffectivelyReadOnly(result.runtime.effects)
|
|
2558
|
+
: this.executor.isReadOnly(toolCall.name, toolCall.arguments);
|
|
2559
|
+
if (readOnly) errorTracker.delete(toolCall.name);
|
|
2560
|
+
else errorTracker.clear();
|
|
2519
2561
|
return resultContent;
|
|
2520
2562
|
}
|
|
2521
2563
|
if (!result.error) return resultContent;
|
|
2522
2564
|
|
|
2523
|
-
|
|
2565
|
+
// Count only the identical call failing identically. Error headers such as
|
|
2566
|
+
// "Command failed: <cmd> … Message: <first line>" repeat across different
|
|
2567
|
+
// test failures, so the whole observation is part of the signature.
|
|
2568
|
+
const errorSig = createHash("sha256")
|
|
2569
|
+
.update(JSON.stringify([toolCall.arguments ?? {}, result.error, result.output ?? ""]))
|
|
2570
|
+
.digest("hex");
|
|
2524
2571
|
if (!errorTracker.has(toolCall.name)) errorTracker.set(toolCall.name, new Map());
|
|
2525
2572
|
const toolErrors = errorTracker.get(toolCall.name)!;
|
|
2526
2573
|
const count = (toolErrors.get(errorSig) ?? 0) + 1;
|
|
@@ -2,7 +2,6 @@ import type { ToolResult } from "../tools/types.js";
|
|
|
2
2
|
import type { ToolExecutor } from "../tools/executor.js";
|
|
3
3
|
import type { ToolExecutionHooks } from "./streaming-tool-executor.js";
|
|
4
4
|
import { operationFailure } from "../execution/failure.js";
|
|
5
|
-
import { isEffectivelyReadOnly } from "../tools/effects.js";
|
|
6
5
|
import { canonicalizeJsonSchema } from "../tools/schema.js";
|
|
7
6
|
import { sliceHeadCodePoints } from "../utils/logical-lines.js";
|
|
8
7
|
import { createHash } from "node:crypto";
|
|
@@ -103,11 +102,11 @@ const READ_ONLY_GIT_SUBCOMMANDS = new Set([
|
|
|
103
102
|
|
|
104
103
|
/**
|
|
105
104
|
* The shell tool declares a conservative read+write effect because arbitrary
|
|
106
|
-
* shell is impossible to prove safe. For duplicate
|
|
105
|
+
* shell is impossible to prove safe. For duplicate folding we can still
|
|
107
106
|
* recognise a deliberately tiny subset of inspection commands. This is not
|
|
108
|
-
* a permission decision: it
|
|
109
|
-
*
|
|
110
|
-
*
|
|
107
|
+
* a permission decision: it only lets an identical repeated result be folded.
|
|
108
|
+
* Anything involving shell composition or a potentially writing flag is never
|
|
109
|
+
* folded.
|
|
111
110
|
*/
|
|
112
111
|
function isMemoizableBashQuery(args: Record<string, unknown>): boolean {
|
|
113
112
|
if (args.run_in_background === true || typeof args.command !== "string") return false;
|
|
@@ -146,7 +145,11 @@ function isMemoizableBashQuery(args: Record<string, unknown>): boolean {
|
|
|
146
145
|
return true;
|
|
147
146
|
}
|
|
148
147
|
|
|
149
|
-
|
|
148
|
+
/** Local queries whose identical repeated output may be folded into a pointer
|
|
149
|
+
* to the earlier result. They still execute: a file can change outside the
|
|
150
|
+
* agent's own tools (the user's editor, a background job), and only the fresh
|
|
151
|
+
* output can show that. */
|
|
152
|
+
export function isDuplicateQuery(name: string, args: Record<string, unknown>): boolean {
|
|
150
153
|
return DUPLICATE_QUERY_TOOLS.has(name) || (name === "bash" && isMemoizableBashQuery(args));
|
|
151
154
|
}
|
|
152
155
|
|
|
@@ -160,7 +163,7 @@ function httpFetchKey(name: string, args: Record<string, unknown>): string | und
|
|
|
160
163
|
return `${method} ${args.url}${args.raw === true ? " raw" : ""}`;
|
|
161
164
|
}
|
|
162
165
|
|
|
163
|
-
function duplicateQueryKey(name: string, args: Record<string, unknown>): string {
|
|
166
|
+
export function duplicateQueryKey(name: string, args: Record<string, unknown>): string {
|
|
164
167
|
return `${name}:${JSON.stringify(canonicalizeJsonSchema(args))}`;
|
|
165
168
|
}
|
|
166
169
|
|
|
@@ -220,22 +223,28 @@ function taskPlanRequiredResult(mode: TaskDecompositionMode): ToolResult {
|
|
|
220
223
|
};
|
|
221
224
|
}
|
|
222
225
|
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
226
|
+
export interface RunToolExecutionHooks extends ToolExecutionHooks {
|
|
227
|
+
/** Forget fetched pages once history is rewritten: their results may have
|
|
228
|
+
* been compacted away, so "reuse that result" would point at nothing. */
|
|
229
|
+
forgetObservations(): void;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/** Reuse a recent remote fetch instead of repeating it. Local reads and
|
|
233
|
+
* searches are not suppressed here; LoopAgent folds an identical result after
|
|
234
|
+
* it runs. */
|
|
228
235
|
export function createRunToolExecutionHooks(
|
|
229
236
|
executor: ToolExecutor,
|
|
230
237
|
onSuppressed: (name: string, args: Record<string, unknown>) => void,
|
|
231
238
|
taskDecomposition: TaskDecompositionMode,
|
|
232
239
|
hasTodoTool: boolean,
|
|
233
|
-
):
|
|
234
|
-
const completedOrInFlight = new Set<string>();
|
|
240
|
+
): RunToolExecutionHooks {
|
|
235
241
|
// Remote GETs do not depend on the workspace, so a mutation must not forget them.
|
|
236
242
|
const fetchedUrls = new Map<string, number>();
|
|
237
243
|
const planState: TaskPlanGateState = { ready: false, baselineReads: 0 };
|
|
238
244
|
return {
|
|
245
|
+
forgetObservations() {
|
|
246
|
+
fetchedUrls.clear();
|
|
247
|
+
},
|
|
239
248
|
beforeExecute(name, args) {
|
|
240
249
|
// Planning is not a permission boundary. Only an explicitly required
|
|
241
250
|
// plan may block execution; auto must not turn a short task into retries.
|
|
@@ -265,20 +274,7 @@ export function createRunToolExecutionHooks(
|
|
|
265
274
|
);
|
|
266
275
|
}
|
|
267
276
|
fetchedUrls.set(fetchKey, Date.now());
|
|
268
|
-
return undefined;
|
|
269
|
-
}
|
|
270
|
-
if (!isDuplicateQuery(name, args)) return undefined;
|
|
271
|
-
const key = duplicateQueryKey(name, args);
|
|
272
|
-
if (completedOrInFlight.has(key)) {
|
|
273
|
-
onSuppressed(name, args);
|
|
274
|
-
const target = primaryArgSig(name, args) || "the same arguments";
|
|
275
|
-
return duplicateSuppression(
|
|
276
|
-
`[Duplicate ${name} suppressed for ${target}. ` +
|
|
277
|
-
"Reuse the previous result; the workspace has not changed since it was returned. " +
|
|
278
|
-
"Choose the next concrete action instead of reading/searching it again.]",
|
|
279
|
-
);
|
|
280
277
|
}
|
|
281
|
-
completedOrInFlight.add(key);
|
|
282
278
|
return undefined;
|
|
283
279
|
},
|
|
284
280
|
afterExecute(name, args, result) {
|
|
@@ -287,19 +283,9 @@ export function createRunToolExecutionHooks(
|
|
|
287
283
|
if (!result.success) fetchedUrls.delete(fetchedKey);
|
|
288
284
|
return;
|
|
289
285
|
}
|
|
290
|
-
if (isDuplicateQuery(name, args)) {
|
|
291
|
-
if (!result.success) completedOrInFlight.delete(duplicateQueryKey(name, args));
|
|
292
|
-
return;
|
|
293
|
-
}
|
|
294
286
|
if (name === "todo_write" && result.success) {
|
|
295
287
|
planState.ready = true;
|
|
296
288
|
}
|
|
297
|
-
const readOnly = executor.workspaceGate
|
|
298
|
-
? !!result.runtime?.effects && isEffectivelyReadOnly(result.runtime.effects)
|
|
299
|
-
: executor.isReadOnly(name, args);
|
|
300
|
-
if (result.success && !readOnly) {
|
|
301
|
-
completedOrInFlight.clear();
|
|
302
|
-
}
|
|
303
289
|
},
|
|
304
290
|
};
|
|
305
291
|
}
|