@juanbenjumea/pi-agy 0.7.14 → 0.7.15

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.
@@ -0,0 +1,115 @@
1
+ /**
2
+ * Native token usage validation, session-cumulative differencing, and
3
+ * Pi `Usage` normalization for Antigravity provider turns.
4
+ *
5
+ * Verified against live `agy --output-format stream-json`:
6
+ * - `input_tokens` excludes `cache_read_tokens`.
7
+ * - `output_tokens` includes `thinking_tokens` (matching Pi's `reasoning` subset).
8
+ * - In persistent `--input-format stream-json` mode, `result.usage` is
9
+ * cumulative across turns in the process session, so consecutive turns
10
+ * subtract the previous committed baseline to avoid double-counting.
11
+ */
12
+
13
+ export interface ValidatedAgyUsage {
14
+ input: number;
15
+ output: number;
16
+ cacheRead: number;
17
+ thinking?: number;
18
+ }
19
+
20
+ export interface NormalizedProviderUsage {
21
+ input: number;
22
+ output: number;
23
+ cacheRead: number;
24
+ cacheWrite: number;
25
+ reasoning?: number;
26
+ totalTokens: number;
27
+ }
28
+
29
+ export const ZERO_USAGE_BASELINE: Readonly<ValidatedAgyUsage> = Object.freeze({
30
+ input: 0,
31
+ output: 0,
32
+ cacheRead: 0,
33
+ thinking: 0,
34
+ });
35
+
36
+ function parseNonNegSafeInt(value: unknown): number | undefined {
37
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) {
38
+ return undefined;
39
+ }
40
+ return value === 0 ? 0 : value;
41
+ }
42
+
43
+ /**
44
+ * Validate a raw `agy` usage object without coercion, rounding, or clamping.
45
+ * Returns `undefined` when absent or when any recognized own field is invalid.
46
+ */
47
+ export function validateAgyUsage(raw: unknown): ValidatedAgyUsage | undefined {
48
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return undefined;
49
+ const record = raw as Record<string, unknown>;
50
+
51
+ if (!Object.hasOwn(record, "input_tokens") || !Object.hasOwn(record, "output_tokens")) {
52
+ return undefined;
53
+ }
54
+ const input = parseNonNegSafeInt(record.input_tokens);
55
+ const output = parseNonNegSafeInt(record.output_tokens);
56
+ if (input === undefined || output === undefined) return undefined;
57
+
58
+ let cacheRead = 0;
59
+ if (Object.hasOwn(record, "cache_read_tokens") && record.cache_read_tokens !== undefined) {
60
+ const parsed = parseNonNegSafeInt(record.cache_read_tokens);
61
+ if (parsed === undefined) return undefined;
62
+ cacheRead = parsed;
63
+ }
64
+
65
+ let thinking: number | undefined;
66
+ if (Object.hasOwn(record, "thinking_tokens") && record.thinking_tokens !== undefined) {
67
+ const parsed = parseNonNegSafeInt(record.thinking_tokens);
68
+ if (parsed === undefined) return undefined;
69
+ thinking = parsed;
70
+ }
71
+
72
+ if (Object.hasOwn(record, "total_tokens") && record.total_tokens !== undefined) {
73
+ if (parseNonNegSafeInt(record.total_tokens) === undefined) return undefined;
74
+ }
75
+
76
+ return thinking !== undefined
77
+ ? { input, output, cacheRead, thinking }
78
+ : { input, output, cacheRead };
79
+ }
80
+
81
+ /**
82
+ * Difference a cumulative session usage snapshot against a known same-generation
83
+ * baseline. Returns `undefined` on counter regression or safe-integer overflow.
84
+ */
85
+ export function diffAgyUsage(
86
+ current: ValidatedAgyUsage,
87
+ baseline: ValidatedAgyUsage,
88
+ ): NormalizedProviderUsage | undefined {
89
+ const input = current.input - baseline.input;
90
+ const output = current.output - baseline.output;
91
+ const cacheRead = current.cacheRead - baseline.cacheRead;
92
+ if (input < 0 || output < 0 || cacheRead < 0) return undefined;
93
+
94
+ let reasoning: number | undefined;
95
+ if (current.thinking !== undefined) {
96
+ const baseThinking = baseline.thinking ?? 0;
97
+ const deltaThinking = current.thinking - baseThinking;
98
+ if (deltaThinking < 0) return undefined;
99
+ if (deltaThinking <= output) {
100
+ reasoning = deltaThinking === 0 ? 0 : deltaThinking;
101
+ }
102
+ }
103
+
104
+ const totalTokens = input + output + cacheRead;
105
+ if (!Number.isSafeInteger(totalTokens)) return undefined;
106
+
107
+ return {
108
+ input: input === 0 ? 0 : input,
109
+ output: output === 0 ? 0 : output,
110
+ cacheRead: cacheRead === 0 ? 0 : cacheRead,
111
+ cacheWrite: 0,
112
+ ...(reasoning !== undefined ? { reasoning } : {}),
113
+ totalTokens: totalTokens === 0 ? 0 : totalTokens,
114
+ };
115
+ }
@@ -2,12 +2,13 @@
2
2
  * Antigravity provider turn runtime (`antigravity/*` models in `/model`).
