@juanbenjumea/pi-agy 0.6.11 → 0.7.1
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/CHANGELOG.md +15 -0
- package/README.md +59 -2
- package/extensions/commands.ts +66 -105
- package/extensions/index.ts +164 -47
- package/extensions/lib/args.ts +125 -0
- package/extensions/lib/cli.ts +31 -1223
- package/extensions/lib/command-args.ts +101 -0
- package/extensions/lib/config.ts +36 -1
- package/extensions/lib/confirm.ts +43 -0
- package/extensions/lib/doctor.ts +37 -1
- package/extensions/lib/inspect.ts +254 -0
- package/extensions/lib/lock.ts +1 -1
- package/extensions/lib/model-sort.ts +46 -0
- package/extensions/lib/provider-driver.ts +728 -0
- package/extensions/lib/provider-mcp.ts +580 -0
- package/extensions/lib/provider-models.ts +251 -0
- package/extensions/lib/provider.ts +1148 -0
- package/extensions/lib/retry.ts +34 -0
- package/extensions/lib/spawn.ts +411 -0
- package/extensions/lib/usage.ts +398 -0
- package/extensions/lib/verify.ts +11 -0
- package/package.json +6 -1
|
@@ -0,0 +1,1148 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Antigravity provider turn runtime (`antigravity/*` models in `/model`).
|
|
3
|
+
*
|
|
4
|
+
* Each Pi turn runs on a persistent agy driver process (see
|
|
5
|
+
* provider-driver.ts) with the transcript rendered as text. Response text
|
|
6
|
+
* streams back into Pi's TUI; agy's own tool activity surfaces as thinking
|
|
7
|
+
* events (`[agy tool: …]`) for visibility.
|
|
8
|
+
*
|
|
9
|
+
* Architectural wall (Phase 1): agy runs its OWN closed tool loop against
|
|
10
|
+
* the working directory. Pi's read/write/edit/bash tools never fire for
|
|
11
|
+
* these turns, so Pi's inline diff review does not engage — edits already
|
|
12
|
+
* landed on disk. Full Pi-tool bridging (MCP bridge + approval gates) is
|
|
13
|
+
* Phase 2; until then, prefer `agy_execute` delegation from a trusted Pi
|
|
14
|
+
* model when you need Pi-owned tool execution and diff review.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { randomBytes } from "node:crypto";
|
|
18
|
+
import { chmod, mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
|
|
19
|
+
import * as os from "node:os";
|
|
20
|
+
import * as path from "node:path";
|
|
21
|
+
|
|
22
|
+
import { loadAgyConfig } from "./config.js";
|
|
23
|
+
import { withDirLock } from "./lock.js";
|
|
24
|
+
import {
|
|
25
|
+
startMcpBridge,
|
|
26
|
+
toSafeBridgeName,
|
|
27
|
+
type BridgeToolDef,
|
|
28
|
+
type McpBridgeHandle,
|
|
29
|
+
} from "./provider-mcp.js";
|
|
30
|
+
import { getSession, saveSession } from "./sessions.js";
|
|
31
|
+
import { AgyProviderDriver, PROVIDER_TURN_TIMEOUT_MS } from "./provider-driver.js";
|
|
32
|
+
import {
|
|
33
|
+
toProviderEffort,
|
|
34
|
+
type AgyProviderEffort,
|
|
35
|
+
type AgyProviderModelEntry,
|
|
36
|
+
type AgyThinkingLevel,
|
|
37
|
+
} from "./provider-models.js";
|
|
38
|
+
|
|
39
|
+
/** Provider id registered with Pi. Collides with the bridge package — do not install both. */
|
|
40
|
+
export const AGY_PROVIDER_ID = "antigravity";
|
|
41
|
+
|
|
42
|
+
/** Custom API sentinel; no built-in provider claims it. */
|
|
43
|
+
export const AGY_PROVIDER_API = "agy-provider";
|
|
44
|
+
|
|
45
|
+
/** Bounds for transcript rendering into a single turn prompt. */
|
|
46
|
+
const MAX_HISTORY_CHARS = 24_000;
|
|
47
|
+
const MAX_SYSTEM_CHARS = 8_000;
|
|
48
|
+
const MAX_MESSAGE_CHARS = 6_000;
|
|
49
|
+
|
|
50
|
+
/** Minimal structural transcript message (subset of Pi's Message). */
|
|
51
|
+
export interface ProviderTranscriptMessage {
|
|
52
|
+
role: string;
|
|
53
|
+
content?: unknown;
|
|
54
|
+
toolName?: string;
|
|
55
|
+
toolCallId?: string;
|
|
56
|
+
isError?: boolean;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export interface ProviderTurnCallbacks {
|
|
60
|
+
onText?: (delta: string) => void;
|
|
61
|
+
onActivity?: (label: string) => void;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export interface ProviderTurnRequest {
|
|
65
|
+
/** Exact agy `--model` value (base or qualified slug). */
|
|
66
|
+
fullModel: string;
|
|
67
|
+
/** Pass `--effort` (effort-driven bases only). */
|
|
68
|
+
effort?: AgyProviderEffort;
|
|
69
|
+
prompt: string;
|
|
70
|
+
dir: string;
|
|
71
|
+
signal: AbortSignal;
|
|
72
|
+
timeoutMs: number;
|
|
73
|
+
/** Resume this agy conversation instead of starting a new one. */
|
|
74
|
+
resumeConversationId?: string;
|
|
75
|
+
skipPermissions: boolean;
|
|
76
|
+
/** Pi tools projected for this turn (refreshed per turn). */
|
|
77
|
+
bridgedTools: BridgeToolDef[];
|
|
78
|
+
callbacks?: ProviderTurnCallbacks;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** A bridged Pi-tool call parked mid-turn; agy waits on the MCP response. */
|
|
82
|
+
export interface ProviderToolPark {
|
|
83
|
+
callId: string;
|
|
84
|
+
/** Real Pi tool name. */
|
|
85
|
+
toolName: string;
|
|
86
|
+
args: Record<string, unknown>;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export type ProviderRunEnd =
|
|
90
|
+
| { kind: "done"; result: ProviderTurnResult }
|
|
91
|
+
| { kind: "parked"; park: ProviderToolPark };
|
|
92
|
+
|
|
93
|
+
export interface ProviderToolDelivery {
|
|
94
|
+
callId: string;
|
|
95
|
+
text: string;
|
|
96
|
+
isError: boolean;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Round-trip runner: `run` starts a driver turn (first phase end),
|
|
101
|
+
* `resume` delivers Pi tool results and waits for the next end, `cancel`
|
|
102
|
+
* abandons a suspended turn. One Pi turn maps to one call.
|
|
103
|
+
*/
|
|
104
|
+
export interface ProviderTurnRunner {
|
|
105
|
+
run: (request: ProviderTurnRequest) => Promise<ProviderRunEnd>;
|
|
106
|
+
resume: (
|
|
107
|
+
deliveries: ProviderToolDelivery[],
|
|
108
|
+
callbacks?: ProviderTurnCallbacks,
|
|
109
|
+
signal?: AbortSignal,
|
|
110
|
+
timeoutMs?: number,
|
|
111
|
+
) => Promise<ProviderRunEnd>;
|
|
112
|
+
cancel: () => void;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export interface ProviderTurnResult {
|
|
116
|
+
text: string;
|
|
117
|
+
truncated: boolean;
|
|
118
|
+
/** True when the text below is partial because the turn was cancelled. */
|
|
119
|
+
aborted?: boolean;
|
|
120
|
+
/** True when the text below is partial because the turn hit its deadline. */
|
|
121
|
+
timedOut?: boolean;
|
|
122
|
+
conversationId?: string;
|
|
123
|
+
/** Bounded agy tool-activity labels observed during the turn. */
|
|
124
|
+
activity: string[];
|
|
125
|
+
deniedActions?: Array<{ action?: string; display_name?: string }>;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function textOfContent(content: unknown, imagePath?: (block: object) => string | undefined): string {
|
|
129
|
+
if (typeof content === "string") return content;
|
|
130
|
+
if (Array.isArray(content)) {
|
|
131
|
+
const parts: string[] = [];
|
|
132
|
+
for (const block of content) {
|
|
133
|
+
if (typeof block === "string") {
|
|
134
|
+
parts.push(block);
|
|
135
|
+
} else if (block && typeof block === "object") {
|
|
136
|
+
const record = block as Record<string, unknown>;
|
|
137
|
+
if (record.type === "text" && typeof record.text === "string") {
|
|
138
|
+
parts.push(record.text);
|
|
139
|
+
} else if (record.type === "image") {
|
|
140
|
+
const staged = imagePath?.(block);
|
|
141
|
+
parts.push(
|
|
142
|
+
staged ?? "[image omitted: agy provider turns are text-only]",
|
|
143
|
+
);
|
|
144
|
+
} else if (record.type === "toolCall") {
|
|
145
|
+
parts.push(`[tool call: ${String(record.name ?? "unknown")}]`);
|
|
146
|
+
} else if (record.type === "thinking" && typeof record.thinking === "string") {
|
|
147
|
+
parts.push(record.thinking);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
return parts.join("\n");
|
|
152
|
+
}
|
|
153
|
+
return "";
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function clip(text: string, max: number): string {
|
|
157
|
+
if (text.length <= max) return text;
|
|
158
|
+
return text.slice(0, max - 1) + "…";
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
export interface PromptImageBlock {
|
|
162
|
+
/** Identity of the transcript block (lookup key, never serialized). */
|
|
163
|
+
block: object;
|
|
164
|
+
data: string;
|
|
165
|
+
mimeType: string;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
export interface StagedImages {
|
|
169
|
+
/** Per-turn subdir, undefined when nothing stageable. */
|
|
170
|
+
dir: string | undefined;
|
|
171
|
+
/** Block identity → absolute path (order-independent lookup). */
|
|
172
|
+
paths: Map<object, string>;
|
|
173
|
+
/** Remove this staging (idempotent, never throws). */
|
|
174
|
+
cleanup: () => Promise<void>;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** Cap staged images per invocation (count and per-file size). */
|
|
178
|
+
export const MAX_STAGED_IMAGES = 8;
|
|
179
|
+
export const MAX_IMAGE_BYTES = 8 * 1024 * 1024;
|
|
180
|
+
|
|
181
|
+
const IMAGE_EXTENSIONS: Record<string, string> = {
|
|
182
|
+
"image/png": "png",
|
|
183
|
+
"image/jpeg": "jpg",
|
|
184
|
+
"image/webp": "webp",
|
|
185
|
+
"image/gif": "gif",
|
|
186
|
+
"image/bmp": "bmp",
|
|
187
|
+
"image/svg+xml": "svg",
|
|
188
|
+
};
|
|
189
|
+
|
|
190
|
+
export function imageExtension(mimeType: string): string {
|
|
191
|
+
return IMAGE_EXTENSIONS[mimeType.toLowerCase()] ?? "bin";
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** Collect image blocks in transcript order, optionally only one tool result. */
|
|
195
|
+
export function collectImageBlocks(
|
|
196
|
+
messages: ProviderTranscriptMessage[],
|
|
197
|
+
onlyToolCallId?: string,
|
|
198
|
+
): PromptImageBlock[] {
|
|
199
|
+
const blocks: PromptImageBlock[] = [];
|
|
200
|
+
for (const message of messages) {
|
|
201
|
+
if (onlyToolCallId !== undefined) {
|
|
202
|
+
if (message.role !== "toolResult" || message.toolCallId !== onlyToolCallId) continue;
|
|
203
|
+
}
|
|
204
|
+
const content = message.content;
|
|
205
|
+
if (!Array.isArray(content)) continue;
|
|
206
|
+
for (const block of content) {
|
|
207
|
+
if (typeof block !== "object" || block === null) continue;
|
|
208
|
+
const record = block as Record<string, unknown>;
|
|
209
|
+
if (record.type !== "image") continue;
|
|
210
|
+
if (typeof record.data !== "string" || typeof record.mimeType !== "string") continue;
|
|
211
|
+
blocks.push({ block, data: record.data, mimeType: record.mimeType });
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
return blocks;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/** Strict base64 (Node's decoder silently strips non-alphabet chars). */
|
|
218
|
+
const STRICT_BASE64_RE = /^[A-Za-z0-9+/]*={0,2}$/;
|
|
219
|
+
|
|
220
|
+
function decodeImageData(data: string): Buffer | undefined {
|
|
221
|
+
if (typeof data !== "string" || data.length === 0 || data.length % 4 !== 0) return undefined;
|
|
222
|
+
if (!STRICT_BASE64_RE.test(data)) return undefined;
|
|
223
|
+
try {
|
|
224
|
+
const bytes = Buffer.from(data, "base64");
|
|
225
|
+
if (bytes.length === 0 || bytes.length > MAX_IMAGE_BYTES) return undefined;
|
|
226
|
+
return bytes;
|
|
227
|
+
} catch {
|
|
228
|
+
return undefined;
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/** Process-stable staging root (0700): per-turn subdirs, one --add-dir. */
|
|
233
|
+
let imageStagingRoot: string | undefined;
|
|
234
|
+
|
|
235
|
+
/** Live staging dirs (teardown sweep; per-turn cleanup disposes handles). */
|
|
236
|
+
const liveStagingDirs = new Set<string>();
|
|
237
|
+
|
|
238
|
+
/** Resolve (creating once) the process staging root for agy --add-dir. */
|
|
239
|
+
export async function ensureImageStagingRoot(): Promise<string> {
|
|
240
|
+
if (!imageStagingRoot) {
|
|
241
|
+
// mkdtemp (not join+mkdir): atomic, unique, 0700 — no pre-creation or
|
|
242
|
+
// symlink race between check and creation.
|
|
243
|
+
imageStagingRoot = await mkdtemp(path.join(os.tmpdir(), "pi-agy-images-"));
|
|
244
|
+
try {
|
|
245
|
+
await chmod(imageStagingRoot, 0o700);
|
|
246
|
+
} catch {
|
|
247
|
+
// mkdtemp already guarantees 0700; best effort.
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
return imageStagingRoot;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* Materialize image blocks as files agy's tools can open. Newest transcript
|
|
255
|
+
* images win (oldest starve first) so a fresh attachment is never dropped
|
|
256
|
+
* behind history. Failures degrade to omitted notes, never to turn
|
|
257
|
+
* failures. Each call owns its subdir; dispose via the returned cleanup.
|
|
258
|
+
*/
|
|
259
|
+
export async function stageImages(blocks: PromptImageBlock[]): Promise<StagedImages> {
|
|
260
|
+
const paths = new Map<object, string>();
|
|
261
|
+
const noop = async (): Promise<void> => undefined;
|
|
262
|
+
const bounded = blocks.slice(-MAX_STAGED_IMAGES);
|
|
263
|
+
if (bounded.length === 0) return { dir: undefined, paths, cleanup: noop };
|
|
264
|
+
let root: string;
|
|
265
|
+
try {
|
|
266
|
+
root = await ensureImageStagingRoot();
|
|
267
|
+
} catch {
|
|
268
|
+
return { dir: undefined, paths, cleanup: noop };
|
|
269
|
+
}
|
|
270
|
+
const dir = path.join(root, randomBytes(8).toString("hex"));
|
|
271
|
+
try {
|
|
272
|
+
await mkdir(dir, { mode: 0o700 });
|
|
273
|
+
} catch {
|
|
274
|
+
return { dir: undefined, paths, cleanup: noop };
|
|
275
|
+
}
|
|
276
|
+
liveStagingDirs.add(dir);
|
|
277
|
+
let cleaned = false;
|
|
278
|
+
const cleanup = async (): Promise<void> => {
|
|
279
|
+
if (cleaned) return;
|
|
280
|
+
cleaned = true;
|
|
281
|
+
liveStagingDirs.delete(dir);
|
|
282
|
+
await rm(dir, { recursive: true, force: true }).catch(() => undefined);
|
|
283
|
+
};
|
|
284
|
+
for (let index = 0; index < bounded.length; index++) {
|
|
285
|
+
const block = bounded[index];
|
|
286
|
+
const bytes = decodeImageData(block.data);
|
|
287
|
+
if (!bytes) continue;
|
|
288
|
+
const file = path.join(dir, `image-${index}.${imageExtension(block.mimeType)}`);
|
|
289
|
+
try {
|
|
290
|
+
await writeFile(file, bytes, { mode: 0o600 });
|
|
291
|
+
await chmod(file, 0o600);
|
|
292
|
+
} catch {
|
|
293
|
+
continue;
|
|
294
|
+
}
|
|
295
|
+
paths.set(block.block, file);
|
|
296
|
+
}
|
|
297
|
+
if (paths.size === 0) {
|
|
298
|
+
await cleanup();
|
|
299
|
+
return { dir: undefined, paths, cleanup: noop };
|
|
300
|
+
}
|
|
301
|
+
return { dir, paths, cleanup };
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/** Remove every staging dir and the root (teardown, tests). */
|
|
305
|
+
export async function clearImageStaging(): Promise<void> {
|
|
306
|
+
const dirs = [...liveStagingDirs];
|
|
307
|
+
liveStagingDirs.clear();
|
|
308
|
+
await Promise.all(dirs.map((dir) => rm(dir, { recursive: true, force: true }).catch(() => undefined)));
|
|
309
|
+
if (imageStagingRoot) {
|
|
310
|
+
const root = imageStagingRoot;
|
|
311
|
+
imageStagingRoot = undefined;
|
|
312
|
+
await rm(root, { recursive: true, force: true }).catch(() => undefined);
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/**
|
|
317
|
+
* Render Pi transcript messages into a single agy `-p` prompt. The latest
|
|
318
|
+
* user message is authoritative; earlier history is bounded reference. Pi
|
|
319
|
+
* tool definitions are intentionally NOT translated — agy runs its own tool
|
|
320
|
+
* loop (see the module wall note).
|
|
321
|
+
*/
|
|
322
|
+
export function renderProviderPrompt(
|
|
323
|
+
messages: ProviderTranscriptMessage[],
|
|
324
|
+
systemPrompt?: string,
|
|
325
|
+
imagePaths?: Map<object, string>,
|
|
326
|
+
): string {
|
|
327
|
+
const imageRef = (block: object): string | undefined => {
|
|
328
|
+
const file = imagePaths?.get(block);
|
|
329
|
+
return file
|
|
330
|
+
? `[attached image saved at ${file} — open it with your file tools to view it]`
|
|
331
|
+
: undefined;
|
|
332
|
+
};
|
|
333
|
+
const lines: string[] = [];
|
|
334
|
+
if (systemPrompt?.trim()) {
|
|
335
|
+
lines.push("System instructions:", clip(systemPrompt.trim(), MAX_SYSTEM_CHARS), "");
|
|
336
|
+
}
|
|
337
|
+
const history = messages.slice(0, -1);
|
|
338
|
+
const rendered: string[] = [];
|
|
339
|
+
let budget = MAX_HISTORY_CHARS;
|
|
340
|
+
for (let i = history.length - 1; i >= 0 && budget > 0; i--) {
|
|
341
|
+
const message = history[i];
|
|
342
|
+
const text = clip(textOfContent(message.content, imageRef).trim(), MAX_MESSAGE_CHARS);
|
|
343
|
+
if (!text) continue;
|
|
344
|
+
let label: string;
|
|
345
|
+
if (message.role === "user") label = "User";
|
|
346
|
+
else if (message.role === "assistant") label = "Assistant (previous turn)";
|
|
347
|
+
else if (message.role === "toolResult") {
|
|
348
|
+
label = `Tool result (${message.toolName ?? "tool"}${message.isError ? ", error" : ""})`;
|
|
349
|
+
} else if (message.role === "system") label = "System";
|
|
350
|
+
else label = message.role;
|
|
351
|
+
const entry = `${label}: ${text}`;
|
|
352
|
+
if (entry.length > budget) break;
|
|
353
|
+
budget -= entry.length;
|
|
354
|
+
rendered.unshift(entry);
|
|
355
|
+
}
|
|
356
|
+
if (rendered.length > 0) {
|
|
357
|
+
lines.push("Conversation history (reference only; the current message is authoritative):", ...rendered, "");
|
|
358
|
+
}
|
|
359
|
+
const last = messages[messages.length - 1];
|
|
360
|
+
const current = last ? textOfContent(last.content, imageRef).trim() : "";
|
|
361
|
+
const currentLabel = last && last.role !== "user" ? `Current message (${last.role}):` : "Current message:";
|
|
362
|
+
lines.push(currentLabel, current || "(empty — respond with a brief acknowledgement)");
|
|
363
|
+
return lines.join("\n");
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/** Pi tool source shape (structural subset of Pi's ToolInfo). */
|
|
367
|
+
export interface ProviderToolSource {
|
|
368
|
+
name: string;
|
|
369
|
+
description?: string;
|
|
370
|
+
parameters?: unknown;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
/**
|
|
374
|
+
* Tools that must never be bridged back into agy: self-delegation loops
|
|
375
|
+
* burn quota and nest conversations, they are not capabilities agy lacks.
|
|
376
|
+
*/
|
|
377
|
+
const BRIDGE_EXCLUDED_TOOL_NAMES = new Set(["askantigravity"]);
|
|
378
|
+
const MAX_BRIDGED_TOOLS = 100;
|
|
379
|
+
|
|
380
|
+
function isBridgableToolName(name: string): boolean {
|
|
381
|
+
const lowered = name.toLowerCase();
|
|
382
|
+
if (lowered === "agy" || lowered.startsWith("agy_") || lowered.startsWith("agy-")) return false;
|
|
383
|
+
return !BRIDGE_EXCLUDED_TOOL_NAMES.has(lowered);
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
function jsonClone(value: unknown): Record<string, unknown> | undefined {
|
|
387
|
+
try {
|
|
388
|
+
const cloned: unknown = JSON.parse(JSON.stringify(value));
|
|
389
|
+
if (cloned && typeof cloned === "object" && !Array.isArray(cloned)) {
|
|
390
|
+
return cloned as Record<string, unknown>;
|
|
391
|
+
}
|
|
392
|
+
return undefined;
|
|
393
|
+
} catch {
|
|
394
|
+
return undefined;
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
/**
|
|
399
|
+
* Project Pi tools into bridge definitions: exclude self-delegation,
|
|
400
|
+
* sanitize MCP names, drop unserializable schemas. First-seen wins on
|
|
401
|
+
* collisions so output is deterministic.
|
|
402
|
+
*/
|
|
403
|
+
export function projectBridgeTools(sources: ProviderToolSource[]): BridgeToolDef[] {
|
|
404
|
+
const defs: BridgeToolDef[] = [];
|
|
405
|
+
const seenNames = new Set<string>();
|
|
406
|
+
const seenPiNames = new Set<string>();
|
|
407
|
+
for (const source of sources) {
|
|
408
|
+
if (defs.length >= MAX_BRIDGED_TOOLS) break;
|
|
409
|
+
if (typeof source.name !== "string" || !isBridgableToolName(source.name)) continue;
|
|
410
|
+
if (seenPiNames.has(source.name)) continue;
|
|
411
|
+
const name = toSafeBridgeName(source.name);
|
|
412
|
+
if (seenNames.has(name)) continue;
|
|
413
|
+
// MCP requires an object root; anything else degrades to no-arg form
|
|
414
|
+
// instead of shipping a schema agy cannot validate against.
|
|
415
|
+
const cloned = jsonClone(source.parameters);
|
|
416
|
+
const inputSchema =
|
|
417
|
+
cloned && (cloned as { type?: unknown }).type === "object" && typeof (cloned as { properties?: unknown }).properties === "object"
|
|
418
|
+
? (cloned as Record<string, unknown>)
|
|
419
|
+
: { type: "object", properties: {} };
|
|
420
|
+
seenPiNames.add(source.name);
|
|
421
|
+
seenNames.add(name);
|
|
422
|
+
defs.push({
|
|
423
|
+
name,
|
|
424
|
+
piName: source.name,
|
|
425
|
+
description:
|
|
426
|
+
typeof source.description === "string" && source.description.trim()
|
|
427
|
+
? source.description.trim().slice(0, 500)
|
|
428
|
+
: `Pi tool ${source.name}`,
|
|
429
|
+
inputSchema,
|
|
430
|
+
});
|
|
431
|
+
}
|
|
432
|
+
return defs;
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
/** Fingerprint the bridged catalog: changes recycle the driver (fresh ListTools). */
|
|
436
|
+
export function bridgeToolsFingerprint(tools: BridgeToolDef[]): string {
|
|
437
|
+
const canonical = JSON.stringify(
|
|
438
|
+
tools.map((tool) => [tool.name, tool.piName, tool.description, tool.inputSchema]),
|
|
439
|
+
);
|
|
440
|
+
let hash = 5381;
|
|
441
|
+
for (let i = 0; i < canonical.length; i++) {
|
|
442
|
+
hash = ((hash << 5) + hash + canonical.charCodeAt(i)) | 0;
|
|
443
|
+
}
|
|
444
|
+
return `n${tools.length}-h${(hash >>> 0).toString(16)}`;
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
/**
|
|
448
|
+
* Default runner: driver turns serialized on the per-directory lock so a
|
|
449
|
+
* provider turn can never race a delegation run (or another provider turn)
|
|
450
|
+
* in the same directory. Lock waits count against the turn timeout. One
|
|
451
|
+
* runner per directory, shared across Pi turns so suspended (parked) turns
|
|
452
|
+
* resume on the same driver.
|
|
453
|
+
*/
|
|
454
|
+
export function getProviderRunner(dir: string): ProviderTurnRunner {
|
|
455
|
+
const key = path.resolve(dir);
|
|
456
|
+
const existing = providerRunners.get(key);
|
|
457
|
+
if (existing) return existing;
|
|
458
|
+
const driver = getProviderDriver(dir);
|
|
459
|
+
const runner: ProviderTurnRunner = {
|
|
460
|
+
run: (request) => {
|
|
461
|
+
const lockStart = Date.now();
|
|
462
|
+
return withDirLock(
|
|
463
|
+
request.dir,
|
|
464
|
+
async () => {
|
|
465
|
+
const waited = Date.now() - lockStart;
|
|
466
|
+
const remaining = Math.max(5_000, request.timeoutMs - waited);
|
|
467
|
+
// Bridge startup never fails a turn: without a handle the driver
|
|
468
|
+
// simply spawns plain and parks are refused at the bridge.
|
|
469
|
+
const bridge = await ensureProviderBridge(request.dir).catch(() => undefined);
|
|
470
|
+
// Process-stable staging root: agy can open staged images even
|
|
471
|
+
// with permissions enforced (no per-turn fingerprint churn).
|
|
472
|
+
const imageRoot = await ensureImageStagingRoot().catch(() => undefined);
|
|
473
|
+
const fingerprint = bridgeToolsFingerprint(request.bridgedTools);
|
|
474
|
+
if (bridge) {
|
|
475
|
+
bridge.setTools(request.bridgedTools);
|
|
476
|
+
bridge.setParkHandler((park) =>
|
|
477
|
+
driver.notifyPark({ callId: park.callId, toolName: park.toolName, args: park.args }),
|
|
478
|
+
);
|
|
479
|
+
driver.onParksOrphaned = (message) => {
|
|
480
|
+
bridge.failAllParks(message);
|
|
481
|
+
// Abandoned suspensions (wall timer, teardown kills) reclaim
|
|
482
|
+
// their staging here; nothing else will consume them.
|
|
483
|
+
const stale = suspendedByDir.get(path.resolve(request.dir));
|
|
484
|
+
if (stale) {
|
|
485
|
+
suspendedByDir.delete(path.resolve(request.dir));
|
|
486
|
+
void runImageCleanups(stale.imageCleanups);
|
|
487
|
+
}
|
|
488
|
+
};
|
|
489
|
+
}
|
|
490
|
+
const end = await driver.turn(
|
|
491
|
+
{
|
|
492
|
+
dir: request.dir,
|
|
493
|
+
fullModel: request.fullModel,
|
|
494
|
+
effort: request.effort,
|
|
495
|
+
skipPermissions: request.skipPermissions,
|
|
496
|
+
bridgeDir: bridge?.configDir,
|
|
497
|
+
bridgeTools: bridge ? fingerprint : undefined,
|
|
498
|
+
imageRoot,
|
|
499
|
+
},
|
|
500
|
+
{
|
|
501
|
+
prompt: request.prompt,
|
|
502
|
+
resumeConversationId: request.resumeConversationId,
|
|
503
|
+
signal: request.signal,
|
|
504
|
+
timeoutMs: remaining,
|
|
505
|
+
onText: request.callbacks?.onText,
|
|
506
|
+
onActivity: request.callbacks?.onActivity,
|
|
507
|
+
},
|
|
508
|
+
);
|
|
509
|
+
return toRunEnd(end);
|
|
510
|
+
},
|
|
511
|
+
request.signal,
|
|
512
|
+
request.timeoutMs,
|
|
513
|
+
);
|
|
514
|
+
},
|
|
515
|
+
resume: async (deliveries, callbacks, resumeSignal, resumeTimeoutMs) => {
|
|
516
|
+
// Like run: resumed phases hold the child and must not race
|
|
517
|
+
// delegation (or another session's fresh turn) in the directory.
|
|
518
|
+
return withDirLock(
|
|
519
|
+
dir,
|
|
520
|
+
async () => {
|
|
521
|
+
const bridge = providerBridges.get(path.resolve(dir));
|
|
522
|
+
if (!bridge) throw new Error("agy provider turn has no bridge to resume on");
|
|
523
|
+
for (const delivery of deliveries) {
|
|
524
|
+
bridge.completePark(delivery.callId, { text: delivery.text, isError: delivery.isError });
|
|
525
|
+
}
|
|
526
|
+
const end = await driver.continueTurn({
|
|
527
|
+
signal: resumeSignal,
|
|
528
|
+
timeoutMs: resumeTimeoutMs,
|
|
529
|
+
onText: callbacks?.onText,
|
|
530
|
+
onActivity: callbacks?.onActivity,
|
|
531
|
+
});
|
|
532
|
+
return toRunEnd(end);
|
|
533
|
+
},
|
|
534
|
+
resumeSignal,
|
|
535
|
+
resumeTimeoutMs,
|
|
536
|
+
);
|
|
537
|
+
},
|
|
538
|
+
cancel: () => {
|
|
539
|
+
driver.cancelSuspended("agy provider turn was cancelled");
|
|
540
|
+
providerBridges.get(path.resolve(dir))?.failAllParks("agy provider turn was cancelled");
|
|
541
|
+
},
|
|
542
|
+
};
|
|
543
|
+
providerRunners.set(key, runner);
|
|
544
|
+
return runner;
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
function toRunEnd(end: { kind: "done"; outcome: ProviderTurnResult } | { kind: "parked"; park: { callId: string; toolName: string; args: Record<string, unknown> } }): ProviderRunEnd {
|
|
548
|
+
if (end.kind === "parked") {
|
|
549
|
+
return { kind: "parked", park: { callId: end.park.callId, toolName: end.park.toolName, args: end.park.args } };
|
|
550
|
+
}
|
|
551
|
+
return { kind: "done", result: end.outcome };
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
/**
|
|
555
|
+
* Driver registry: one persistent agy process per working directory, shared
|
|
556
|
+
* across turns. Reset via closeProviderDrivers() (session shutdown, tests).
|
|
557
|
+
*/
|
|
558
|
+
const providerDrivers = new Map<string, AgyProviderDriver>();
|
|
559
|
+
|
|
560
|
+
export function getProviderDriver(dir: string): AgyProviderDriver {
|
|
561
|
+
// Resolve spelling variants (./, ../) to one driver per directory. (Symlink
|
|
562
|
+
// variants still alias apart; the dir lock owns full canonicalization.)
|
|
563
|
+
const key = path.resolve(dir);
|
|
564
|
+
let driver = providerDrivers.get(key);
|
|
565
|
+
if (!driver) {
|
|
566
|
+
driver = new AgyProviderDriver();
|
|
567
|
+
providerDrivers.set(key, driver);
|
|
568
|
+
}
|
|
569
|
+
return driver;
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
/**
|
|
573
|
+
* MCP bridges, one per directory, started lazily on the first bridged turn.
|
|
574
|
+
* A stored `undefined` means bridging is disabled or failed for the dir —
|
|
575
|
+
* turns proceed plain instead of retrying a broken server every turn.
|
|
576
|
+
*/
|
|
577
|
+
const providerBridges = new Map<string, McpBridgeHandle | undefined>();
|
|
578
|
+
|
|
579
|
+
async function ensureProviderBridge(dir: string): Promise<McpBridgeHandle | undefined> {
|
|
580
|
+
const key = path.resolve(dir);
|
|
581
|
+
if (providerBridges.has(key)) return providerBridges.get(key);
|
|
582
|
+
let handle: McpBridgeHandle | undefined;
|
|
583
|
+
try {
|
|
584
|
+
const config = await loadAgyConfig();
|
|
585
|
+
if (config.providerBridge !== false) {
|
|
586
|
+
handle = await startMcpBridge(dir);
|
|
587
|
+
}
|
|
588
|
+
} catch {
|
|
589
|
+
handle = undefined;
|
|
590
|
+
}
|
|
591
|
+
providerBridges.set(key, handle);
|
|
592
|
+
return handle;
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
const providerRunners = new Map<string, ProviderTurnRunner>();
|
|
596
|
+
|
|
597
|
+
/** Stop memoized bridges so the next turn re-resolves them (toggle support). */
|
|
598
|
+
export async function resetProviderBridges(): Promise<void> {
|
|
599
|
+
const bridges = [...providerBridges.values()];
|
|
600
|
+
providerBridges.clear();
|
|
601
|
+
await Promise.all(
|
|
602
|
+
bridges.map((bridge) => bridge?.stop().catch(() => undefined)),
|
|
603
|
+
);
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
export interface ProviderBridgeStatus {
|
|
607
|
+
dir: string;
|
|
608
|
+
running: boolean;
|
|
609
|
+
toolCount?: number;
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
/** Point-in-time bridge states for status surfaces. Never throws. */
|
|
613
|
+
export function describeProviderBridges(): ProviderBridgeStatus[] {
|
|
614
|
+
const out: ProviderBridgeStatus[] = [];
|
|
615
|
+
try {
|
|
616
|
+
for (const [dir, bridge] of providerBridges) {
|
|
617
|
+
out.push({ dir, running: !!bridge, toolCount: bridge?.describe().toolCount });
|
|
618
|
+
}
|
|
619
|
+
} catch {
|
|
620
|
+
// Status surfaces must never break callers.
|
|
621
|
+
}
|
|
622
|
+
return out;
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
export interface ProviderStatusSuspended {
|
|
626
|
+
toolCallId: string;
|
|
627
|
+
toolName: string;
|
|
628
|
+
modelId: string;
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
export interface ProviderStatus {
|
|
632
|
+
dir: string;
|
|
633
|
+
/** Driver snapshot, when a driver exists for the directory. */
|
|
634
|
+
driver?: {
|
|
635
|
+
state: string;
|
|
636
|
+
turns: number;
|
|
637
|
+
reuses: number;
|
|
638
|
+
recycles: number;
|
|
639
|
+
lastRecycleReason?: string;
|
|
640
|
+
boundConversationId?: string;
|
|
641
|
+
};
|
|
642
|
+
/** Bridge description, when a bridge is running for the directory. */
|
|
643
|
+
bridge?: { toolCount: number };
|
|
644
|
+
/** Suspended turns awaiting Pi tool results. */
|
|
645
|
+
suspended: ProviderStatusSuspended[];
|
|
646
|
+
/** Live image staging dirs process-wide. */
|
|
647
|
+
stagedImages: number;
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
/** Non-creating driver lookup (status surfaces must not spawn state). */
|
|
651
|
+
export function peekProviderDriver(dir: string): AgyProviderDriver | undefined {
|
|
652
|
+
return providerDrivers.get(path.resolve(dir));
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
/** Point-in-time provider status for doctor and debugging. Never throws. */
|
|
656
|
+
export function getProviderStatus(dir: string): ProviderStatus {
|
|
657
|
+
const key = path.resolve(dir);
|
|
658
|
+
const suspended: ProviderStatusSuspended[] = [];
|
|
659
|
+
for (const [suspendedDir, entry] of suspendedByDir) {
|
|
660
|
+
if (suspendedDir === key) {
|
|
661
|
+
suspended.push({ toolCallId: entry.toolCallId, toolName: entry.park.toolName, modelId: entry.modelId });
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
try {
|
|
665
|
+
const driver = providerDrivers.get(key);
|
|
666
|
+
const snapshot = driver?.snapshot();
|
|
667
|
+
const bridge = providerBridges.get(key);
|
|
668
|
+
return {
|
|
669
|
+
dir: key,
|
|
670
|
+
driver: snapshot
|
|
671
|
+
? {
|
|
672
|
+
state: snapshot.state,
|
|
673
|
+
turns: snapshot.stats.turns,
|
|
674
|
+
reuses: snapshot.stats.reuses,
|
|
675
|
+
recycles: snapshot.stats.recycles,
|
|
676
|
+
lastRecycleReason: snapshot.stats.lastRecycleReason,
|
|
677
|
+
boundConversationId: snapshot.boundConversationId,
|
|
678
|
+
}
|
|
679
|
+
: undefined,
|
|
680
|
+
bridge: bridge ? { toolCount: bridge.describe().toolCount } : undefined,
|
|
681
|
+
suspended,
|
|
682
|
+
stagedImages: liveStagingDirs.size,
|
|
683
|
+
};
|
|
684
|
+
} catch {
|
|
685
|
+
return { dir: key, suspended, stagedImages: 0 };
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
/** Kill all driver processes and drop them; the next turn respawns lazily. */
|
|
690
|
+
export async function closeProviderDrivers(): Promise<void> {
|
|
691
|
+
const drivers = [...providerDrivers.values()];
|
|
692
|
+
providerDrivers.clear();
|
|
693
|
+
providerRunners.clear();
|
|
694
|
+
clearSuspendedTurns();
|
|
695
|
+
await clearImageStaging();
|
|
696
|
+
await Promise.all(drivers.map((driver) => driver.close()));
|
|
697
|
+
await resetProviderBridges();
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
export interface AgyProviderStreamDeps {
|
|
701
|
+
entries: AgyProviderModelEntry[];
|
|
702
|
+
runner?: ProviderTurnRunner;
|
|
703
|
+
/** Working directory for agy turns. Defaults to process.cwd() at turn time. */
|
|
704
|
+
dir?: string;
|
|
705
|
+
skipPermissions?: boolean;
|
|
706
|
+
timeoutMs?: number;
|
|
707
|
+
/** Pi tools to bridge into agy turns (projected per turn by the caller). */
|
|
708
|
+
tools?: ProviderToolSource[];
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
export interface AgyStreamSimpleModel {
|
|
712
|
+
id: string;
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
export interface AgyStreamSimpleOptions {
|
|
716
|
+
signal?: AbortSignal;
|
|
717
|
+
reasoning?: AgyThinkingLevel;
|
|
718
|
+
/** Active Pi tools for this turn (bridged into agy). */
|
|
719
|
+
tools?: ProviderToolSource[];
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
/**
|
|
723
|
+
* Minimal event-stream + message types (structural subset of Pi's pi-ai
|
|
724
|
+
* types) so this module is unit-testable with fakes. The extension entry
|
|
725
|
+
* passes the real `createAssistantMessageEventStream` from pi-ai.
|
|
726
|
+
*/
|
|
727
|
+
export interface AgyEventStream {
|
|
728
|
+
push: (event: Record<string, unknown>) => void;
|
|
729
|
+
end: () => void;
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
export interface AgyStreamFactory {
|
|
733
|
+
createStream: () => AgyEventStream;
|
|
734
|
+
getSystemPrompt: (messages: ProviderTranscriptMessage[]) => string;
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
/** Resolve the catalog entry + effort for a selected provider model id. */
|
|
738
|
+
export function resolveProviderTurnModel(
|
|
739
|
+
entries: AgyProviderModelEntry[],
|
|
740
|
+
modelId: string,
|
|
741
|
+
reasoning?: AgyThinkingLevel,
|
|
742
|
+
): { full: string; effort?: AgyProviderEffort } {
|
|
743
|
+
const entry = entries.find((candidate) => candidate.id === modelId);
|
|
744
|
+
if (!entry) {
|
|
745
|
+
throw new Error(
|
|
746
|
+
`Unknown ${AGY_PROVIDER_ID} model '${modelId}'; pick another via /model (the agy catalog may have changed — restart Pi to refresh).`,
|
|
747
|
+
);
|
|
748
|
+
}
|
|
749
|
+
const effort =
|
|
750
|
+
entry.efforts && entry.efforts.length > 0
|
|
751
|
+
? toProviderEffort(reasoning, entry.efforts)
|
|
752
|
+
: undefined;
|
|
753
|
+
return { full: entry.full, effort };
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
/**
|
|
757
|
+
* Collect Pi tool result bodies addressed to a suspended shadow tool call.
|
|
758
|
+
* The bridge call id comes from the suspension itself: the shadow id only
|
|
759
|
+
* exists in Pi's transcript, while agy waits on the bridge's park id.
|
|
760
|
+
* Mixing them up strands agy on an uncompletable call.
|
|
761
|
+
*/
|
|
762
|
+
export function collectParkedDeliveries(
|
|
763
|
+
messages: ProviderTranscriptMessage[],
|
|
764
|
+
toolCallId: string,
|
|
765
|
+
): Array<{ text: string; isError: boolean }> {
|
|
766
|
+
const deliveries: Array<{ text: string; isError: boolean }> = [];
|
|
767
|
+
for (const message of messages) {
|
|
768
|
+
if (message.role !== "toolResult" || message.toolCallId !== toolCallId) continue;
|
|
769
|
+
deliveries.push({
|
|
770
|
+
text: textOfContent(message.content).trim(),
|
|
771
|
+
isError: message.isError === true,
|
|
772
|
+
});
|
|
773
|
+
}
|
|
774
|
+
return deliveries;
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
/** Does the transcript hold our shadow toolCall (same or later, any result)? */
|
|
778
|
+
function transcriptHasToolCall(messages: ProviderTranscriptMessage[], toolCallId: string): boolean {
|
|
779
|
+
return messages.some((message) => {
|
|
780
|
+
const content = message.content;
|
|
781
|
+
if (!Array.isArray(content)) return false;
|
|
782
|
+
return content.some(
|
|
783
|
+
(block) =>
|
|
784
|
+
typeof block === "object" &&
|
|
785
|
+
block !== null &&
|
|
786
|
+
(block as Record<string, unknown>).type === "toolCall" &&
|
|
787
|
+
(block as Record<string, unknown>).id === toolCallId,
|
|
788
|
+
);
|
|
789
|
+
});
|
|
790
|
+
}
|
|
791
|
+
|
|
792
|
+
/** Is there a non-empty user message after our shadow toolCall? */
|
|
793
|
+
function hasUserMessageAfterToolCall(messages: ProviderTranscriptMessage[], toolCallId: string): boolean {
|
|
794
|
+
let seenCall = false;
|
|
795
|
+
for (const message of messages) {
|
|
796
|
+
if (!seenCall) {
|
|
797
|
+
if (transcriptHasToolCall([message], toolCallId)) seenCall = true;
|
|
798
|
+
continue;
|
|
799
|
+
}
|
|
800
|
+
if (message.role === "user" && textOfContent(message.content).trim()) return true;
|
|
801
|
+
}
|
|
802
|
+
return false;
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
interface SuspendedTurn {
|
|
806
|
+
runner: ProviderTurnRunner;
|
|
807
|
+
toolCallId: string;
|
|
808
|
+
park: ProviderToolPark;
|
|
809
|
+
modelId: string;
|
|
810
|
+
/** Image staging cleanups owned by the suspended turn. */
|
|
811
|
+
imageCleanups: Array<() => Promise<void>>;
|
|
812
|
+
}
|
|
813
|
+
|
|
814
|
+
/** Run cleanups sequentially, never throwing. */
|
|
815
|
+
async function runImageCleanups(cleanups: Array<() => Promise<void>>): Promise<void> {
|
|
816
|
+
for (const cleanup of cleanups) {
|
|
817
|
+
try {
|
|
818
|
+
await cleanup();
|
|
819
|
+
} catch {
|
|
820
|
+
// Best effort per handle.
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
|
|
825
|
+
// Suspended turns awaiting Pi tool results, keyed by directory. Entries are
|
|
826
|
+
// consumed only by the Pi turn delivering the matching toolResult; anything
|
|
827
|
+
// else leaves them untouched (another session's business) until the
|
|
828
|
+
// suspension wall timer fires. Module scope so teardown can reach them.
|
|
829
|
+
const suspendedByDir = new Map<string, SuspendedTurn>();
|
|
830
|
+
|
|
831
|
+
/** Drop all suspended-turn records (teardown, tests). Runners are untouched. */
|
|
832
|
+
export function clearSuspendedTurns(): void {
|
|
833
|
+
suspendedByDir.clear();
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
/**
|
|
837
|
+
* Build a `streamSimple` handler for the registered provider. Conversation
|
|
838
|
+
* continuity: resume the in-memory conversation for this model when present,
|
|
839
|
+
* else the session store's provider-recorded conversation, else start fresh.
|
|
840
|
+
* Completed conversations are recorded to the session store so `/agy
|
|
841
|
+
* sessions` can resume them.
|
|
842
|
+
*
|
|
843
|
+
* Bridged Pi tools round-trip through suspended turns: when agy calls one,
|
|
844
|
+
* this emits a real shadow `toolCall` (Pi executes it with normal
|
|
845
|
+
* permissions and review) and ends with `toolUse`; the Pi turn whose
|
|
846
|
+
* transcript delivers the matching `toolResult` resumes the driver turn.
|
|
847
|
+
*/
|
|
848
|
+
export function createAgyStreamSimple(
|
|
849
|
+
factory: AgyStreamFactory,
|
|
850
|
+
deps: AgyProviderStreamDeps,
|
|
851
|
+
): (
|
|
852
|
+
model: AgyStreamSimpleModel,
|
|
853
|
+
messages: ProviderTranscriptMessage[],
|
|
854
|
+
options?: AgyStreamSimpleOptions,
|
|
855
|
+
) => AgyEventStream {
|
|
856
|
+
const resumeByModel = new Map<string, string>();
|
|
857
|
+
const getRunner = (dir: string): ProviderTurnRunner => deps.runner ?? getProviderRunner(dir);
|
|
858
|
+
|
|
859
|
+
return (model, messages, options) => {
|
|
860
|
+
const stream = factory.createStream();
|
|
861
|
+
const output: {
|
|
862
|
+
role: string;
|
|
863
|
+
content: Array<Record<string, unknown>>;
|
|
864
|
+
api: string;
|
|
865
|
+
provider: string;
|
|
866
|
+
model: string;
|
|
867
|
+
usage: {
|
|
868
|
+
input: number;
|
|
869
|
+
output: number;
|
|
870
|
+
cacheRead: number;
|
|
871
|
+
cacheWrite: number;
|
|
872
|
+
totalTokens: number;
|
|
873
|
+
cost: { input: number; output: number; cacheRead: number; cacheWrite: number; total: number };
|
|
874
|
+
};
|
|
875
|
+
stopReason: string;
|
|
876
|
+
timestamp: number;
|
|
877
|
+
errorMessage?: string;
|
|
878
|
+
} = {
|
|
879
|
+
role: "assistant",
|
|
880
|
+
content: [],
|
|
881
|
+
api: AGY_PROVIDER_API,
|
|
882
|
+
provider: AGY_PROVIDER_ID,
|
|
883
|
+
model: model.id,
|
|
884
|
+
usage: {
|
|
885
|
+
input: 0,
|
|
886
|
+
output: 0,
|
|
887
|
+
cacheRead: 0,
|
|
888
|
+
cacheWrite: 0,
|
|
889
|
+
totalTokens: 0,
|
|
890
|
+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
|
|
891
|
+
},
|
|
892
|
+
stopReason: "pending",
|
|
893
|
+
timestamp: Date.now(),
|
|
894
|
+
};
|
|
895
|
+
|
|
896
|
+
(async () => {
|
|
897
|
+
let turnModel: { full: string; effort?: AgyProviderEffort };
|
|
898
|
+
try {
|
|
899
|
+
turnModel = resolveProviderTurnModel(deps.entries, model.id, options?.reasoning);
|
|
900
|
+
} catch (error) {
|
|
901
|
+
output.stopReason = "error";
|
|
902
|
+
output.errorMessage = error instanceof Error ? error.message : String(error);
|
|
903
|
+
stream.push({ type: "error", reason: output.stopReason, error: output });
|
|
904
|
+
stream.end();
|
|
905
|
+
return;
|
|
906
|
+
}
|
|
907
|
+
|
|
908
|
+
stream.push({ type: "start", partial: output });
|
|
909
|
+
const dir = deps.dir ?? process.cwd();
|
|
910
|
+
const signal = options?.signal ?? new AbortController().signal;
|
|
911
|
+
// Image staging owned by this invocation until terminal settle; a
|
|
912
|
+
// park transfers ownership into the suspension entry. Declared here
|
|
913
|
+
// so both the try body and the catch below can clean it.
|
|
914
|
+
const pendingImageCleanups: Array<() => Promise<void>> = [];
|
|
915
|
+
|
|
916
|
+
try {
|
|
917
|
+
const systemPrompt = factory.getSystemPrompt(messages);
|
|
918
|
+
// Only resume when the transcript already holds a prior assistant
|
|
919
|
+
// turn: a fresh session (user message only) must start a new agy
|
|
920
|
+
// conversation instead of inheriting stale context.
|
|
921
|
+
const hasPriorAssistantTurn = messages.some((message) => message.role === "assistant");
|
|
922
|
+
|
|
923
|
+
let textIndex = -1;
|
|
924
|
+
let thinkingIndex = -1;
|
|
925
|
+
const ensureText = (): number => {
|
|
926
|
+
if (textIndex === -1) {
|
|
927
|
+
output.content.push({ type: "text", text: "" });
|
|
928
|
+
textIndex = output.content.length - 1;
|
|
929
|
+
stream.push({ type: "text_start", contentIndex: textIndex, partial: output });
|
|
930
|
+
}
|
|
931
|
+
return textIndex;
|
|
932
|
+
};
|
|
933
|
+
const ensureThinking = (): number => {
|
|
934
|
+
if (thinkingIndex === -1) {
|
|
935
|
+
output.content.push({ type: "thinking", thinking: "" });
|
|
936
|
+
thinkingIndex = output.content.length - 1;
|
|
937
|
+
stream.push({ type: "thinking_start", contentIndex: thinkingIndex, partial: output });
|
|
938
|
+
}
|
|
939
|
+
return thinkingIndex;
|
|
940
|
+
};
|
|
941
|
+
|
|
942
|
+
const callbacks: ProviderTurnCallbacks = {
|
|
943
|
+
onText: (delta) => {
|
|
944
|
+
const index = ensureText();
|
|
945
|
+
const block = output.content[index] as { text: string };
|
|
946
|
+
block.text += delta;
|
|
947
|
+
output.usage.output += delta.length;
|
|
948
|
+
stream.push({ type: "text_delta", contentIndex: index, delta, partial: output });
|
|
949
|
+
},
|
|
950
|
+
onActivity: (label) => {
|
|
951
|
+
const index = ensureThinking();
|
|
952
|
+
const block = output.content[index] as { thinking: string };
|
|
953
|
+
block.thinking += (block.thinking ? "\n" : "") + label;
|
|
954
|
+
stream.push({ type: "thinking_delta", contentIndex: index, delta: label, partial: output });
|
|
955
|
+
},
|
|
956
|
+
};
|
|
957
|
+
|
|
958
|
+
const runner = getRunner(dir);
|
|
959
|
+
const skey = path.resolve(dir);
|
|
960
|
+
const prior = suspendedByDir.get(skey);
|
|
961
|
+
const bodies = prior ? collectParkedDeliveries(messages, prior.toolCallId) : [];
|
|
962
|
+
let end: ProviderRunEnd;
|
|
963
|
+
if (prior && bodies.length > 0) {
|
|
964
|
+
suspendedByDir.delete(skey);
|
|
965
|
+
// Images riding on the delivered tool results are staged too:
|
|
966
|
+
// the resumed agy turn reads them by path. Owned by this
|
|
967
|
+
// invocation; cleaned on its terminal settle below.
|
|
968
|
+
const deliveryImages = await stageImages(collectImageBlocks(messages, prior.toolCallId));
|
|
969
|
+
const resumeCleanups = [...prior.imageCleanups, deliveryImages.cleanup];
|
|
970
|
+
const imageRefs = [...deliveryImages.paths.values()];
|
|
971
|
+
// Deliver by bridge park id (what agy waits on), matched via the
|
|
972
|
+
// shadow toolCall id (what Pi's transcript carries).
|
|
973
|
+
const deliveries: ProviderToolDelivery[] = bodies.map((body) => ({
|
|
974
|
+
callId: prior.park.callId,
|
|
975
|
+
text:
|
|
976
|
+
body.text +
|
|
977
|
+
(imageRefs.length > 0
|
|
978
|
+
? `\n[attached images saved at: ${imageRefs.join(", ")} — open them with your file tools to view]`
|
|
979
|
+
: ""),
|
|
980
|
+
isError: body.isError,
|
|
981
|
+
}));
|
|
982
|
+
try {
|
|
983
|
+
end = await runner.resume(
|
|
984
|
+
deliveries,
|
|
985
|
+
callbacks,
|
|
986
|
+
signal,
|
|
987
|
+
deps.timeoutMs ?? PROVIDER_TURN_TIMEOUT_MS,
|
|
988
|
+
);
|
|
989
|
+
} catch (error) {
|
|
990
|
+
// The suspended turn is gone (agy moved on without us): fail the
|
|
991
|
+
// parks so nothing strands, then surface the failure loudly.
|
|
992
|
+
try {
|
|
993
|
+
runner.cancel();
|
|
994
|
+
} catch {
|
|
995
|
+
// Cancel is best effort next to the real error.
|
|
996
|
+
}
|
|
997
|
+
await runImageCleanups(resumeCleanups);
|
|
998
|
+
throw error;
|
|
999
|
+
}
|
|
1000
|
+
// Staging ownership transfers to the shared settle below: a new
|
|
1001
|
+
// park carries it into the suspension, terminal settle cleans it.
|
|
1002
|
+
pendingImageCleanups.push(...resumeCleanups);
|
|
1003
|
+
} else {
|
|
1004
|
+
if (prior && hasUserMessageAfterToolCall(messages, prior.toolCallId)) {
|
|
1005
|
+
// Our own transcript moved on without delivering (abort, reject,
|
|
1006
|
+
// retry): cancel the stale suspension and start fresh instead
|
|
1007
|
+
// of bricking the directory behind the suspended guard.
|
|
1008
|
+
suspendedByDir.delete(skey);
|
|
1009
|
+
try {
|
|
1010
|
+
runner.cancel();
|
|
1011
|
+
} catch {
|
|
1012
|
+
// Cancel is best effort next to a fresh turn.
|
|
1013
|
+
}
|
|
1014
|
+
await runImageCleanups(prior.imageCleanups);
|
|
1015
|
+
}
|
|
1016
|
+
let resume = hasPriorAssistantTurn ? resumeByModel.get(model.id) : undefined;
|
|
1017
|
+
if (!resume && hasPriorAssistantTurn) {
|
|
1018
|
+
try {
|
|
1019
|
+
const record = await getSession(dir);
|
|
1020
|
+
if (record?.last_conversation_id && record.last_model === model.id) {
|
|
1021
|
+
resume = record.last_conversation_id;
|
|
1022
|
+
}
|
|
1023
|
+
} catch {
|
|
1024
|
+
// Session-store failures must never block a turn.
|
|
1025
|
+
}
|
|
1026
|
+
}
|
|
1027
|
+
// Materialize attached images as files agy's tools can open;
|
|
1028
|
+
// paths render inline, failures degrade to omitted notes. Held
|
|
1029
|
+
// for the driver turn: terminal settle below cleans it, a park
|
|
1030
|
+
// carries it into the suspension.
|
|
1031
|
+
const staged = await stageImages(collectImageBlocks(messages));
|
|
1032
|
+
pendingImageCleanups.push(staged.cleanup);
|
|
1033
|
+
const prompt = renderProviderPrompt(messages, systemPrompt || undefined, staged.paths);
|
|
1034
|
+
end = await runner.run({
|
|
1035
|
+
fullModel: turnModel.full,
|
|
1036
|
+
effort: turnModel.effort,
|
|
1037
|
+
prompt,
|
|
1038
|
+
dir,
|
|
1039
|
+
signal,
|
|
1040
|
+
timeoutMs: deps.timeoutMs ?? PROVIDER_TURN_TIMEOUT_MS,
|
|
1041
|
+
resumeConversationId: resume,
|
|
1042
|
+
skipPermissions: deps.skipPermissions ?? true,
|
|
1043
|
+
bridgedTools: projectBridgeTools(deps.tools ?? []),
|
|
1044
|
+
callbacks,
|
|
1045
|
+
});
|
|
1046
|
+
}
|
|
1047
|
+
|
|
1048
|
+
if (end.kind === "parked") {
|
|
1049
|
+
// A bridged Pi tool call: end any open blocks, then emit a REAL
|
|
1050
|
+
// shadow toolCall so Pi executes it with normal permissions,
|
|
1051
|
+
// approvals, and review. The Pi turn delivering the matching
|
|
1052
|
+
// toolResult resumes this driver turn.
|
|
1053
|
+
if (thinkingIndex !== -1) {
|
|
1054
|
+
const thinking = (output.content[thinkingIndex] as { thinking: string }).thinking;
|
|
1055
|
+
stream.push({ type: "thinking_end", contentIndex: thinkingIndex, content: thinking, partial: output });
|
|
1056
|
+
}
|
|
1057
|
+
if (textIndex !== -1) {
|
|
1058
|
+
const text = (output.content[textIndex] as { text: string }).text;
|
|
1059
|
+
stream.push({ type: "text_end", contentIndex: textIndex, content: text, partial: output });
|
|
1060
|
+
}
|
|
1061
|
+
const toolCallId = `agybridge-${randomBytes(8).toString("hex")}`;
|
|
1062
|
+
const toolCall = {
|
|
1063
|
+
type: "toolCall",
|
|
1064
|
+
id: toolCallId,
|
|
1065
|
+
name: end.park.toolName,
|
|
1066
|
+
arguments: end.park.args,
|
|
1067
|
+
};
|
|
1068
|
+
output.content.push(toolCall);
|
|
1069
|
+
const toolIndex = output.content.length - 1;
|
|
1070
|
+
stream.push({ type: "toolcall_start", contentIndex: toolIndex, partial: output });
|
|
1071
|
+
stream.push({ type: "toolcall_end", contentIndex: toolIndex, toolCall, partial: output });
|
|
1072
|
+
suspendedByDir.set(skey, {
|
|
1073
|
+
runner,
|
|
1074
|
+
toolCallId,
|
|
1075
|
+
park: end.park,
|
|
1076
|
+
modelId: model.id,
|
|
1077
|
+
imageCleanups: pendingImageCleanups,
|
|
1078
|
+
});
|
|
1079
|
+
output.usage.totalTokens =
|
|
1080
|
+
output.usage.input + output.usage.output + output.usage.cacheRead + output.usage.cacheWrite;
|
|
1081
|
+
output.stopReason = "toolUse";
|
|
1082
|
+
stream.push({ type: "done", reason: output.stopReason, message: output });
|
|
1083
|
+
stream.end();
|
|
1084
|
+
return;
|
|
1085
|
+
}
|
|
1086
|
+
const result = end.result;
|
|
1087
|
+
|
|
1088
|
+
if (thinkingIndex !== -1) {
|
|
1089
|
+
const thinking = (output.content[thinkingIndex] as { thinking: string }).thinking;
|
|
1090
|
+
stream.push({ type: "thinking_end", contentIndex: thinkingIndex, content: thinking, partial: output });
|
|
1091
|
+
}
|
|
1092
|
+
if (textIndex === -1) {
|
|
1093
|
+
// No live deltas arrived: the terminal response (if any) is the
|
|
1094
|
+
// answer — never answer empty when agy produced text.
|
|
1095
|
+
const index = ensureText();
|
|
1096
|
+
const fallback =
|
|
1097
|
+
result.text ||
|
|
1098
|
+
(result.activity.length > 0 ? result.activity.join("\n") : "(agy returned no text)");
|
|
1099
|
+
(output.content[index] as { text: string }).text = fallback;
|
|
1100
|
+
stream.push({ type: "text_end", contentIndex: index, content: fallback, partial: output });
|
|
1101
|
+
} else {
|
|
1102
|
+
const block = output.content[textIndex];
|
|
1103
|
+
let finalText = (block as { text: string }).text;
|
|
1104
|
+
if (result.truncated) finalText += "\n\n[truncated: agy response exceeded the provider cap]";
|
|
1105
|
+
if (result.deniedActions && result.deniedActions.length > 0) {
|
|
1106
|
+
finalText += `\n\n[warning: agy reported ${result.deniedActions.length} denied action(s) alongside this response]`;
|
|
1107
|
+
}
|
|
1108
|
+
if (result.aborted) finalText += "\n\n[note: turn cancelled — response is partial]";
|
|
1109
|
+
else if (result.timedOut) finalText += "\n\n[note: turn timed out — response is partial]";
|
|
1110
|
+
(block as { text: string }).text = finalText;
|
|
1111
|
+
stream.push({ type: "text_end", contentIndex: textIndex, content: finalText, partial: output });
|
|
1112
|
+
}
|
|
1113
|
+
|
|
1114
|
+
output.usage.totalTokens = output.usage.input + output.usage.output + output.usage.cacheRead + output.usage.cacheWrite;
|
|
1115
|
+
// Partial turns must never masquerade as clean stops: surface the
|
|
1116
|
+
// real terminal state so Pi retries or reports instead of accepting
|
|
1117
|
+
// truncated text as a complete answer.
|
|
1118
|
+
if (result.aborted) output.stopReason = "aborted";
|
|
1119
|
+
else if (result.timedOut) output.stopReason = "length";
|
|
1120
|
+
else output.stopReason = "stop";
|
|
1121
|
+
if (result.conversationId) {
|
|
1122
|
+
resumeByModel.set(model.id, result.conversationId);
|
|
1123
|
+
const latestUser = [...messages].reverse().find((message) => message.role === "user");
|
|
1124
|
+
const summary = textOfContent(latestUser?.content).trim().slice(0, 80) || undefined;
|
|
1125
|
+
try {
|
|
1126
|
+
// Preserve a delegation-recorded agent: provider turns must not
|
|
1127
|
+
// wipe the agent that /agy continue would otherwise restore.
|
|
1128
|
+
const prior = await getSession(dir).catch(() => undefined);
|
|
1129
|
+
await saveSession(dir, result.conversationId, model.id, undefined, summary, prior?.last_agent);
|
|
1130
|
+
} catch {
|
|
1131
|
+
// Recording failures must never fail a completed turn.
|
|
1132
|
+
}
|
|
1133
|
+
}
|
|
1134
|
+
stream.push({ type: "done", reason: output.stopReason, message: output });
|
|
1135
|
+
stream.end();
|
|
1136
|
+
await runImageCleanups(pendingImageCleanups);
|
|
1137
|
+
} catch (error) {
|
|
1138
|
+
output.stopReason = signal.aborted ? "aborted" : "error";
|
|
1139
|
+
output.errorMessage = error instanceof Error ? error.message : String(error);
|
|
1140
|
+
stream.push({ type: "error", reason: output.stopReason, error: output });
|
|
1141
|
+
stream.end();
|
|
1142
|
+
await runImageCleanups(pendingImageCleanups);
|
|
1143
|
+
}
|
|
1144
|
+
})();
|
|
1145
|
+
|
|
1146
|
+
return stream;
|
|
1147
|
+
};
|
|
1148
|
+
}
|