pi-agy-provider 1.1.2 → 1.1.4
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/index.ts +22 -10
- package/lib/agy-acp-client.ts +191 -29
- package/lib/agy-acp-driver.ts +154 -85
- package/lib/agy-client.ts +21 -3
- package/lib/agy-driver.ts +2 -2
- package/lib/agy-thoughts.ts +64 -6
- package/lib/bridge.ts +113 -16
- package/lib/events.ts +1 -0
- package/lib/models.ts +43 -7
- package/lib/pi-tools-agent.ts +4 -0
- package/lib/prompt.ts +67 -13
- package/lib/reducer.ts +1 -0
- package/lib/turn.ts +1 -0
- package/package.json +1 -1
- package/src/provider.ts +92 -5
- package/src/runtime.ts +33 -2
package/lib/bridge.ts
CHANGED
|
@@ -28,6 +28,7 @@ export const BRIDGE_SERVER_NAME = "pi-bridge";
|
|
|
28
28
|
export const BRIDGE_TOOL_PREFIX = "pi__";
|
|
29
29
|
/** Per-call cap; must stay below agy's 600s turn timeout so agy can still report the failure. */
|
|
30
30
|
export const BRIDGE_CALL_TIMEOUT_MS = 480_000;
|
|
31
|
+
export const DEFAULT_BRIDGE_PROGRESS_KEEPALIVE_MS = 15_000;
|
|
31
32
|
|
|
32
33
|
export interface BridgeToolDef {
|
|
33
34
|
/** Real pi tool name (without the `pi__` prefix). */
|
|
@@ -108,6 +109,9 @@ interface JsonRpcRequest {
|
|
|
108
109
|
protocolVersion?: string;
|
|
109
110
|
name?: string;
|
|
110
111
|
arguments?: JsonObject;
|
|
112
|
+
_meta?: {
|
|
113
|
+
progressToken?: string | number;
|
|
114
|
+
};
|
|
111
115
|
};
|
|
112
116
|
}
|
|
113
117
|
|
|
@@ -144,9 +148,17 @@ export class AgyPiBridge {
|
|
|
144
148
|
#dynamic = new Map<string, DynamicTool>();
|
|
145
149
|
#catalogDigest = createHash("sha256").update("[]").digest("hex");
|
|
146
150
|
#catalogRevision = 0;
|
|
151
|
+
readonly #progressKeepaliveMs: number;
|
|
147
152
|
|
|
148
|
-
constructor(
|
|
153
|
+
constructor(
|
|
154
|
+
serverName: string = BRIDGE_SERVER_NAME,
|
|
155
|
+
options?: { progressKeepaliveMs?: number },
|
|
156
|
+
) {
|
|
149
157
|
this.serverName = serverName;
|
|
158
|
+
this.#progressKeepaliveMs = Math.max(
|
|
159
|
+
10,
|
|
160
|
+
options?.progressKeepaliveMs ?? DEFAULT_BRIDGE_PROGRESS_KEEPALIVE_MS,
|
|
161
|
+
);
|
|
150
162
|
}
|
|
151
163
|
|
|
152
164
|
/** Require `token` in the x-pi-bridge-token header on every request. */
|
|
@@ -240,6 +252,7 @@ export class AgyPiBridge {
|
|
|
240
252
|
start(): Promise<void> {
|
|
241
253
|
if (this.#server) return Promise.resolve();
|
|
242
254
|
const server = createServer((req, res) => this.#handleHttp(req, res));
|
|
255
|
+
server.maxConnections = 64;
|
|
243
256
|
this.#server = server;
|
|
244
257
|
return new Promise((resolve, reject) => {
|
|
245
258
|
const onError = (error: Error) => {
|
|
@@ -257,23 +270,32 @@ export class AgyPiBridge {
|
|
|
257
270
|
});
|
|
258
271
|
}
|
|
259
272
|
|
|
260
|
-
/** Fail all pending calls and stop listening. */
|
|
273
|
+
/** Fail all pending calls and stop listening, closing keep-alive sockets immediately. */
|
|
261
274
|
close(): Promise<void> {
|
|
262
275
|
const server = this.#server;
|
|
263
276
|
if (!server) return Promise.resolve();
|
|
264
277
|
this.#server = undefined;
|
|
265
278
|
this.#port = 0;
|
|
279
|
+
this.cancelPendingCalls("antigravity: pi session shut down while the tool call was pending.");
|
|
280
|
+
return new Promise((resolve) => {
|
|
281
|
+
server.close(() => resolve());
|
|
282
|
+
server.closeAllConnections?.();
|
|
283
|
+
});
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/** Cancel any in-flight Pi tool calls when the upstream Antigravity turn exits early. */
|
|
287
|
+
cancelPendingCalls(
|
|
288
|
+
reason = "antigravity: turn ended before pi returned the tool result.",
|
|
289
|
+
): number {
|
|
290
|
+
if (this.#pending.size === 0) return 0;
|
|
291
|
+
let count = 0;
|
|
266
292
|
for (const pending of this.#pending.values()) {
|
|
267
293
|
clearTimeout(pending.timer);
|
|
268
|
-
pending.resolve({
|
|
269
|
-
|
|
270
|
-
isError: true,
|
|
271
|
-
});
|
|
294
|
+
pending.resolve({ content: reason, isError: true });
|
|
295
|
+
count += 1;
|
|
272
296
|
}
|
|
273
297
|
this.#pending.clear();
|
|
274
|
-
return
|
|
275
|
-
server.close(() => resolve());
|
|
276
|
-
});
|
|
298
|
+
return count;
|
|
277
299
|
}
|
|
278
300
|
|
|
279
301
|
/** True when the provider is still waiting for pi to execute this call. */
|
|
@@ -319,6 +341,79 @@ export class AgyPiBridge {
|
|
|
319
341
|
);
|
|
320
342
|
return;
|
|
321
343
|
}
|
|
344
|
+
const acceptHeader = Array.isArray(req.headers.accept)
|
|
345
|
+
? req.headers.accept.join(",")
|
|
346
|
+
: (req.headers.accept ?? "");
|
|
347
|
+
const progressToken = rpc.params?._meta?.progressToken;
|
|
348
|
+
const useSseProgress =
|
|
349
|
+
rpc.method === "tools/call" &&
|
|
350
|
+
acceptHeader.includes("text/event-stream") &&
|
|
351
|
+
(typeof progressToken === "string" || typeof progressToken === "number");
|
|
352
|
+
|
|
353
|
+
if (useSseProgress) {
|
|
354
|
+
res.writeHead(200, {
|
|
355
|
+
"content-type": "text/event-stream",
|
|
356
|
+
"cache-control": "no-cache",
|
|
357
|
+
connection: "keep-alive",
|
|
358
|
+
"mcp-session-id": SESSION_ID,
|
|
359
|
+
});
|
|
360
|
+
let progress = 0;
|
|
361
|
+
let keepalive: NodeJS.Timeout | undefined;
|
|
362
|
+
const stopKeepalive = () => {
|
|
363
|
+
if (!keepalive) return;
|
|
364
|
+
clearInterval(keepalive);
|
|
365
|
+
keepalive = undefined;
|
|
366
|
+
};
|
|
367
|
+
const sendProgress = () => {
|
|
368
|
+
if (res.writableEnded || res.destroyed) {
|
|
369
|
+
stopKeepalive();
|
|
370
|
+
return;
|
|
371
|
+
}
|
|
372
|
+
const frame = {
|
|
373
|
+
jsonrpc: "2.0",
|
|
374
|
+
method: "notifications/progress",
|
|
375
|
+
params: {
|
|
376
|
+
progressToken,
|
|
377
|
+
progress: progress++,
|
|
378
|
+
message: "Waiting for Pi tool execution",
|
|
379
|
+
},
|
|
380
|
+
};
|
|
381
|
+
res.write(`event: message\ndata: ${JSON.stringify(frame)}\n\n`);
|
|
382
|
+
};
|
|
383
|
+
res.once("close", stopKeepalive);
|
|
384
|
+
sendProgress();
|
|
385
|
+
keepalive = setInterval(sendProgress, this.#progressKeepaliveMs);
|
|
386
|
+
keepalive.unref?.();
|
|
387
|
+
|
|
388
|
+
void this.#handleRpc(rpc)
|
|
389
|
+
.then(
|
|
390
|
+
(response) => {
|
|
391
|
+
stopKeepalive();
|
|
392
|
+
if (res.writableEnded || res.destroyed) return;
|
|
393
|
+
if (response) {
|
|
394
|
+
res.write(`event: message\ndata: ${JSON.stringify(response)}\n\n`);
|
|
395
|
+
}
|
|
396
|
+
res.end();
|
|
397
|
+
},
|
|
398
|
+
() => {
|
|
399
|
+
stopKeepalive();
|
|
400
|
+
if (res.writableEnded || res.destroyed) return;
|
|
401
|
+
const errFrame = {
|
|
402
|
+
jsonrpc: "2.0",
|
|
403
|
+
id: rpc.id ?? null,
|
|
404
|
+
error: { code: -32603, message: "Internal error" },
|
|
405
|
+
};
|
|
406
|
+
res.write(`event: message\ndata: ${JSON.stringify(errFrame)}\n\n`);
|
|
407
|
+
res.end();
|
|
408
|
+
},
|
|
409
|
+
)
|
|
410
|
+
.finally(() => {
|
|
411
|
+
res.off("close", stopKeepalive);
|
|
412
|
+
stopKeepalive();
|
|
413
|
+
});
|
|
414
|
+
return;
|
|
415
|
+
}
|
|
416
|
+
|
|
322
417
|
void this.#handleRpc(rpc).then(
|
|
323
418
|
(response) => {
|
|
324
419
|
if (!response) {
|
|
@@ -436,18 +531,20 @@ export class AgyPiBridge {
|
|
|
436
531
|
};
|
|
437
532
|
}
|
|
438
533
|
return new Promise<BridgeCallResult>((resolve) => {
|
|
534
|
+
const timer = setTimeout(() => {
|
|
535
|
+
this.#pending.delete(id);
|
|
536
|
+
resolve({
|
|
537
|
+
content: `antigravity: pi tool "${tool}" did not return within ${Math.round(BRIDGE_CALL_TIMEOUT_MS / 1000)}s.`,
|
|
538
|
+
isError: true,
|
|
539
|
+
});
|
|
540
|
+
}, BRIDGE_CALL_TIMEOUT_MS);
|
|
541
|
+
timer.unref?.();
|
|
439
542
|
const pending: PendingCall = {
|
|
440
543
|
id,
|
|
441
544
|
tool,
|
|
442
545
|
args,
|
|
443
546
|
resolve,
|
|
444
|
-
timer
|
|
445
|
-
this.#pending.delete(id);
|
|
446
|
-
resolve({
|
|
447
|
-
content: `antigravity: pi tool "${tool}" did not return within ${Math.round(BRIDGE_CALL_TIMEOUT_MS / 1000)}s.`,
|
|
448
|
-
isError: true,
|
|
449
|
-
});
|
|
450
|
-
}, BRIDGE_CALL_TIMEOUT_MS),
|
|
547
|
+
timer,
|
|
451
548
|
};
|
|
452
549
|
this.#pending.set(id, pending);
|
|
453
550
|
});
|
package/lib/events.ts
CHANGED
package/lib/models.ts
CHANGED
|
@@ -225,25 +225,32 @@ const ZERO_PRICING: ModelPricing = {
|
|
|
225
225
|
* than inheriting an unrelated vendor's rate.
|
|
226
226
|
*/
|
|
227
227
|
export function pricingForModel(modelId: string): ModelPricing {
|
|
228
|
-
|
|
228
|
+
const baseId = modelId.replace(EFFORT_SUFFIX, "");
|
|
229
|
+
if (/^gemini-4-hydrogen$/i.test(baseId)) {
|
|
230
|
+
return { input: 1.5, output: 7.5, cacheRead: 0.075, cacheWrite: 0 };
|
|
231
|
+
}
|
|
232
|
+
if (/^gemini-4-(?:argon|carbon)$/i.test(baseId)) {
|
|
233
|
+
return { input: 2, output: 10, cacheRead: 0.1, cacheWrite: 0 };
|
|
234
|
+
}
|
|
235
|
+
if (/^gemini-3\.(?:8|7|6)-flash$/i.test(baseId)) {
|
|
229
236
|
return { input: 0.75, output: 3.75, cacheRead: 0.075, cacheWrite: 0.75 };
|
|
230
237
|
}
|
|
231
|
-
if (/^gemini-3\.5-flash$/i.test(
|
|
238
|
+
if (/^gemini-3\.5-flash$/i.test(baseId)) {
|
|
232
239
|
return { input: 1.5, output: 9, cacheRead: 0.15, cacheWrite: 1.5 };
|
|
233
240
|
}
|
|
234
|
-
if (/^gemini-3\.1-pro/i.test(
|
|
241
|
+
if (/^gemini-3\.1-pro/i.test(baseId)) {
|
|
235
242
|
return { input: 2, output: 12, cacheRead: 0.2, cacheWrite: 2 };
|
|
236
243
|
}
|
|
237
|
-
if (/^claude-sonnet-5-5/i.test(
|
|
244
|
+
if (/^claude-sonnet-5-5/i.test(baseId)) {
|
|
238
245
|
return { input: 2, output: 10, cacheRead: 0.1, cacheWrite: 2.5 };
|
|
239
246
|
}
|
|
240
|
-
if (/^claude-opus-5-5/i.test(
|
|
247
|
+
if (/^claude-opus-5-5/i.test(baseId)) {
|
|
241
248
|
return { input: 4, output: 20, cacheRead: 0.2, cacheWrite: 5 };
|
|
242
249
|
}
|
|
243
|
-
if (/^claude-sonnet-4-6/i.test(
|
|
250
|
+
if (/^claude-sonnet-4-6/i.test(baseId)) {
|
|
244
251
|
return { input: 3, output: 15, cacheRead: 0.3, cacheWrite: 3.75 };
|
|
245
252
|
}
|
|
246
|
-
if (/^claude-opus-4-6/i.test(
|
|
253
|
+
if (/^claude-opus-4-6/i.test(baseId)) {
|
|
247
254
|
return { input: 5, output: 25, cacheRead: 0.5, cacheWrite: 6.25 };
|
|
248
255
|
}
|
|
249
256
|
return { ...ZERO_PRICING };
|
|
@@ -499,6 +506,35 @@ export function formatAgyConsultLabel(
|
|
|
499
506
|
return `Consulted ${modelLabel}${effortPart}`;
|
|
500
507
|
}
|
|
501
508
|
|
|
509
|
+
const PI_COMPACTION_RESERVE_TOKENS = 16_384;
|
|
510
|
+
|
|
511
|
+
function formatCompactTokenCount(tokens: number): string {
|
|
512
|
+
return tokens >= 1_000 ? `${Math.round(tokens / 1_000)}k` : `${tokens}`;
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
/**
|
|
516
|
+
* Format a short warning suffix for `/m` autocomplete when switching to a
|
|
517
|
+
* Pi-managed model whose context window would trigger immediate compaction.
|
|
518
|
+
*/
|
|
519
|
+
export function formatConsultCompactionWarning(
|
|
520
|
+
contextTokens: number | null | undefined,
|
|
521
|
+
targetContextWindow: number | null | undefined,
|
|
522
|
+
reserveTokens = PI_COMPACTION_RESERVE_TOKENS,
|
|
523
|
+
): string {
|
|
524
|
+
if (
|
|
525
|
+
typeof contextTokens !== "number" ||
|
|
526
|
+
!Number.isFinite(contextTokens) ||
|
|
527
|
+
contextTokens <= 0 ||
|
|
528
|
+
typeof targetContextWindow !== "number" ||
|
|
529
|
+
!Number.isFinite(targetContextWindow) ||
|
|
530
|
+
targetContextWindow <= 0
|
|
531
|
+
) {
|
|
532
|
+
return "";
|
|
533
|
+
}
|
|
534
|
+
if (contextTokens <= targetContextWindow - reserveTokens) return "";
|
|
535
|
+
return ` · ⚠ will compact (${formatCompactTokenCount(contextTokens)}/${formatCompactTokenCount(targetContextWindow)})`;
|
|
536
|
+
}
|
|
537
|
+
|
|
502
538
|
export function extractAgyConsultFooter(
|
|
503
539
|
text: string,
|
|
504
540
|
models: readonly AgyModelInfo[] = ALL_FALLBACK_MODELS,
|
package/lib/pi-tools-agent.ts
CHANGED
|
@@ -28,6 +28,10 @@ export const EAGER_PI_BRIDGE_TOOLS = [
|
|
|
28
28
|
* so models retain native image viewing (`view_file`, avoiding ACP MCP image
|
|
29
29
|
* offloading), image generation, and built-in web fallback when Pi web
|
|
30
30
|
* extensions are not installed.
|
|
31
|
+
*
|
|
32
|
+
* Note: In `agy 1.5.0+`, `"view_file"` already resolves to the built-in
|
|
33
|
+
* `read_file` declaration; listing both `"read_file"` and `"view_file"` fails
|
|
34
|
+
* executor construction with a duplicate `"read_file"` tool conflict.
|
|
31
35
|
*/
|
|
32
36
|
export const PI_TOOLS_AGENT_NATIVE_TOOLS = [
|
|
33
37
|
"view_file",
|
package/lib/prompt.ts
CHANGED
|
@@ -11,9 +11,9 @@ export function piToolsAgentPrompt(serverName: string): string {
|
|
|
11
11
|
"# System Prompt",
|
|
12
12
|
"You are the agent for the current Pi coding session. Complete the user request using Pi tools.",
|
|
13
13
|
`Your tools are provided by the MCP server ${serverName}. Use the exact MCP tool names and schemas it exposes.`,
|
|
14
|
-
"
|
|
15
|
-
"Use the Pi bridge for file access, editing, commands, web access, skills, and
|
|
16
|
-
"Prefer pi__read for text and code files; for local image files (or if an MCP image result is offloaded to disk), use native view_file so the image stays directly visible in your model context.",
|
|
14
|
+
"Session instructions refer to tools by their short names (`read`, `bash`, `edit`, `write`, `grep`, `find`, `ls`, `ask_user_question`, `codemode`); map them to the `pi__*` tools exposed by this bridge (`pi__read`, `pi__bash`, `pi__edit`, `pi__write`, `pi__grep`, `pi__find`, `pi__ls`, `pi__ask_user_question`, `pi__codemode`).",
|
|
15
|
+
"Use the Pi bridge for file access, editing, commands, batching (`pi__codemode`), web access, skills, and user questionnaires (`pi__ask_user_question`). Never call native `ask_question` because headless mode auto-settles it without waiting for the user.",
|
|
16
|
+
"Prefer `pi__read` for text and code files; for local image files (or if an MCP image result is offloaded to disk), use native `read_file` or `view_file` so the image stays directly visible in your model context.",
|
|
17
17
|
"Pi background work belongs to Pi tools; use the bridged tools to inspect or manage it.",
|
|
18
18
|
].join("\n\n");
|
|
19
19
|
}
|
|
@@ -79,7 +79,7 @@ export function attachedImagesPrompt(imagePaths: readonly string[]): string {
|
|
|
79
79
|
if (imagePaths.length === 0) return "";
|
|
80
80
|
const list = imagePaths.map((filePath, idx) => `- Image ${idx + 1}: ${filePath}`).join("\n");
|
|
81
81
|
return [
|
|
82
|
-
"[Attached user image(s) saved to disk because the agy print interface is text-only — inspect them with your file-reading tool (`pi__read` or `view_file`):",
|
|
82
|
+
"[Attached user image(s) saved to disk because the agy print interface is text-only — inspect them with your file-reading tool (`pi__read`, `read_file`, or `view_file`):",
|
|
83
83
|
list,
|
|
84
84
|
"]",
|
|
85
85
|
].join("\n");
|
|
@@ -190,9 +190,18 @@ export interface PiDocsPaths {
|
|
|
190
190
|
* pi-side agent config — not agy input. Summary requests never see this
|
|
191
191
|
* block: they keep their own instructions.
|
|
192
192
|
*/
|
|
193
|
+
export const PI_BRIDGE_ROUTING_NOTES = [
|
|
194
|
+
"- Tool routing: When bridged `pi__*` MCP tools (`pi__read`, `pi__edit`, `pi__write`, `pi__bash`, `pi__grep`, `pi__find`, `pi__ls`, `pi__ask_user_question`, `pi__codemode`) are available, map short tool names in `<rules>` (`read`, `edit`, `write`, `bash`, `ask_user_question`, `codemode`) to their `pi__*` equivalents.",
|
|
195
|
+
"- Images & questions: Use `pi__read` for text/code files and native `read_file` or `view_file` for local/offloaded image files so images stay directly visible in context. Never call headless native `ask_question` (it auto-settles without waiting); use `pi__ask_user_question` when available or ask directly in Markdown.",
|
|
196
|
+
].join("\n");
|
|
197
|
+
|
|
193
198
|
export function buildAgyRelayedInstructions(piDocs: PiDocsPaths): string {
|
|
194
199
|
return [
|
|
195
200
|
...(piDocs.cwd ? [`Current working directory: ${piDocs.cwd}`, ""] : []),
|
|
201
|
+
"Session tool mode: Native Antigravity tools (`/agy-tools off`)",
|
|
202
|
+
"- Use your native Antigravity tools for file reading, editing, search, and shell commands; if `pi__activate_skill` is exposed via MCP, use it to load Pi-only skills.",
|
|
203
|
+
"- Never call headless native `ask_question` (it auto-settles without waiting); ask clarifying questions directly in Markdown and end your turn.",
|
|
204
|
+
"",
|
|
196
205
|
"Pi documentation (read only when the user asks about the harness itself, its SDK, extensions, themes, skills, or TUI):",
|
|
197
206
|
`- Main documentation: ${piDocs.readme}`,
|
|
198
207
|
`- Additional docs: ${piDocs.docs}`,
|
|
@@ -203,27 +212,28 @@ export function buildAgyRelayedInstructions(piDocs: PiDocsPaths): string {
|
|
|
203
212
|
].join("\n");
|
|
204
213
|
}
|
|
205
214
|
|
|
206
|
-
/**
|
|
215
|
+
/** Format session instructions for CLI executors that lack a separate system-prompt channel. */
|
|
207
216
|
export function piSystemInstructionsPrompt(instructions: string): string {
|
|
208
217
|
const relayed = stripPiToolInventory(instructions);
|
|
218
|
+
const hasPiRules = /<rules>[\s\S]*?<\/rules>/.test(relayed);
|
|
209
219
|
return [
|
|
210
|
-
"
|
|
211
|
-
"
|
|
212
|
-
|
|
220
|
+
"<session_instructions>",
|
|
221
|
+
"Apply the following session rules and project context for this turn (superseding any earlier `<session_instructions>` block in this conversation while keeping native system rules intact).",
|
|
222
|
+
...(hasPiRules ? [PI_BRIDGE_ROUTING_NOTES] : []),
|
|
213
223
|
relayed ||
|
|
214
|
-
"
|
|
215
|
-
"
|
|
224
|
+
"No additional session instructions are active for this turn.",
|
|
225
|
+
"</session_instructions>",
|
|
216
226
|
].join("\n\n");
|
|
217
227
|
}
|
|
218
228
|
|
|
219
229
|
/** Rehydrate a fresh agy conversation from the active branch of a pi session. */
|
|
220
230
|
export function restoredPiContextPrompt(transcript: string): string {
|
|
221
231
|
return [
|
|
222
|
-
"
|
|
223
|
-
"",
|
|
224
|
-
"This fresh agy conversation is continuing the active pi history, including any work with another provider, session resume, fork, or branch move. Treat the transcript below as prior conversation context, then answer the current user request that follows it.",
|
|
232
|
+
"<restored_session_context>",
|
|
233
|
+
"This conversation is continuing prior session history (including earlier turns, session resume, fork, or branch move). Treat the transcript below as prior conversation context, then answer the current user request that follows it.",
|
|
225
234
|
"",
|
|
226
235
|
transcript,
|
|
236
|
+
"</restored_session_context>",
|
|
227
237
|
"",
|
|
228
238
|
"## Current user request",
|
|
229
239
|
].join("\n");
|
|
@@ -756,4 +766,48 @@ export function inspectGrillResponseMarker(text: string): boolean {
|
|
|
756
766
|
return Boolean(text && text.includes(GRILL_COMPLETE_MARKER));
|
|
757
767
|
}
|
|
758
768
|
|
|
769
|
+
/**
|
|
770
|
+
* agy runs `/plan` when matched at start or after whitespace, and `/logout`
|
|
771
|
+
* or `/usage` on joined user text, instead of passing them to the model.
|
|
772
|
+
* Inserting U+200B before the `/` stops agy from intercepting them, and agy
|
|
773
|
+
* strips U+200B before the model sees the prompt. Paths and unrelated slash
|
|
774
|
+
* tokens like `/plan-x` or `/Users/...` are untouched.
|
|
775
|
+
*/
|
|
776
|
+
const AGY_INTERCEPTED_SLASH_COMMAND_RE =
|
|
777
|
+
/(^|[\s\x1c-\x1f\x85])\/(?=(?:plan|usage|logout)(?:[\s\x1c-\x1f\x85]|$))/giu;
|
|
778
|
+
|
|
779
|
+
export function neutralizeAgyInterceptedSlashCommands(text: string): string {
|
|
780
|
+
return text.replace(AGY_INTERCEPTED_SLASH_COMMAND_RE, "$1\u200B/");
|
|
781
|
+
}
|
|
782
|
+
|
|
783
|
+
export interface LateBridgeToolResultEntry {
|
|
784
|
+
toolCallId: string;
|
|
785
|
+
toolName: string;
|
|
786
|
+
content: string;
|
|
787
|
+
isError: boolean;
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
export function lateBridgeToolResultsPrompt(
|
|
791
|
+
results: readonly LateBridgeToolResultEntry[],
|
|
792
|
+
fallbackUserPrompt?: string,
|
|
793
|
+
): string {
|
|
794
|
+
const rendered = results
|
|
795
|
+
.map(
|
|
796
|
+
(r) =>
|
|
797
|
+
`<tool_result id="${r.toolCallId}" tool="${r.toolName}" status="${r.isError ? "error" : "ok"}">\n${r.content}\n</tool_result>`,
|
|
798
|
+
)
|
|
799
|
+
.join("\n\n");
|
|
800
|
+
const header = fallbackUserPrompt
|
|
801
|
+
? "Continue the user request below using the completed Pi tool result(s) that finished after the previous Antigravity prompt ended. Do not repeat completed tool actions."
|
|
802
|
+
: "Continue the current user request already given in this session using the completed Pi tool result(s) below (which finished after the previous Antigravity prompt ended). Do not repeat completed tool actions.";
|
|
803
|
+
return [
|
|
804
|
+
header,
|
|
805
|
+
`<late_tool_results>\n${rendered}\n</late_tool_results>`,
|
|
806
|
+
fallbackUserPrompt ? `# Current user request\n\n${fallbackUserPrompt}` : undefined,
|
|
807
|
+
]
|
|
808
|
+
.filter((part): part is string => Boolean(part))
|
|
809
|
+
.join("\n\n");
|
|
810
|
+
}
|
|
811
|
+
|
|
812
|
+
|
|
759
813
|
|
package/lib/reducer.ts
CHANGED
package/lib/turn.ts
CHANGED
package/package.json
CHANGED
package/src/provider.ts
CHANGED
|
@@ -68,8 +68,11 @@ import {
|
|
|
68
68
|
GOAL_INITIAL_PROMPT,
|
|
69
69
|
GRILL_COMPLETE_MARKER,
|
|
70
70
|
GRILL_DEACTIVATED_PROMPT,
|
|
71
|
+
lateBridgeToolResultsPrompt,
|
|
72
|
+
neutralizeAgyInterceptedSlashCommands,
|
|
71
73
|
omittedImagesPrompt,
|
|
72
74
|
restoredPiContextPrompt,
|
|
75
|
+
type LateBridgeToolResultEntry,
|
|
73
76
|
SWARM_CONTINUATION_PROMPT,
|
|
74
77
|
SWARM_DEACTIVATED_PROMPT,
|
|
75
78
|
SWARM_ORCHESTRATOR_PROMPT,
|
|
@@ -534,6 +537,62 @@ export function latestUserPrompt(context: TranscriptContext): { prompt: string;
|
|
|
534
537
|
return { prompt: segments.join("\n"), images };
|
|
535
538
|
}
|
|
536
539
|
|
|
540
|
+
const MAX_LATE_TOOL_RESULT_CHARS = 30_000;
|
|
541
|
+
|
|
542
|
+
function flattenToolResultContent(raw: unknown): string {
|
|
543
|
+
if (typeof raw === "string") {
|
|
544
|
+
return raw.length > MAX_LATE_TOOL_RESULT_CHARS
|
|
545
|
+
? `${raw.slice(0, MAX_LATE_TOOL_RESULT_CHARS)}\n... [truncated]`
|
|
546
|
+
: raw;
|
|
547
|
+
}
|
|
548
|
+
if (!Array.isArray(raw)) return "";
|
|
549
|
+
const parts: string[] = [];
|
|
550
|
+
for (const part of raw as Array<Record<string, unknown>>) {
|
|
551
|
+
if (part?.type === "text" && typeof part.text === "string") {
|
|
552
|
+
parts.push(part.text);
|
|
553
|
+
} else if (part?.type === "image") {
|
|
554
|
+
parts.push("[image omitted]");
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
const joined = parts.join("\n");
|
|
558
|
+
return joined.length > MAX_LATE_TOOL_RESULT_CHARS
|
|
559
|
+
? `${joined.slice(0, MAX_LATE_TOOL_RESULT_CHARS)}\n... [truncated]`
|
|
560
|
+
: joined;
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
/**
|
|
564
|
+
* When an ACP prompt ends before Pi finishes executing a bridged tool (e.g.
|
|
565
|
+
* `agy`'s internal MCP timeout), `bridge.resolveCall` cannot deliver the late
|
|
566
|
+
* `toolResult` to that finished turn. Collect the trailing `pi-bridge-*`
|
|
567
|
+
* `toolResult`s so the runtime can replay them into a continuation prompt.
|
|
568
|
+
*/
|
|
569
|
+
function extractTrailingBridgeToolResults(
|
|
570
|
+
messages: TranscriptContext["messages"],
|
|
571
|
+
afterIndex: number,
|
|
572
|
+
): LateBridgeToolResultEntry[] {
|
|
573
|
+
const trailing: LateBridgeToolResultEntry[] = [];
|
|
574
|
+
for (let i = messages.length - 1; i > afterIndex; i -= 1) {
|
|
575
|
+
const msg = messages[i] as {
|
|
576
|
+
role?: string;
|
|
577
|
+
toolCallId?: string;
|
|
578
|
+
toolName?: string;
|
|
579
|
+
content?: unknown;
|
|
580
|
+
isError?: boolean;
|
|
581
|
+
};
|
|
582
|
+
if (msg?.role !== "toolResult") break;
|
|
583
|
+
if (typeof msg.toolCallId !== "string" || !msg.toolCallId.startsWith("pi-bridge-")) {
|
|
584
|
+
return [];
|
|
585
|
+
}
|
|
586
|
+
trailing.push({
|
|
587
|
+
toolCallId: msg.toolCallId,
|
|
588
|
+
toolName: typeof msg.toolName === "string" && msg.toolName ? msg.toolName : "tool",
|
|
589
|
+
content: flattenToolResultContent(msg.content),
|
|
590
|
+
isError: msg.isError === true,
|
|
591
|
+
});
|
|
592
|
+
}
|
|
593
|
+
return trailing.reverse();
|
|
594
|
+
}
|
|
595
|
+
|
|
537
596
|
// A fresh fallback conversation can safely receive roughly 60k characters of
|
|
538
597
|
// transcript history while staying well below agy's stdin line / pipe buffer
|
|
539
598
|
// limit (~160KB-177KB). Normal reloads resume the persisted native conversation;
|
|
@@ -861,7 +920,8 @@ export function mapUsage(u: AgyUsage | undefined): AssistantMessage["usage"] {
|
|
|
861
920
|
const input = u?.input_tokens ?? 0;
|
|
862
921
|
const output = u?.output_tokens ?? 0;
|
|
863
922
|
const cacheRead = u?.cache_read_tokens ?? 0;
|
|
864
|
-
const
|
|
923
|
+
const cacheWrite = u?.cache_write_tokens ?? 0;
|
|
924
|
+
const componentTotal = input + output + cacheRead + cacheWrite;
|
|
865
925
|
return {
|
|
866
926
|
input,
|
|
867
927
|
output,
|
|
@@ -869,7 +929,7 @@ export function mapUsage(u: AgyUsage | undefined): AssistantMessage["usage"] {
|
|
|
869
929
|
// report thinking_tokens as the reasoning subset of output regardless.
|
|
870
930
|
reasoning: u?.thinking_tokens,
|
|
871
931
|
cacheRead,
|
|
872
|
-
cacheWrite
|
|
932
|
+
cacheWrite,
|
|
873
933
|
totalTokens: Math.max(u?.total_tokens ?? 0, componentTotal),
|
|
874
934
|
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
|
|
875
935
|
};
|
|
@@ -1313,7 +1373,8 @@ export function streamAntigravity(
|
|
|
1313
1373
|
const sideRequest = rawUserPrompt
|
|
1314
1374
|
? isSideConversationRequest(rawUserPrompt, systemPrompt)
|
|
1315
1375
|
: false;
|
|
1316
|
-
const
|
|
1376
|
+
const oneOffRequest = options?.cacheRetention === "none";
|
|
1377
|
+
const isolatedRequest = summaryRequest || sideRequest || oneOffRequest;
|
|
1317
1378
|
isDisposableTurn = isolatedRequest;
|
|
1318
1379
|
let prompt = rawUserPrompt;
|
|
1319
1380
|
let consultOverride: OneShotConsultOverride | undefined;
|
|
@@ -1459,6 +1520,9 @@ export function streamAntigravity(
|
|
|
1459
1520
|
hadBoostInConversation = true;
|
|
1460
1521
|
}
|
|
1461
1522
|
}
|
|
1523
|
+
if (!summaryRequest && prompt) {
|
|
1524
|
+
prompt = neutralizeAgyInterceptedSlashCommands(prompt);
|
|
1525
|
+
}
|
|
1462
1526
|
|
|
1463
1527
|
if (isolatedRequest) {
|
|
1464
1528
|
// Pi invokes compaction, branch summarization, and side conversations (/btw)
|
|
@@ -1479,15 +1543,25 @@ export function streamAntigravity(
|
|
|
1479
1543
|
const turnCwd = turnSnapshot.cwd ?? process.cwd();
|
|
1480
1544
|
|
|
1481
1545
|
let bridgeRevision: string | undefined;
|
|
1546
|
+
let resolvedBridgeCount = 0;
|
|
1482
1547
|
const processProfile: AgyProcessProfile = getProcessProfile(isolatedRequest);
|
|
1483
1548
|
if (!isolatedRequest) {
|
|
1484
1549
|
// Refresh and resolve before the driver fingerprint is evaluated.
|
|
1485
1550
|
// Re-entry into a pending bridge turn returns the existing controller,
|
|
1486
1551
|
// so a changed revision is deferred safely to the next user turn.
|
|
1487
1552
|
bridge.refreshTools();
|
|
1488
|
-
resolveBridgeResultsFromContext(bridge, context.messages);
|
|
1553
|
+
resolvedBridgeCount = resolveBridgeResultsFromContext(bridge, context.messages);
|
|
1489
1554
|
bridgeRevision = getBridgeRevision();
|
|
1490
1555
|
}
|
|
1556
|
+
const postBridgeSnapshot = !isolatedRequest
|
|
1557
|
+
? await turnRuntime.runPromise(turnService.snapshot)
|
|
1558
|
+
: turnSnapshot;
|
|
1559
|
+
const lateBridgeResults =
|
|
1560
|
+
!isolatedRequest &&
|
|
1561
|
+
resolvedBridgeCount === 0 &&
|
|
1562
|
+
!postBridgeSnapshot.hasLiveTurn
|
|
1563
|
+
? extractTrailingBridgeToolResults(context.messages, userBatch.start)
|
|
1564
|
+
: [];
|
|
1491
1565
|
const canUseAskUserQuestion =
|
|
1492
1566
|
!isolatedRequest &&
|
|
1493
1567
|
bridge.hasTool("ask_user_question") &&
|
|
@@ -1569,7 +1643,12 @@ export function streamAntigravity(
|
|
|
1569
1643
|
? MAX_ACP_SUMMARIZATION_PROMPT_CHARS
|
|
1570
1644
|
: MAX_AGY_SUMMARIZATION_PROMPT_CHARS,
|
|
1571
1645
|
)
|
|
1572
|
-
:
|
|
1646
|
+
: lateBridgeResults.length > 0
|
|
1647
|
+
? lateBridgeToolResultsPrompt(
|
|
1648
|
+
lateBridgeResults,
|
|
1649
|
+
postBridgeSnapshot.conversationId ? undefined : turnPromptWithImages,
|
|
1650
|
+
)
|
|
1651
|
+
: turnPromptWithImages;
|
|
1573
1652
|
const readOnlyPermissions =
|
|
1574
1653
|
summaryRequest ||
|
|
1575
1654
|
sideSummaryRequest ||
|
|
@@ -1625,6 +1704,13 @@ export function streamAntigravity(
|
|
|
1625
1704
|
bridgeRevision,
|
|
1626
1705
|
signal: options?.signal,
|
|
1627
1706
|
contextTokens: latestContextTokens,
|
|
1707
|
+
onTurnEnded: isolatedRequest
|
|
1708
|
+
? undefined
|
|
1709
|
+
: () => {
|
|
1710
|
+
bridge.cancelPendingCalls(
|
|
1711
|
+
"Antigravity prompt ended before Pi returned the tool result.",
|
|
1712
|
+
);
|
|
1713
|
+
},
|
|
1628
1714
|
timeoutMs: isTeamwork || isSwarm
|
|
1629
1715
|
? 43_200_000
|
|
1630
1716
|
: isBoost || isGoal || isGoalActive?.()
|
|
@@ -2415,6 +2501,7 @@ export function streamAntigravity(
|
|
|
2415
2501
|
const recovered =
|
|
2416
2502
|
!earlyTermination &&
|
|
2417
2503
|
hasResponse &&
|
|
2504
|
+
!/quota exceeded|Usage Limit Reached/i.test(activity.error ?? "") &&
|
|
2418
2505
|
!OVERFLOW_PATTERN.test(activity.error ?? "") &&
|
|
2419
2506
|
RECOVERED_INTERRUPTION_PATTERN.test(activity.error ?? "");
|
|
2420
2507
|
|