3
3
  *
4
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 into Pi's TUI, and agy's tool activity appears as thinking events
7
- * (`[agy tool: …]`). By default, a loopback MCP bridge parks agy's Pi-tool
8
- * calls for execution by Pi, so its normal permissions, approvals, and diff
9
- * review apply. The bridge is separate from agy's own tools and can be disabled
10
- * with `providerBridge: false`.
5
+ * provider-driver.ts) with full transcript rendering on cold start and delta
6
+ * prompts on synced resumed conversations. Response text and real model
7
+ * thinking stream into Pi's TUI, while agy step/tool progress routes to Pi's
8
+ * live status bar. By default, a loopback MCP bridge parks agy's Pi-tool
9
+ * calls (micro-batched for parallel calls) for execution by Pi, so its normal
10
+ * permissions, approvals, and diff review apply. The bridge is separate from
11
+ * agy's own tools and can be disabled with `providerBridge: false`.
11
12
  */
12
13
 
13
14
  import { randomBytes } from "node:crypto";
@@ -22,9 +23,11 @@ import {
22
23
  collectImageBlocks,
23
24
  ensureImageStagingRoot,
24
25
  getLiveImageStagingCount,
26
+ renderProviderDeltaPrompt,
25
27
  renderProviderPrompt,
26
28
  stageImages,
27
29
  textOfContent,
30
+ transcriptFingerprint,
28
31
  type ProviderTranscriptMessage,
29
32
  } from "./provider-prompt.js";
