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.
- 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 +187 -187
- package/package.json +1 -1
- package/src/App.tsx +19 -6
- 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 +19 -2
- 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/runHeadless.ts +2 -1
- 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 +21 -3
- 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-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 +3 -1
- package/zapsdk/agent/single-call.ts +4 -2
- package/zapsdk/builtin-tools/acp-agent.ts +188 -0
- package/zapsdk/builtin-tools/delegate-detect.ts +1 -1
- package/zapsdk/builtin-tools/index.ts +9 -0
- package/zapsdk/core/llm.ts +2 -0
- package/zapsdk/core/providers/openai-responses.ts +25 -7
- 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,228 @@
|
|
|
1
|
+
import { Readable, Writable } from "node:stream";
|
|
2
|
+
import type { ChildProcess } from "node:child_process";
|
|
3
|
+
import {
|
|
4
|
+
client, ndJsonStream, PROTOCOL_VERSION,
|
|
5
|
+
type AgentApp, type ClientConnection, type ContentBlock, type InitializeResponse,
|
|
6
|
+
type NewSessionResponse, type PromptResponse, type SessionUpdate,
|
|
7
|
+
} from "@agentclientprotocol/sdk";
|
|
8
|
+
import { AcpClientError, type AcpClientHandlers } from "./types.js";
|
|
9
|
+
import { terminateProcessTree, terminateProcessTreeWithGrace } from "../execution/process.js";
|
|
10
|
+
|
|
11
|
+
const STDERR_CAP = 16 * 1024;
|
|
12
|
+
const CANCEL_GRACE_MS = 5_000;
|
|
13
|
+
const MAX_MESSAGE_BYTES = 16 * 1024 * 1024;
|
|
14
|
+
const EXIT_SETTLE_MS = 500;
|
|
15
|
+
|
|
16
|
+
function delay(ms: number): Promise<undefined> {
|
|
17
|
+
return new Promise(resolve => { const timer = setTimeout(() => resolve(undefined), ms); timer.unref?.(); });
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Where an ACP agent lives. Stdio covers real agents; in-process covers
|
|
21
|
+
* adapters and tests. The connection cannot tell them apart. */
|
|
22
|
+
export interface AcpTransport {
|
|
23
|
+
open(app: ReturnType<typeof client>): ClientConnection;
|
|
24
|
+
/** Settles when the agent can no longer answer (process exit). */
|
|
25
|
+
readonly exited: Promise<{ code: number | null; signal: string | null }>;
|
|
26
|
+
stderrTail(): string;
|
|
27
|
+
dispose(): Promise<void>;
|
|
28
|
+
/** Synchronous SIGKILL of the agent's process tree (process exit only). */
|
|
29
|
+
kill?(): void;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function stdioTransport(child: ChildProcess): AcpTransport {
|
|
33
|
+
if (!child.stdin || !child.stdout) throw new AcpClientError("ACP agent has no stdio pipes", "spawn_failed");
|
|
34
|
+
let stderr = "";
|
|
35
|
+
child.stderr?.setEncoding("utf8");
|
|
36
|
+
child.stderr?.on("data", (chunk: string) => { stderr = (stderr + chunk).slice(-STDERR_CAP); });
|
|
37
|
+
// EPIPE on a dead agent surfaces through `exited`, not as an unhandled error.
|
|
38
|
+
child.stdin.on("error", () => {});
|
|
39
|
+
const exited = new Promise<{ code: number | null; signal: string | null }>((resolve) => {
|
|
40
|
+
child.once("close", (code, signal) => resolve({ code, signal }));
|
|
41
|
+
child.once("error", (error) => { stderr += `\n${error.message}`; resolve({ code: null, signal: null }); });
|
|
42
|
+
});
|
|
43
|
+
return {
|
|
44
|
+
open: (app) => app.connect(ndJsonStream(
|
|
45
|
+
Writable.toWeb(child.stdin!) as WritableStream<Uint8Array>,
|
|
46
|
+
Readable.toWeb(child.stdout!) as ReadableStream<Uint8Array>,
|
|
47
|
+
{ maxMessageBytes: MAX_MESSAGE_BYTES })),
|
|
48
|
+
exited,
|
|
49
|
+
stderrTail: () => stderr.trim(),
|
|
50
|
+
async dispose() {
|
|
51
|
+
if (child.exitCode !== null || child.signalCode !== null) return;
|
|
52
|
+
child.stdin?.end();
|
|
53
|
+
terminateProcessTreeWithGrace(child, 3_000);
|
|
54
|
+
await exited;
|
|
55
|
+
},
|
|
56
|
+
kill() {
|
|
57
|
+
if (child.exitCode === null && child.signalCode === null) terminateProcessTree(child, "SIGKILL");
|
|
58
|
+
},
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function inProcessTransport(agent: AgentApp): AcpTransport {
|
|
63
|
+
let release!: () => void;
|
|
64
|
+
const exited = new Promise<{ code: number | null; signal: string | null }>((resolve) => {
|
|
65
|
+
release = () => resolve({ code: 0, signal: null });
|
|
66
|
+
});
|
|
67
|
+
return {
|
|
68
|
+
open: (app) => app.connect(agent),
|
|
69
|
+
exited,
|
|
70
|
+
stderrTail: () => "",
|
|
71
|
+
async dispose() { release(); },
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export interface AcpPromptOptions {
|
|
76
|
+
signal?: AbortSignal;
|
|
77
|
+
onUpdate?: (update: SessionUpdate) => void;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** One ACP connection: initialize once, then sessions and prompts. */
|
|
81
|
+
export class AcpClientConnection {
|
|
82
|
+
private readonly listeners = new Map<string, (update: SessionUpdate) => void>();
|
|
83
|
+
private connection!: ClientConnection;
|
|
84
|
+
info!: InitializeResponse;
|
|
85
|
+
|
|
86
|
+
private constructor(private readonly transport: AcpTransport) {}
|
|
87
|
+
|
|
88
|
+
static async open(transport: AcpTransport, handlers: AcpClientHandlers, options: {
|
|
89
|
+
clientName?: string; clientVersion?: string; signal?: AbortSignal; timeoutMs?: number;
|
|
90
|
+
} = {}): Promise<AcpClientConnection> {
|
|
91
|
+
const self = new AcpClientConnection(transport);
|
|
92
|
+
const app = client({ name: options.clientName ?? "zapcode" })
|
|
93
|
+
.onNotification("session/update", ({ params }) => { self.listeners.get(params.sessionId)?.(params.update); });
|
|
94
|
+
if (handlers.requestPermission) {
|
|
95
|
+
const handler = handlers.requestPermission;
|
|
96
|
+
app.onRequest("session/request_permission", ({ params, signal }) => handler(params, signal));
|
|
97
|
+
} else {
|
|
98
|
+
app.onRequest("session/request_permission", () => ({ outcome: { outcome: "cancelled" } }));
|
|
99
|
+
}
|
|
100
|
+
if (handlers.readTextFile) {
|
|
101
|
+
const handler = handlers.readTextFile;
|
|
102
|
+
app.onRequest("fs/read_text_file", ({ params, signal }) => handler(params, signal));
|
|
103
|
+
}
|
|
104
|
+
if (handlers.writeTextFile) {
|
|
105
|
+
const handler = handlers.writeTextFile;
|
|
106
|
+
app.onRequest("fs/write_text_file", async ({ params, signal }) => { await handler(params, signal); return {}; });
|
|
107
|
+
}
|
|
108
|
+
self.connection = transport.open(app);
|
|
109
|
+
try {
|
|
110
|
+
self.info = await self.call(self.connection.agent.request("initialize", {
|
|
111
|
+
protocolVersion: PROTOCOL_VERSION,
|
|
112
|
+
clientCapabilities: {
|
|
113
|
+
fs: { readTextFile: !!handlers.readTextFile, writeTextFile: !!handlers.writeTextFile },
|
|
114
|
+
terminal: false,
|
|
115
|
+
},
|
|
116
|
+
clientInfo: { name: options.clientName ?? "zapcode", version: options.clientVersion ?? "0" },
|
|
117
|
+
}), "initialize_failed", options);
|
|
118
|
+
} catch (error) {
|
|
119
|
+
await self.close();
|
|
120
|
+
throw error;
|
|
121
|
+
}
|
|
122
|
+
return self;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
get agentName(): string {
|
|
126
|
+
return this.info.agentInfo?.title || this.info.agentInfo?.name || "agent";
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
async newSession(cwd: string, options: { signal?: AbortSignal; timeoutMs?: number } = {}): Promise<NewSessionResponse> {
|
|
130
|
+
return this.call(this.connection.agent.request("session/new", { cwd, mcpServers: [] }), "session_failed", options);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** Resume a prior session. Replayed history is dropped; only new turns are mapped. */
|
|
134
|
+
async loadSession(sessionId: string, cwd: string, options: { signal?: AbortSignal; timeoutMs?: number } = {}): Promise<void> {
|
|
135
|
+
if (!this.info.agentCapabilities?.loadSession) {
|
|
136
|
+
throw new AcpClientError(`${this.agentName} cannot resume sessions`, "session_failed");
|
|
137
|
+
}
|
|
138
|
+
await this.call(this.connection.agent.request("session/load", { sessionId, cwd, mcpServers: [] }), "session_failed", options);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
async setMode(sessionId: string, modeId: string): Promise<void> {
|
|
142
|
+
await this.call(this.connection.agent.request("session/set_mode", { sessionId, modeId }), "session_failed");
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
async setConfigOption(sessionId: string, configId: string, value: string): Promise<void> {
|
|
146
|
+
await this.call(this.connection.agent.request("session/set_config_option", { sessionId, configId, value }), "session_failed");
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** Unstable `session/set_model`; agents without it reject and the caller decides. */
|
|
150
|
+
async setModel(sessionId: string, modelId: string): Promise<void> {
|
|
151
|
+
await this.call(this.connection.agent.request("session/set_model", { sessionId, modelId }), "session_failed");
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
async prompt(sessionId: string, prompt: ContentBlock[], options: AcpPromptOptions = {}): Promise<PromptResponse> {
|
|
155
|
+
if (options.onUpdate) this.listeners.set(sessionId, options.onUpdate);
|
|
156
|
+
const signal = options.signal;
|
|
157
|
+
let onAbort: (() => void) | undefined;
|
|
158
|
+
try {
|
|
159
|
+
const request = this.connection.agent.request("session/prompt", { sessionId, prompt });
|
|
160
|
+
const cancelled = new Promise<PromptResponse>((resolve, reject) => {
|
|
161
|
+
onAbort = () => {
|
|
162
|
+
void this.connection.agent.notify("session/cancel", { sessionId }).catch(() => {});
|
|
163
|
+
// A cooperative agent answers with stopReason "cancelled"; do not
|
|
164
|
+
// wait forever for one that ignores the notification.
|
|
165
|
+
const timer = setTimeout(() => reject(new AcpClientError("ACP agent ignored cancellation", "cancelled")), CANCEL_GRACE_MS);
|
|
166
|
+
timer.unref?.();
|
|
167
|
+
request.then(resolve, reject).finally(() => clearTimeout(timer));
|
|
168
|
+
};
|
|
169
|
+
if (signal?.aborted) onAbort();
|
|
170
|
+
else signal?.addEventListener("abort", onAbort, { once: true });
|
|
171
|
+
});
|
|
172
|
+
return await this.call(signal ? Promise.race([request, cancelled]) : request, "prompt_failed");
|
|
173
|
+
} finally {
|
|
174
|
+
if (onAbort) signal?.removeEventListener("abort", onAbort);
|
|
175
|
+
this.listeners.delete(sessionId);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
async close(): Promise<void> {
|
|
180
|
+
try { this.connection?.close(); } catch { /* already closed */ }
|
|
181
|
+
await this.transport.dispose();
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
stderrTail(): string { return this.transport.stderrTail(); }
|
|
185
|
+
|
|
186
|
+
/** Race a request against agent exit, a timeout and the caller's signal. */
|
|
187
|
+
private async call<T>(request: Promise<T>, code: AcpClientError["code"], options: { signal?: AbortSignal; timeoutMs?: number } = {}): Promise<T> {
|
|
188
|
+
const guards: Array<Promise<never>> = [
|
|
189
|
+
this.transport.exited.then(({ code: exitCode, signal }) => {
|
|
190
|
+
throw new AcpClientError(`ACP agent exited (${signal ?? `code ${exitCode}`})`, "exited", this.transport.stderrTail() || undefined);
|
|
191
|
+
}),
|
|
192
|
+
];
|
|
193
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
194
|
+
if (options.timeoutMs) {
|
|
195
|
+
guards.push(new Promise<never>((_, reject) => {
|
|
196
|
+
timer = setTimeout(() => reject(new AcpClientError(`ACP request timed out after ${options.timeoutMs}ms`, "timeout")), options.timeoutMs);
|
|
197
|
+
timer.unref?.();
|
|
198
|
+
}));
|
|
199
|
+
}
|
|
200
|
+
let onAbort: (() => void) | undefined;
|
|
201
|
+
if (options.signal) {
|
|
202
|
+
guards.push(new Promise<never>((_, reject) => {
|
|
203
|
+
onAbort = () => reject(new AcpClientError("cancelled", "cancelled"));
|
|
204
|
+
if (options.signal!.aborted) onAbort();
|
|
205
|
+
else options.signal!.addEventListener("abort", onAbort, { once: true });
|
|
206
|
+
}));
|
|
207
|
+
}
|
|
208
|
+
try {
|
|
209
|
+
return await Promise.race([request, ...guards]);
|
|
210
|
+
} catch (error) {
|
|
211
|
+
if (error instanceof AcpClientError) throw error;
|
|
212
|
+
// A dying agent closes stdout before the exit event fires, so the
|
|
213
|
+
// request fails as "connection closed" first. Report it as the exit.
|
|
214
|
+
const exit = await Promise.race([this.transport.exited, delay(EXIT_SETTLE_MS)]);
|
|
215
|
+
if (exit) {
|
|
216
|
+
throw new AcpClientError(`ACP agent exited (${exit.signal ?? `code ${exit.code}`})`, "exited", this.transport.stderrTail() || undefined);
|
|
217
|
+
}
|
|
218
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
219
|
+
// -32000 is ACP's auth_required error code.
|
|
220
|
+
const auth = (error as { code?: number }).code === -32000
|
|
221
|
+
|| /auth(entication)? required|not authenticated|unauthori[sz]ed/i.test(message);
|
|
222
|
+
throw new AcpClientError(message, auth ? "auth_required" : code, this.transport.stderrTail() || undefined);
|
|
223
|
+
} finally {
|
|
224
|
+
if (timer) clearTimeout(timer);
|
|
225
|
+
if (onAbort) options.signal?.removeEventListener("abort", onAbort);
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { which } from "../builtin-tools/delegate-detect.js";
|
|
2
|
+
import type { AcpAgentSpec } from "./types.js";
|
|
3
|
+
|
|
4
|
+
/** ACP agents zap recognizes on PATH without configuration. User config
|
|
5
|
+
* entries with the same id win; zap itself is never auto-registered. */
|
|
6
|
+
export const KNOWN_ACP_AGENTS: readonly AcpAgentSpec[] = [
|
|
7
|
+
{ id: "agy", name: "Antigravity", command: "agy", args: ["acp"], selfGoverned: true,
|
|
8
|
+
description: "Google Antigravity agent (Gemini models)." },
|
|
9
|
+
// Codex has no native ACP mode; the adapter (`npm i -g @agentclientprotocol/codex-acp`)
|
|
10
|
+
// speaks ACP and reuses the codex login. Its default "agent" mode asks
|
|
11
|
+
// zap only for actions it judges unsafe and writes workspace files itself.
|
|
12
|
+
// ("read-only" routes every edit to zap but stalls for minutes upstream.)
|
|
13
|
+
{ id: "codex", name: "Codex", command: "codex-acp", args: [], selfGoverned: true,
|
|
14
|
+
description: "OpenAI Codex through its ACP adapter." },
|
|
15
|
+
]
|
|
16
|
+
|
|
17
|
+
/** Merge configured agents with known agents found on PATH. Configured
|
|
18
|
+
* commands are resolved too, so a missing binary is dropped. */
|
|
19
|
+
export async function detectAcpAgents(configured: readonly AcpAgentSpec[] = [], pathEnv?: string): Promise<AcpAgentSpec[]> {
|
|
20
|
+
const byId = new Map<string, AcpAgentSpec>();
|
|
21
|
+
for (const spec of KNOWN_ACP_AGENTS) byId.set(spec.id, spec);
|
|
22
|
+
for (const spec of configured) byId.set(spec.id, { ...byId.get(spec.id), ...spec });
|
|
23
|
+
const resolved = await Promise.all([...byId.values()].map(async (spec) => {
|
|
24
|
+
const bin = await which(spec.command, pathEnv);
|
|
25
|
+
return bin ? { ...spec, command: bin } : null;
|
|
26
|
+
}));
|
|
27
|
+
return resolved.filter((spec): spec is AcpAgentSpec => spec !== null);
|
|
28
|
+
}
|
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
ContentBlock, PlanEntry, SessionUpdate, ToolCallContent, ToolCallLocation, Usage,
|
|
3
|
+
} from "@agentclientprotocol/sdk";
|
|
4
|
+
import type { AgentEvent } from "../agent/events.js";
|
|
5
|
+
import { nextContentId } from "../agent/events.js";
|
|
6
|
+
import type { TokenUsage } from "../core/types.js";
|
|
7
|
+
import type { ToolResult } from "../tools/types.js";
|
|
8
|
+
import { buildDiffMeta } from "../builtin-tools/diff-meta.js";
|
|
9
|
+
|
|
10
|
+
interface ToolState {
|
|
11
|
+
id: string;
|
|
12
|
+
title: string;
|
|
13
|
+
kind?: string;
|
|
14
|
+
name?: string;
|
|
15
|
+
rawInput?: unknown;
|
|
16
|
+
locations: ToolCallLocation[];
|
|
17
|
+
content: ToolCallContent[];
|
|
18
|
+
rawOutput?: unknown;
|
|
19
|
+
/** Output streamed in `_meta.terminal_output_delta` (codex-acp) when the
|
|
20
|
+
* client has no terminal capability. */
|
|
21
|
+
terminalOutput: string;
|
|
22
|
+
announced: boolean;
|
|
23
|
+
settled: boolean;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const TOOL_OUTPUT_MAX_CHARS = 8_000;
|
|
27
|
+
|
|
28
|
+
/** Turns a stream of ACP session updates into zap AgentEvents.
|
|
29
|
+
*
|
|
30
|
+
* Thinking and text stream as deltas and are sealed when the other kind or a
|
|
31
|
+
* tool call starts, matching LoopAgent's ordering so the transcript reads the
|
|
32
|
+
* same. Tool calls are announced once and settled on the first terminal
|
|
33
|
+
* status. One mapper covers one prompt turn; `finish()` seals what is open. */
|
|
34
|
+
export class AcpEventMapper {
|
|
35
|
+
private thinking?: { id: string; text: string };
|
|
36
|
+
private text?: { id: string; text: string };
|
|
37
|
+
private readonly tools = new Map<string, ToolState>();
|
|
38
|
+
private step = 0;
|
|
39
|
+
private readonly messageText: string[] = [];
|
|
40
|
+
plan: PlanEntry[] = [];
|
|
41
|
+
contextUsage?: { used: number; size: number };
|
|
42
|
+
|
|
43
|
+
constructor(private readonly path: string[] = []) {}
|
|
44
|
+
|
|
45
|
+
/** Agent-visible message text for this turn, in order. */
|
|
46
|
+
get reportText(): string { return this.messageText.join("").trim(); }
|
|
47
|
+
get toolCallCount(): number { return this.tools.size; }
|
|
48
|
+
|
|
49
|
+
map(update: SessionUpdate): AgentEvent[] {
|
|
50
|
+
const out: AgentEvent[] = [];
|
|
51
|
+
switch (update.sessionUpdate) {
|
|
52
|
+
case "agent_thought_chunk": {
|
|
53
|
+
const piece = contentText(update.content);
|
|
54
|
+
if (!piece) break;
|
|
55
|
+
this.sealText(out);
|
|
56
|
+
this.thinking ??= { id: nextContentId("acpth"), text: "" };
|
|
57
|
+
this.thinking.text += piece;
|
|
58
|
+
out.push({ type: "content_delta", kind: "thinking", id: this.thinking.id, text: piece, path: this.path });
|
|
59
|
+
break;
|
|
60
|
+
}
|
|
61
|
+
case "agent_message_chunk": {
|
|
62
|
+
const piece = contentText(update.content);
|
|
63
|
+
if (!piece) break;
|
|
64
|
+
this.sealThinking(out);
|
|
65
|
+
this.text ??= { id: nextContentId("acptx"), text: "" };
|
|
66
|
+
this.text.text += piece;
|
|
67
|
+
this.messageText.push(piece);
|
|
68
|
+
out.push({ type: "content_delta", kind: "text", id: this.text.id, text: piece, path: this.path });
|
|
69
|
+
break;
|
|
70
|
+
}
|
|
71
|
+
case "tool_call": {
|
|
72
|
+
const tool = this.tool(update.toolCallId);
|
|
73
|
+
tool.title = update.title || tool.title;
|
|
74
|
+
tool.kind = update.kind ?? tool.kind;
|
|
75
|
+
tool.name = update.name ?? tool.name;
|
|
76
|
+
if (update.rawInput !== undefined) tool.rawInput = update.rawInput;
|
|
77
|
+
if (update.locations) tool.locations = update.locations;
|
|
78
|
+
if (update.content) tool.content = update.content;
|
|
79
|
+
this.announce(tool, out);
|
|
80
|
+
if (update.status === "completed" || update.status === "failed") this.settle(tool, update.status, out);
|
|
81
|
+
break;
|
|
82
|
+
}
|
|
83
|
+
case "tool_call_update": {
|
|
84
|
+
const tool = this.tool(update.toolCallId);
|
|
85
|
+
if (update.title) tool.title = update.title;
|
|
86
|
+
if (update.kind) tool.kind = update.kind;
|
|
87
|
+
if (update.name) tool.name = update.name;
|
|
88
|
+
if (update.rawInput !== undefined) tool.rawInput = update.rawInput;
|
|
89
|
+
if (update.locations) tool.locations = update.locations;
|
|
90
|
+
if (update.content) tool.content = update.content;
|
|
91
|
+
if (update.rawOutput !== undefined) tool.rawOutput = update.rawOutput;
|
|
92
|
+
const delta = (update._meta?.terminal_output_delta as { data?: unknown } | undefined)?.data;
|
|
93
|
+
if (typeof delta === "string") tool.terminalOutput += delta;
|
|
94
|
+
if (update.status === "completed" || update.status === "failed") {
|
|
95
|
+
this.announce(tool, out);
|
|
96
|
+
this.settle(tool, update.status, out);
|
|
97
|
+
} else if (update.status === "in_progress") {
|
|
98
|
+
this.announce(tool, out);
|
|
99
|
+
}
|
|
100
|
+
break;
|
|
101
|
+
}
|
|
102
|
+
case "plan":
|
|
103
|
+
this.plan = update.entries;
|
|
104
|
+
break;
|
|
105
|
+
case "usage_update":
|
|
106
|
+
this.contextUsage = { used: update.used, size: update.size };
|
|
107
|
+
break;
|
|
108
|
+
default:
|
|
109
|
+
break;
|
|
110
|
+
}
|
|
111
|
+
return out;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Seal open content and settle tools the agent never finished. */
|
|
115
|
+
finish(stopped: "end_turn" | "cancelled" | "error" | string): AgentEvent[] {
|
|
116
|
+
const out: AgentEvent[] = [];
|
|
117
|
+
this.sealThinking(out);
|
|
118
|
+
this.sealText(out);
|
|
119
|
+
for (const tool of this.tools.values()) {
|
|
120
|
+
if (tool.announced && !tool.settled) {
|
|
121
|
+
tool.settled = true;
|
|
122
|
+
out.push({ type: "content_final", kind: "tool_result", id: tool.id, step: this.step,
|
|
123
|
+
toolName: toolName(tool), path: this.path,
|
|
124
|
+
result: { success: false, output: "", error: stopped === "cancelled" ? "cancelled" : "agent ended the turn before the tool finished" } });
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
return out;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
private tool(id: string): ToolState {
|
|
131
|
+
let tool = this.tools.get(id);
|
|
132
|
+
if (!tool) {
|
|
133
|
+
tool = { id, title: "tool", locations: [], content: [], terminalOutput: "", announced: false, settled: false };
|
|
134
|
+
this.tools.set(id, tool);
|
|
135
|
+
}
|
|
136
|
+
return tool;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
private announce(tool: ToolState, out: AgentEvent[]): void {
|
|
140
|
+
if (tool.announced) return;
|
|
141
|
+
this.sealThinking(out);
|
|
142
|
+
this.sealText(out);
|
|
143
|
+
tool.announced = true;
|
|
144
|
+
this.step += 1;
|
|
145
|
+
out.push({ type: "content_final", kind: "tool_call", id: tool.id, step: this.step,
|
|
146
|
+
toolName: toolName(tool), arguments: toolArguments(tool), path: this.path });
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
private settle(tool: ToolState, status: "completed" | "failed", out: AgentEvent[]): void {
|
|
150
|
+
if (tool.settled) return;
|
|
151
|
+
tool.settled = true;
|
|
152
|
+
out.push({ type: "content_final", kind: "tool_result", id: tool.id, step: this.step,
|
|
153
|
+
toolName: toolName(tool), result: toolResult(tool, status), path: this.path });
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
private sealThinking(out: AgentEvent[]): void {
|
|
157
|
+
if (!this.thinking) return;
|
|
158
|
+
out.push({ type: "content_final", kind: "thinking", id: this.thinking.id, text: this.thinking.text, path: this.path });
|
|
159
|
+
this.thinking = undefined;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
private sealText(out: AgentEvent[]): void {
|
|
163
|
+
if (!this.text) return;
|
|
164
|
+
out.push({ type: "content_final", kind: "text", id: this.text.id, text: this.text.text, path: this.path });
|
|
165
|
+
this.text = undefined;
|
|
166
|
+
// Separate message segments interrupted by tools in the final report.
|
|
167
|
+
this.messageText.push("\n\n");
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
export function contentText(block: ContentBlock | undefined | null): string {
|
|
172
|
+
if (!block) return "";
|
|
173
|
+
if (block.type === "text") return block.text;
|
|
174
|
+
if (block.type === "resource_link") return `[${block.name ?? block.uri}](${block.uri})`;
|
|
175
|
+
if (block.type === "resource" && "text" in block.resource) return block.resource.text;
|
|
176
|
+
return "";
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** Usage from a prompt response or `_meta`, in zap's shape. */
|
|
180
|
+
export function acpUsage(usage: Usage | null | undefined): TokenUsage | undefined {
|
|
181
|
+
if (!usage) return undefined;
|
|
182
|
+
return {
|
|
183
|
+
inputTokens: Math.max(0, usage.inputTokens - (usage.cachedReadTokens ?? 0)),
|
|
184
|
+
outputTokens: usage.outputTokens,
|
|
185
|
+
cacheReadInputTokens: usage.cachedReadTokens ?? undefined,
|
|
186
|
+
cacheCreationInputTokens: usage.cachedWriteTokens ?? undefined,
|
|
187
|
+
providerUsageReported: true,
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function toolName(tool: ToolState): string {
|
|
192
|
+
return tool.name || tool.kind || "tool";
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function toolArguments(tool: ToolState): Record<string, unknown> {
|
|
196
|
+
const args: Record<string, unknown> = { title: tool.title };
|
|
197
|
+
if (tool.rawInput && typeof tool.rawInput === "object" && !Array.isArray(tool.rawInput)) {
|
|
198
|
+
Object.assign(args, tool.rawInput as Record<string, unknown>);
|
|
199
|
+
} else if (tool.rawInput !== undefined) {
|
|
200
|
+
args.input = tool.rawInput;
|
|
201
|
+
}
|
|
202
|
+
const paths = tool.locations.map(location => location.path);
|
|
203
|
+
if (paths.length === 1 && args.path === undefined) args.path = paths[0];
|
|
204
|
+
else if (paths.length > 1 && args.paths === undefined) args.paths = paths;
|
|
205
|
+
return args;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
function toolResult(tool: ToolState, status: "completed" | "failed"): ToolResult {
|
|
209
|
+
const parts: string[] = [];
|
|
210
|
+
let meta: unknown;
|
|
211
|
+
for (const item of tool.content) {
|
|
212
|
+
if (item.type === "content") {
|
|
213
|
+
const text = contentText(item.content);
|
|
214
|
+
if (text) parts.push(text);
|
|
215
|
+
} else if (item.type === "diff") {
|
|
216
|
+
parts.push(`${item.oldText == null ? "Created" : "Edited"} ${item.path}`);
|
|
217
|
+
meta ??= buildDiffMeta(item.oldText ?? "", item.newText, item.path);
|
|
218
|
+
} else if (item.type === "terminal" && !tool.terminalOutput) {
|
|
219
|
+
parts.push(`[terminal ${item.terminalId}]`);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
if (tool.terminalOutput) parts.push(tool.terminalOutput.trimEnd());
|
|
223
|
+
if (!parts.length && tool.rawOutput !== undefined) {
|
|
224
|
+
parts.push(typeof tool.rawOutput === "string" ? tool.rawOutput : JSON.stringify(tool.rawOutput));
|
|
225
|
+
}
|
|
226
|
+
let output = parts.join("\n");
|
|
227
|
+
if (output.length > TOOL_OUTPUT_MAX_CHARS) output = `${output.slice(0, TOOL_OUTPUT_MAX_CHARS)}\n… (truncated)`;
|
|
228
|
+
return status === "failed"
|
|
229
|
+
? { success: false, output: "", error: output || "failed", meta }
|
|
230
|
+
: { success: true, output, meta };
|
|
231
|
+
}
|