30
33
  export {
@@ -32,12 +35,15 @@ export {
32
35
  collectImageBlocks,
33
36
  ensureImageStagingRoot,
34
37
  imageExtension,
38
+ renderProviderDeltaPrompt,
35
39
  renderProviderPrompt,
36
40
  stageImages,
41
+ transcriptFingerprint,
37
42
  MAX_IMAGE_BYTES,
38
43
  MAX_STAGED_IMAGES,
39
44
  type PromptImageBlock,
40
45
  type ProviderTranscriptMessage,
46
+ type RenderProviderPromptOptions,
41
47
  type StagedImages,
42
48
  } from "./provider-prompt.js";
43
49
 
@@ -46,6 +52,14 @@ import type { McpBridgeHandle } from "./provider-mcp.js";
46
52
  import type { BridgeToolDef } from "./provider-tools.js";
47
53
  import { getSession, saveSession } from "./sessions.js";
48
54
  import { AgyProviderDriver, PROVIDER_TURN_TIMEOUT_MS } from "./provider-driver.js";
55
+ import type { NormalizedProviderUsage } from "./provider-usage.js";
56
+ export {
57
+ diffAgyUsage,
58
+ validateAgyUsage,
59
+ ZERO_USAGE_BASELINE,
60
+ type NormalizedProviderUsage,
61
+ type ValidatedAgyUsage,
62
+ } from "./provider-usage.js";
49
63
  import {
50
64
  toProviderEffort,
51
65
  validateAgyModelId,
@@ -64,9 +78,31 @@ export const AGY_PROVIDER_API = "agy-provider";
64
78
 
65
79
  export interface ProviderTurnCallbacks {
66
80
  onText?: (delta: string) => void;
81
+ onThinking?: (delta: string) => void;
67
82
  onActivity?: (label: string) => void;
68
83
  }
69
84
 
85
+ /**
86
+ * Build session-only `agy --settings` JSON that denies agy's built-in shell
87
+ * and file-write tools when Pi already bridges their equivalents via MCP,
88
+ * preventing built-in tools from shadowing Pi's native approvals and diffs.
89
+ * Intentionally emits only `deny` rules (no blanket `allow`) so other MCP
90
+ * servers keep the user's configured permission policy.
91
+ */
92
+ export function buildBridgeSettings(bridgedTools: readonly BridgeToolDef[]): string | undefined {
93
+ if (bridgedTools.length === 0) return undefined;
94
+ const names = new Set(bridgedTools.map((tool) => tool.piName.toLowerCase()));
95
+ const deny: string[] = [];
96
+ if (names.has("bash") || names.has("shell") || names.has("run_command")) {
97
+ deny.push("command(*)");
98
+ }
99
+ if (names.has("write") || names.has("edit") || names.has("write_file") || names.has("edit_file")) {
100
+ deny.push("write_file(*)");
101
+ }
102
+ if (deny.length === 0) return undefined;
103
+ return JSON.stringify({ permissions: { deny } });
104
+ }
105
+
70
106
  export interface ProviderTurnRequest {
71
107
  /** Exact agy `--model` value (base or qualified slug). */
72
108
  fullModel: string;
@@ -99,7 +135,7 @@ export interface ProviderTurnOwnership {
99
135
 
100
136
  export type ProviderRunEnd =
101
137
  | { kind: "done"; result: ProviderTurnResult }
102
- | { kind: "parked"; park: ProviderToolPark; ownership?: ProviderTurnOwnership };
138
+ | { kind: "parked"; park: ProviderToolPark; parks?: ProviderToolPark[]; ownership?: ProviderTurnOwnership };
103
139
 
104
140
  export interface ProviderToolDelivery {
105
141
  callId: string;
@@ -134,6 +170,8 @@ export interface ProviderTurnResult {
134
170
  /** Bounded agy tool-activity labels observed during the turn. */
135
171
  activity: string[];
136
172
  deniedActions?: Array<{ action?: string; display_name?: string }>;
173
+ /** Validated per-turn native usage delta, when available. */
174
+ usage?: NormalizedProviderUsage;
137
175
  }
138
176
 
139
177
  /**
@@ -212,10 +250,12 @@ export function getProviderRunner(dir: string): ProviderTurnRunner {
212
250
  dir: request.dir, fullModel: request.fullModel, effort: request.effort,
213
251
  skipPermissions: request.skipPermissions, bridgeDir: bridge?.configDir,
214
252
  bridgeTools: bridge ? fingerprint : undefined, imageRoot,
253
+ settingsJson: bridge ? buildBridgeSettings(request.bridgedTools) : undefined,
215
254
  }, {
216
255
  prompt: request.prompt, resumeConversationId: request.resumeConversationId,
217
256
  signal: request.signal, timeoutMs: remaining,
218
- onText: request.callbacks?.onText, onActivity: request.callbacks?.onActivity,
257
+ onText: request.callbacks?.onText, onThinking: request.callbacks?.onThinking,
258
+ onActivity: request.callbacks?.onActivity,
219
259
  });
220
260
  return finishPhase(owned, end);
221
261
  } catch (error) {
@@ -241,7 +281,8 @@ export function getProviderRunner(dir: string): ProviderTurnRunner {
241
281
  }
242
282
  const end = await driver.continueTurn({
243
283
  signal: resumeSignal, timeoutMs: resumeTimeoutMs,
244
- onText: callbacks?.onText, onActivity: callbacks?.onActivity,
284
+ onText: callbacks?.onText, onThinking: callbacks?.onThinking,
285
+ onActivity: callbacks?.onActivity,
245
286
  });
246
287
  return finishPhase(owned, end);
247
288
  } catch (error) {
@@ -261,9 +302,22 @@ export function getProviderRunner(dir: string): ProviderTurnRunner {
261
302
  return runner;
262
303
  }
263
304
 
264
- function toRunEnd(end: { kind: "done"; outcome: ProviderTurnResult } | { kind: "parked"; park: { callId: string; toolName: string; args: Record<string, unknown> } }): ProviderRunEnd {
305
+ function toRunEnd(
306
+ end:
307
+ | { kind: "done"; outcome: ProviderTurnResult }
308
+ | {
309
+ kind: "parked";
310
+ park: { callId: string; toolName: string; args: Record<string, unknown> };
311
+ parks?: Array<{ callId: string; toolName: string; args: Record<string, unknown> }>;
312
+ },
313
+ ): ProviderRunEnd {
265
314
  if (end.kind === "parked") {
266
- return { kind: "parked", park: { callId: end.park.callId, toolName: end.park.toolName, args: end.park.args } };
315
+ const parks = (end.parks && end.parks.length > 0 ? end.parks : [end.park]).map((park) => ({
316
+ callId: park.callId,
317
+ toolName: park.toolName,
318
+ args: park.args,
319
+ }));
320
+ return { kind: "parked", park: parks[0], parks };
267
321
  }
268
322
  return { kind: "done", result: end.outcome };
269
323
  }
@@ -377,7 +431,9 @@ export function getProviderStatus(dir: string): ProviderStatus {
377
431
  const suspended: ProviderStatusSuspended[] = [];
378
432
  for (const [suspendedDir, entry] of suspendedByDir) {
379
433
  if (suspendedDir === key) {
380
- suspended.push({ toolCallId: entry.toolCallId, toolName: entry.park.toolName, modelId: entry.modelId });
434
+ for (const call of entry.calls) {
435
+ suspended.push({ toolCallId: call.toolCallId, toolName: call.park.toolName, modelId: entry.modelId });
436
+ }
381
437
  }
382
438
  }
383
439
  try {
@@ -425,6 +481,8 @@ export interface AgyProviderStreamDeps {
425
481
  timeoutMs?: number;
426
482
  /** Pi tools to bridge into agy turns (projected per turn by the caller). */
427
483
  tools?: ProviderToolSource[];
484
+ /** Live status callback for agy step/tool progress (undefined clears status). */
485
+ onActivity?: (label: string | undefined) => void;
428
486
  }
429
487
 
430
488
  export interface AgyStreamSimpleModel {
@@ -521,18 +579,35 @@ function hasUserMessageAfterToolCall(messages: ProviderTranscriptMessage[], tool
521
579
  return false;
522
580
  }
523
581
 
582
+ interface SuspendedToolCall {
583
+ toolCallId: string;
584
+ park: ProviderToolPark;
585
+ }
586
+
524
587
  interface SuspendedTurn {
525
588
  /** Original executed selector, retained across reasoning/catalog changes and re-parks. */
526
589
  rawModelId: AgyModelId;
527
590
  runner: ProviderTurnRunner;
528
591
  ownership?: ProviderTurnOwnership;
529
- toolCallId: string;
530
- park: ProviderToolPark;
592
+ calls: SuspendedToolCall[];
531
593
  modelId: string;
594
+ /** System prompt actually sent on the originating turn, preserved for delta sync. */
595
+ systemPrompt: string;
596
+ /** Bridged tool catalog fingerprint sent on the originating turn. */
597
+ bridgeToolsKey: string;
532
598
  /** Image staging cleanups owned by the suspended turn. */
533
599
  imageCleanups: Array<() => Promise<void>>;
534
600
  }
535
601
 
602
+ interface ConversationSyncState {
603
+ conversationId: string;
604
+ systemPrompt: string;
605
+ bridgeToolsKey: string;
606
+ syncedInputCount: number;
607
+ syncedInputFingerprint: string;
608
+ syncedAssistantFingerprint: string;
609
+ }
610
+
536
611
  /** Run cleanups sequentially, never throwing. */
537
612
  async function runImageCleanups(cleanups: Array<() => Promise<void>>): Promise<void> {
538
613
  for (const cleanup of cleanups) {
@@ -576,6 +651,7 @@ export function createAgyStreamSimple(
576
651
  options?: AgyStreamSimpleOptions,
577
652
  ) => AgyEventStream {
578
653
  const resumeByModel = new Map<string, string>();
654
+ const syncByModel = new Map<string, ConversationSyncState>();
579
655
  const getRunner = (dir: string): ProviderTurnRunner => deps.runner ?? getProviderRunner(dir);
580
656
 
581
657
  return (model, messages, options) => {
@@ -591,6 +667,7 @@ export function createAgyStreamSimple(
591
667
  output: number;
592
668
  cacheRead: number;
593
669
  cacheWrite: number;
670
+ reasoning?: number;
594
671
  totalTokens: number;
595
672
  cost: { input: number; output: number; cacheRead: number; cacheWrite: number; total: number };
596
673
  };
@@ -634,6 +711,13 @@ export function createAgyStreamSimple(
634
711
  // park transfers ownership into the suspension entry. Declared here
635
712
  // so both the try body and the catch below can clean it.
636
713
  const pendingImageCleanups: Array<() => Promise<void>> = [];
714
+ const setActivityStatus = (label: string | undefined): void => {
715
+ try {
716
+ deps.onActivity?.(label);
717
+ } catch {
718
+ // Live status surfaces must never disrupt a turn.
719
+ }
720
+ };
637
721
 
638
722
  try {
639
723
  const systemPrompt = factory.getSystemPrompt(messages);
@@ -642,68 +726,87 @@ export function createAgyStreamSimple(
642
726
  // conversation instead of inheriting stale context.
643
727
  const hasPriorAssistantTurn = messages.some((message) => message.role === "assistant");
644
728
 
645
- let textIndex = -1;
646
- let thinkingIndex = -1;
647
- const ensureText = (): number => {
648
- if (textIndex === -1) {
649
- output.content.push({ type: "text", text: "" });
650
- textIndex = output.content.length - 1;
651
- stream.push({ type: "text_start", contentIndex: textIndex, partial: output });
652
- }
653
- return textIndex;
654
- };
655
- const ensureThinking = (): number => {
656
- if (thinkingIndex === -1) {
657
- output.content.push({ type: "thinking", thinking: "" });
658
- thinkingIndex = output.content.length - 1;
659
- stream.push({ type: "thinking_start", contentIndex: thinkingIndex, partial: output });
660
- }
661
- return thinkingIndex;
662
- };
729
+ let textIndex = -1;
730
+ let thinkingIndex = -1;
731
+ const ensureText = (): number => {
732
+ if (textIndex === -1) {
733
+ output.content.push({ type: "text", text: "" });
734
+ textIndex = output.content.length - 1;
735
+ stream.push({ type: "text_start", contentIndex: textIndex, partial: output });
736
+ }
737
+ return textIndex;
738
+ };
739
+ const ensureThinking = (): number => {
740
+ if (thinkingIndex === -1) {
741
+ output.content.push({ type: "thinking", thinking: "" });
742
+ thinkingIndex = output.content.length - 1;
743
+ stream.push({ type: "thinking_start", contentIndex: thinkingIndex, partial: output });
744
+ }
745
+ return thinkingIndex;
746
+ };
663
747
 
664
748
  const callbacks: ProviderTurnCallbacks = {
665
749
  onText: (delta) => {
666
750
  const index = ensureText();
667
751
  const block = output.content[index] as { text: string };
668
752
  block.text += delta;
669
- output.usage.output += delta.length;
670
753
  stream.push({ type: "text_delta", contentIndex: index, delta, partial: output });
671
754
  },
672
- onActivity: (label) => {
755
+ onThinking: (delta) => {
673
756
  const index = ensureThinking();
674
757
  const block = output.content[index] as { thinking: string };
675
- block.thinking += (block.thinking ? "\n" : "") + label;
676
- stream.push({ type: "thinking_delta", contentIndex: index, delta: label, partial: output });
758
+ block.thinking += delta;
759
+ stream.push({ type: "thinking_delta", contentIndex: index, delta, partial: output });
760
+ },
761
+ onActivity: (label) => {
762
+ setActivityStatus(label);
677
763
  },
678
764
  };
679
765
 
680
766
  const runner = getRunner(dir);
681
767
  const skey = path.resolve(dir);
682
768
  const prior = suspendedByDir.get(skey);
683
- const bodies = prior ? collectParkedDeliveries(messages, prior.toolCallId) : [];
769
+ const deliveredByCall = prior
770
+ ? prior.calls.map((call) => ({
771
+ call,
772
+ bodies: collectParkedDeliveries(messages, call.toolCallId),
773
+ }))
774
+ : [];
775
+ const hasCompleteDelivery =
776
+ !!prior &&
777
+ deliveredByCall.length > 0 &&
778
+ deliveredByCall.every((entry) => entry.bodies.length > 0);
684
779
  let end: ProviderRunEnd;
685
780
  let executedRawModelId: AgyModelId;
686
- if (prior && bodies.length > 0) {
781
+ let activeSystemPrompt = systemPrompt;
782
+ let activeBridgeToolsKey = "";
783
+ if (prior && hasCompleteDelivery) {
687
784
  executedRawModelId = prior.rawModelId;
785
+ activeSystemPrompt = prior.systemPrompt;
786
+ activeBridgeToolsKey = prior.bridgeToolsKey;
688
787
  prior.ownership?.assertValid();
689
788
  suspendedByDir.delete(skey);
690
- // Images riding on the delivered tool results are staged too:
691
- // the resumed agy turn reads them by path. Owned by this
692
- // invocation; cleaned on its terminal settle below.
693
- const deliveryImages = await stageImages(collectImageBlocks(messages, prior.toolCallId));
694
- const resumeCleanups = [...prior.imageCleanups, deliveryImages.cleanup];
695
- const imageRefs = [...deliveryImages.paths.values()];
789
+ const resumeCleanups = [...prior.imageCleanups];
696
790
  // Deliver by bridge park id (what agy waits on), matched via the
697
- // shadow toolCall id (what Pi's transcript carries).
698
- const deliveries: ProviderToolDelivery[] = bodies.map((body) => ({
699
- callId: prior.park.callId,
700
- text:
701
- body.text +
702
- (imageRefs.length > 0
703
- ? `\n[attached images saved at: ${imageRefs.join(", ")} — open them with your file tools to view]`
704
- : ""),
705
- isError: body.isError,
706
- }));
791
+ // shadow toolCall id (what Pi's transcript carries). Images riding
792
+ // on each delivered tool result are staged per tool call.
793
+ const deliveries: ProviderToolDelivery[] = [];
794
+ for (const { call, bodies } of deliveredByCall) {
795
+ const deliveryImages = await stageImages(collectImageBlocks(messages, call.toolCallId));
796
+ resumeCleanups.push(deliveryImages.cleanup);
797
+ const imageRefs = [...deliveryImages.paths.values()];
798
+ for (const body of bodies) {
799
+ deliveries.push({
800
+ callId: call.park.callId,
801
+ text:
802
+ body.text +
803
+ (imageRefs.length > 0
804
+ ? `\n[attached images saved at: ${imageRefs.join(", ")} — open them with your file tools to view]`
805
+ : ""),
806
+ isError: body.isError,
807
+ });
808
+ }
809
+ }
707
810
  try {
708
811
  end = await runner.resume(
709
812
  deliveries,
@@ -726,7 +829,7 @@ export function createAgyStreamSimple(
726
829
  // park carries it into the suspension, terminal settle cleans it.
727
830
  pendingImageCleanups.push(...resumeCleanups);
728
831
  } else {
729
- if (prior && hasUserMessageAfterToolCall(messages, prior.toolCallId)) {
832
+ if (prior && prior.calls.some((call) => hasUserMessageAfterToolCall(messages, call.toolCallId))) {
730
833
  // Our own transcript moved on without delivering (abort, reject,
731
834
  // retry): cancel the stale suspension and start fresh instead
732
835
  // of bricking the directory behind the suspended guard.
@@ -749,13 +852,35 @@ export function createAgyStreamSimple(
749
852
  // Session-store failures must never block a turn.
750
853
  }
751
854
  }
752
- // Materialize attached images as files agy's tools can open;
753
- // paths render inline, failures degrade to omitted notes. Held
754
- // for the driver turn: terminal settle below cleans it, a park
755
- // carries it into the suspension.
756
- const staged = await stageImages(collectImageBlocks(messages));
757
- pendingImageCleanups.push(staged.cleanup);
758
- const prompt = renderProviderPrompt(messages, systemPrompt || undefined, staged.paths);
855
+ const bridgedTools = projectBridgeTools(options?.tools ?? deps.tools ?? []);
856
+ activeBridgeToolsKey = bridgeToolsFingerprint(bridgedTools);
857
+ const sync = resume ? syncByModel.get(model.id) : undefined;
858
+ const canDelta =
859
+ !!sync &&
860
+ sync.conversationId === resume &&
861
+ sync.systemPrompt === systemPrompt &&
862
+ sync.bridgeToolsKey === activeBridgeToolsKey &&
863
+ messages.length > sync.syncedInputCount + 1 &&
864
+ messages[sync.syncedInputCount]?.role === "assistant" &&
865
+ transcriptFingerprint(messages.slice(0, sync.syncedInputCount)) === sync.syncedInputFingerprint &&
866
+ transcriptFingerprint([messages[sync.syncedInputCount]]) === sync.syncedAssistantFingerprint;
867
+ let prompt: string;
868
+ if (canDelta) {
869
+ const deltaMessages = messages.slice(sync.syncedInputCount + 1);
870
+ const staged = await stageImages(collectImageBlocks(deltaMessages));
871
+ pendingImageCleanups.push(staged.cleanup);
872
+ prompt = renderProviderDeltaPrompt(deltaMessages, staged.paths);
873
+ } else {
874
+ // Materialize attached images as files agy's tools can open;
875
+ // paths render inline, failures degrade to omitted notes. Held
876
+ // for the driver turn: terminal settle below cleans it, a park
877
+ // carries it into the suspension.
878
+ const staged = await stageImages(collectImageBlocks(messages));
879
+ pendingImageCleanups.push(staged.cleanup);
880
+ prompt = renderProviderPrompt(messages, systemPrompt || undefined, staged.paths, {
881
+ bridgedToolNames: bridgedTools.map((tool) => tool.name),
882
+ });
883
+ }
759
884
  // Capture before execution: later invocations can resolve a different
760
885
  // profile while this child remains parked on its original target.
761
886
  executedRawModelId = validateAgyModelId(
@@ -770,16 +895,17 @@ export function createAgyStreamSimple(
770
895
  timeoutMs: deps.timeoutMs ?? PROVIDER_TURN_TIMEOUT_MS,
771
896
  resumeConversationId: resume,
772
897
  skipPermissions: deps.skipPermissions ?? true,
773
- bridgedTools: projectBridgeTools(options?.tools ?? deps.tools ?? []),
898
+ bridgedTools,
774
899
  callbacks,
775
900
  });
776
901
  }
777
902
 
778
903
  if (end.kind === "parked") {
779
- // A bridged Pi tool call: end any open blocks, then emit a REAL
780
- // shadow toolCall so Pi executes it with normal permissions,
781
- // approvals, and review. The Pi turn delivering the matching
782
- // toolResult resumes this driver turn.
904
+ setActivityStatus(undefined);
905
+ // Bridged Pi tool call(s): end any open blocks, then emit REAL
906
+ // shadow toolCall blocks so Pi executes them with normal
907
+ // permissions, approvals, and review. The Pi turn delivering the
908
+ // matching toolResults resumes this driver turn.
783
909
  if (thinkingIndex !== -1) {
784
910
  const thinking = (output.content[thinkingIndex] as { thinking: string }).thinking;
785
911
  stream.push({ type: "thinking_end", contentIndex: thinkingIndex, content: thinking, partial: output });
@@ -788,23 +914,41 @@ export function createAgyStreamSimple(
788
914
  const text = (output.content[textIndex] as { text: string }).text;
789
915
  stream.push({ type: "text_end", contentIndex: textIndex, content: text, partial: output });
790
916
  }
791
- const toolCallId = `agybridge-${randomBytes(8).toString("hex")}`;
792
- const toolCall = {
793
- type: "toolCall",
794
- id: toolCallId,
795
- name: end.park.toolName,
796
- arguments: end.park.args,
797
- };
917
+ const parks = end.parks && end.parks.length > 0 ? end.parks : [end.park];
918
+ const calls: SuspendedToolCall[] = [];
919
+ const toolCalls: Array<{
920
+ type: "toolCall";
921
+ id: string;
922
+ name: string;
923
+ arguments: Record<string, unknown>;
924
+ }> = [];
925
+ for (const park of parks) {
926
+ const toolCallId = `agybridge-${randomBytes(8).toString("hex")}`;
927
+ calls.push({ toolCallId, park });
928
+ toolCalls.push({
929
+ type: "toolCall",
930
+ id: toolCallId,
931
+ name: park.toolName,
932
+ arguments: park.args,
933
+ });
934
+ }
798
935
  end.ownership?.assertValid();
799
936
  suspendedByDir.set(skey, {
800
- runner, ownership: end.ownership, toolCallId, park: end.park,
937
+ runner,
938
+ ownership: end.ownership,
939
+ calls,
801
940
  rawModelId: executedRawModelId,
802
- modelId: model.id, imageCleanups: pendingImageCleanups,
941
+ modelId: model.id,
942
+ systemPrompt: activeSystemPrompt,
943
+ bridgeToolsKey: activeBridgeToolsKey,
944
+ imageCleanups: pendingImageCleanups,
803
945
  });
804
- output.content.push(toolCall);
805
- const toolIndex = output.content.length - 1;
806
- stream.push({ type: "toolcall_start", contentIndex: toolIndex, partial: output });
807
- stream.push({ type: "toolcall_end", contentIndex: toolIndex, toolCall, partial: output });
946
+ for (const toolCall of toolCalls) {
947
+ output.content.push(toolCall);
948
+ const toolIndex = output.content.length - 1;
949
+ stream.push({ type: "toolcall_start", contentIndex: toolIndex, partial: output });
950
+ stream.push({ type: "toolcall_end", contentIndex: toolIndex, toolCall, partial: output });
951
+ }
808
952
  output.usage.totalTokens =
809
953
  output.usage.input + output.usage.output + output.usage.cacheRead + output.usage.cacheWrite;
810
954
  output.stopReason = "toolUse";
@@ -813,6 +957,7 @@ export function createAgyStreamSimple(
813
957
  return;
814
958
  }
815
959
  const result = end.result;
960
+ setActivityStatus(undefined);
816
961
 
817
962
  if (thinkingIndex !== -1) {
818
963
  const thinking = (output.content[thinkingIndex] as { thinking: string }).thinking;
@@ -833,7 +978,19 @@ export function createAgyStreamSimple(
833
978
  block.text = finalText;
834
979
  stream.push({ type: "text_end", contentIndex: index, content: finalText, partial: output });
835
980
 
836
- output.usage.totalTokens = output.usage.input + output.usage.output + output.usage.cacheRead + output.usage.cacheWrite;
981
+ if (result.usage) {
982
+ output.usage.input = result.usage.input;
983
+ output.usage.output = result.usage.output;
984
+ output.usage.cacheRead = result.usage.cacheRead;
985
+ output.usage.cacheWrite = result.usage.cacheWrite;
986
+ if (result.usage.reasoning !== undefined) {
987
+ output.usage.reasoning = result.usage.reasoning;
988
+ }
989
+ output.usage.totalTokens = result.usage.totalTokens;
990
+ } else {
991
+ output.usage.totalTokens =
992
+ output.usage.input + output.usage.output + output.usage.cacheRead + output.usage.cacheWrite;
993
+ }
837
994
  // Partial turns must never masquerade as clean stops: surface the
838
995
  // real terminal state so Pi retries or reports instead of accepting
839
996
  // truncated text as a complete answer.
@@ -842,6 +999,18 @@ export function createAgyStreamSimple(
842
999
  else output.stopReason = "stop";
843
1000
  if (result.conversationId) {
844
1001
  resumeByModel.set(model.id, result.conversationId);
1002
+ if (!result.aborted && !result.timedOut) {
1003
+ syncByModel.set(model.id, {
1004
+ conversationId: result.conversationId,
1005
+ systemPrompt: activeSystemPrompt,
1006
+ bridgeToolsKey: activeBridgeToolsKey,
1007
+ syncedInputCount: messages.length,
1008
+ syncedInputFingerprint: transcriptFingerprint(messages),
1009
+ syncedAssistantFingerprint: transcriptFingerprint([output]),
1010
+ });
1011
+ } else {
1012
+ syncByModel.delete(model.id);
1013
+ }
845
1014
  const latestUser = [...messages].reverse().find((message) => message.role === "user");
846
1015
  const summary = textOfContent(latestUser?.content).trim().slice(0, 80) || undefined;
847
1016
  try {
@@ -860,6 +1029,8 @@ export function createAgyStreamSimple(
860
1029
  stream.end();
861
1030
  await runImageCleanups(pendingImageCleanups);
862
1031
  } catch (error) {
1032
+ syncByModel.delete(model.id);
1033
+ setActivityStatus(undefined);
863
1034
  output.stopReason = signal.aborted ? "aborted" : "error";
864
1035
  output.errorMessage = error instanceof Error ? error.message : String(error);
865
1036
  stream.push({ type: "error", reason: output.stopReason, error: output });