@estebanforge/pi-antigravity-bridge 1.17.1 → 1.18.0

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/src/provider.ts CHANGED
@@ -38,6 +38,7 @@ import { looksBackgroundNativeCall } from "./background-watch.js";
38
38
  import { SubagentRoster } from "./subagent-roster.js";
39
39
  import { clampOverflowUsage, toPiUsage } from "./stream-events.js";
40
40
  import { mapAgyToolToNative } from "./native-tools.js";
41
+ import { ACP_MUTATING_TOOLS } from "./native-fileops.js";
41
42
  import { toAgyEffort, type AgyModelEntry } from "./models.js";
42
43
  import { AcpHistorySync, OutboundFrameBudgetError } from "./acp/history-sync.js";
43
44
  import { SessionStore } from "./sessions.js";
@@ -276,11 +277,16 @@ export function buildFullPrompt(
276
277
  systemPrompt: string | undefined,
277
278
  digest: string,
278
279
  prompt: string,
279
- options?: { codemodeOnly?: boolean; acpToolsDirect?: boolean },
280
+ options?: { codemodeOnly?: boolean; acpToolsDirect?: boolean; lean?: boolean },
280
281
  ): string {
281
282
  const parts: string[] = [];
282
283
  if (systemPrompt) {
283
- parts.push(`${SYSTEM_PROMPT_PREAMBLE}\n\n${systemPrompt}\n\n${toolNotes(options)}\n\n${SYSTEM_PROMPT_END}`);
284
+ const notes = toolNotes(options);
285
+ parts.push(
286
+ notes.length > 0
287
+ ? `${SYSTEM_PROMPT_PREAMBLE}\n\n${systemPrompt}\n\n${notes}\n\n${SYSTEM_PROMPT_END}`
288
+ : `${SYSTEM_PROMPT_PREAMBLE}\n\n${systemPrompt}\n\n${SYSTEM_PROMPT_END}`,
289
+ );
284
290
  }
285
291
  if (digest) {
286
292
  parts.push(`${DIGEST_PREAMBLE}\n\n${digest}`);
@@ -292,8 +298,11 @@ export function buildFullPrompt(
292
298
  }
293
299
 
294
300
  /** Shared note composition for the system prompt block and the stream-json
295
- * staged agent file (which concatenates the notes without buildFullPrompt). */
296
- function toolNotes(options?: { codemodeOnly?: boolean; acpToolsDirect?: boolean }): string {
301
+ * staged agent file (which concatenates the notes without buildFullPrompt).
302
+ * Lean sessions ship NO notes: every note asserts a typed per-tool surface
303
+ * a lean agent never has; the staged lean agent body is the protocol. */
304
+ function toolNotes(options?: { codemodeOnly?: boolean; acpToolsDirect?: boolean; lean?: boolean }): string {
305
+ if (options?.lean) return "";
297
306
  const parts = [TOOL_PRIORITY_NOTE];
298
307
  if (options?.acpToolsDirect) parts.push(ACP_TOOL_NOTE);
299
308
  if (options?.codemodeOnly) parts.push(CODEMODE_NOTE);
@@ -624,13 +633,16 @@ export function sessionKey(
624
633
  options: SimpleStreamOptions | undefined,
625
634
  cwd: string,
626
635
  engine: "stream-json" | "acp",
636
+ lean = false,
627
637
  ): string {
628
638
  const sid = (options as { sessionId?: string } | undefined)?.sessionId;
629
639
  const base = sid && sid.length > 0 ? `sid:${sid}` : `cwd:${cwd}`;
630
640
  // Engine-scoped keys (plan 9.4): one ACP turn must never touch the stream
631
641
  // binding and vice versa. Un-suffixed keys = stream-json, byte-compatible with
632
- // every store that predates the ACP engine.
633
- return base + (engine === "acp" ? "@acp" : "");
642
+ // every store that predates the ACP engine. The lean marker scopes agent
643
+ // modes apart the same way: a lean flip restarts into a fresh conversation
644
+ // instead of resuming history recorded under the other agent file.
645
+ return base + (engine === "acp" ? "@acp" : "") + (lean ? "@lean" : "");
634
646
  }
635
647
 
636
648
  /** Rotate the bound agy conversation after pi compacts the session.
@@ -669,6 +681,9 @@ export interface NativeDisplayEvent {
669
681
  * extension resolve the polled pi tool via the escalation registry. */
670
682
  callId?: string;
671
683
  path?: string;
684
+ /** Search target of a search-class native call (grep pattern, web
685
+ * query); read and command calls leave it undefined. */
686
+ query?: string;
672
687
  command?: string;
673
688
  output?: string;
674
689
  diff?: string;
@@ -697,6 +712,8 @@ export interface StreamSimpleDeps {
697
712
  * read decides (tests); production wiring always passes it so a
698
713
  * mid-session config flip cannot move one side of a parked turn. */
699
714
  engine?: "stream-json" | "acp";
715
+ /** Lean agent mode, latched at extension load (see DriverDeps). */
716
+ leanAgent?: boolean;
700
717
  /** Output-only ACP tool events; persisted as TUI entries, never sent to
701
718
  * Antigravity or dispatched through Pi's executable tools. */
702
719
  onNativeEvent?: (event: NativeDisplayEvent) => void;
@@ -1590,6 +1607,11 @@ export interface DriverDeps {
1590
1607
  pendingCompactionHandoff?: Set<string>;
1591
1608
  /** Active engine (config), for engine-scoped session keys. */
1592
1609
  engine: "stream-json" | "acp";
1610
+ /** Lean agent mode, LATCHED at provider construction: the spawned process
1611
+ * only sees the flag at spawn, so notes/catalog/session keys must follow
1612
+ * the latched value, not a live config read (a mid-session flip is
1613
+ * restart-applies). */
1614
+ leanAgent?: boolean;
1593
1615
  /** Live pi-side tool visibility (see StreamSimpleDeps). */
1594
1616
  hasActiveTool?: (name: string) => boolean;
1595
1617
  /** Per-provider handoff runtime (see StreamSimpleDeps). */
@@ -1645,11 +1667,14 @@ function emitToolUse(
1645
1667
  stream.end();
1646
1668
  }
1647
1669
 
1648
- /** ACP edit-class tool names that carry a file-path arg and land the file on
1649
- * disk (observed live: edit_file, create_file, write_file on agy 1.5.11).
1650
- * Read/execute tools also match the arg-shape heuristic but produce no diff
1651
- * (unchanged content), so the gate avoids mislabeling them as edits. */
1652
- const ACP_EDIT_TOOLS = new Set(["edit_file", "create_file", "write_to_file", "write_file"]);
1670
+ /** ACP tool names that carry a file-path arg and land the file on disk.
1671
+ * Shared with the compaction fileOps classification (native-fileops.ts),
1672
+ * so the diff gate and the <modified-files> list agree on what an edit is. */
1673
+ const ACP_EDIT_TOOLS = ACP_MUTATING_TOOLS;
1674
+
1675
+ /** agy ACP tools that read a file's content; the only native calls whose
1676
+ * path belongs in the compaction read list (#32). */
1677
+ const ACP_READ_TOOLS = new Set(["read_file", "view_file"]);
1653
1678
 
1654
1679
  export function consumeActivity(
1655
1680
  stream: AssistantMessageEventStream,
@@ -1694,16 +1719,25 @@ function callIdArg(args: Record<string, unknown>): string | undefined {
1694
1719
  return typeof v === "string" && v.length > 0 ? v : undefined;
1695
1720
  }
1696
1721
 
1697
- /** File-path argument of an ACP edit tool (observed: `file_path`); other
1698
- * tool kinds (execute, read) don't carry one. Returns undefined for
1699
- * non-edit tools. */
1700
- function acpEditFileArg(args: Record<string, unknown>): string | undefined {
1722
+ /** File-path argument of an ACP tool call (observed: `file_path` on edits,
1723
+ * `AbsolutePath` on view_file). Returns undefined when no path-like arg
1724
+ * exists. */
1725
+ function acpFileArg(args: Record<string, unknown>): string | undefined {
1701
1726
  for (const [k, v] of Object.entries(args)) {
1702
1727
  if (typeof v === "string" && v.trim() && /file|path/i.test(k)) return v;
1703
1728
  }
1704
1729
  return undefined;
1705
1730
  }
1706
1731
 
1732
+ /** Search-target argument of an ACP search call (observed: grep_search's
1733
+ * `pattern`, search-family `query`). Returns undefined for other calls. */
1734
+ function acpQueryArg(args: Record<string, unknown>): string | undefined {
1735
+ for (const [k, v] of Object.entries(args)) {
1736
+ if (typeof v === "string" && v.trim() && /query|pattern/i.test(k)) return v;
1737
+ }
1738
+ return undefined;
1739
+ }
1740
+
1707
1741
  case "tool_done": {
1708
1742
  // Gate C (ACP): the server already executed the tool; nothing parks.
1709
1743
  // Edit display has TWO paths on ACP:
@@ -1714,7 +1748,7 @@ function acpEditFileArg(args: Record<string, unknown>): string | undefined {
1714
1748
  // output the stream-json engine produces, one readFileSync.
1715
1749
  if (feats.engine === "acp") {
1716
1750
  const d = activity.diff;
1717
- const editFile = ACP_EDIT_TOOLS.has(activity.name) ? acpEditFileArg(activity.args) : undefined;
1751
+ const editFile = ACP_EDIT_TOOLS.has(activity.name) ? acpFileArg(activity.args) : undefined;
1718
1752
  const file = d?.path ?? (editFile ? (path.isAbsolute(editFile) ? editFile : path.resolve(cwd, editFile)) : undefined);
1719
1753
  let diffText = d ? formatInlineDiff(d.oldText ?? "", d.newText) : undefined;
1720
1754
  if (!d && file) {
@@ -1727,10 +1761,18 @@ function acpEditFileArg(args: Record<string, unknown>): string | undefined {
1727
1761
  diffText = diffCtx.diffEdit(file, disk).text;
1728
1762
  }
1729
1763
  const command = ["CommandLine", "command_line", "command"].map((k) => activity.args[k]).find((v): v is string => typeof v === "string" && v.length > 0);
1764
+ // Read/search calls carry no diff; capture their target so the
1765
+ // entry keeps the path/query and the compaction fileOps (#32)
1766
+ // can list what agy read. Allowlist beats arg shape: a rename
1767
+ // degrades to no capture, while shape-matching would list
1768
+ // directories and command working dirs as read files.
1769
+ const query = !d && !editFile && !command ? acpQueryArg(activity.args) : undefined;
1770
+ const readArg = !d && !editFile && !command && !query && ACP_READ_TOOLS.has(activity.name) ? acpFileArg(activity.args) : undefined;
1771
+ const readPath = readArg ? (path.isAbsolute(readArg) ? readArg : path.resolve(cwd, readArg)) : undefined;
1730
1772
  let displayed = false;
1731
1773
  try {
1732
1774
  if (feats.onNativeEvent) {
1733
- feats.onNativeEvent({ name: activity.name, mcpServer: activity.mcpServer, status: "completed", path: file, command, output: activity.output, diff: diffText, callId: callIdArg(activity.args) });
1775
+ feats.onNativeEvent({ name: activity.name, mcpServer: activity.mcpServer, status: "completed", path: file ?? readPath, query, command, output: activity.output, diff: diffText, callId: callIdArg(activity.args) });
1734
1776
  displayed = true;
1735
1777
  }
1736
1778
  } catch { /* A stale renderer must never fail the model turn. */ }
@@ -1828,7 +1870,7 @@ async function runTurnDriver(
1828
1870
  const blocks: BlockState = { partial, textIdx: null, thinkingIdx: null, started: false };
1829
1871
 
1830
1872
  const cwd = (options as { cwd?: string } | undefined)?.cwd ?? process.cwd();
1831
- const key = sessionKey(options, cwd, deps.engine);
1873
+ const key = sessionKey(options, cwd, deps.engine, deps.leanAgent === true);
1832
1874
  // Ephemeral helper calls (pi compaction / branch summarization set
1833
1875
  // cacheRetention: "none"; cache warming / replay callers set
1834
1876
  // disableContinuation: true) must run in a fresh, isolated agy
@@ -1840,6 +1882,9 @@ async function runTurnDriver(
1840
1882
  const compactionHandoff =
1841
1883
  !ephemeral && !existing?.conversationId && Boolean(deps.pendingCompactionHandoff?.has(key));
1842
1884
  const messageCount = context.messages.length;
1885
+ // Re-read for the LATE-delivery path below: the fresh-pass `config` above
1886
+ // may predate a steer that landed mid-turn, and the late run wants the
1887
+ // then-current mode/timeout values.
1843
1888
  const config = loadConfig();
1844
1889
  // Settle bookkeeping shared by both store.set paths: the boundary
1845
1890
  // fingerprint validates next turn's delta window, and the compaction
@@ -1857,7 +1902,15 @@ async function runTurnDriver(
1857
1902
  // Continuation: resolve parked round-trips from pi's toolResult messages,
1858
1903
  // then re-attach to the still-running agy turn. No new user event is sent:
1859
1904
  // agy receives the result via the bridge's MCP HTTP response.
1860
- const results = collectToolResults(context.messages, deps.roundTrips.pendingIds);
1905
+ // Ephemeral passes (summaries, cache warming) and handoff passes with no
1906
+ // live turn to reattach to never continue (#33): a stale pending
1907
+ // toolResult would let a throwaway caller consume the live turn, or let
1908
+ // the digest dispatch settle quietly over a stale escalated ack instead
1909
+ // of shipping the handoff.
1910
+ const collectibleIds = ephemeral || (compactionHandoff && !deps.driver.activeHandle)
1911
+ ? []
1912
+ : deps.roundTrips.pendingIds;
1913
+ const results = collectToolResults(context.messages, collectibleIds);
1861
1914
  const isContinuation = results.length > 0;
1862
1915
  // Scanned before the resolve loop: the pending set must still contain the
1863
1916
  // parks being resolved. The steering floor is the session's dispatch
@@ -1927,6 +1980,11 @@ async function runTurnDriver(
1927
1980
  // that survives its first pass is only findable here. Claims are
1928
1981
  // single-use; entries stay pollable for a late model poll.
1929
1982
  let redeliveryConversation: string | undefined;
1983
+ // A strand redelivery into a conversation other than the current binding
1984
+ // is a side trip: the answer belongs where the question was asked. The
1985
+ // settle must keep the fresh record - the recreate check below must not
1986
+ // read this as a mid-turn conversation recreation (#33).
1987
+ let redeliverySideTrip = false;
1930
1988
  const collectStranded = (): LateToolResult[] =>
1931
1989
  deps.roundTrips.claimAllUndelivered().map((view) => {
1932
1990
  redeliveryConversation ??= view.conversationId;
@@ -2004,6 +2062,9 @@ async function runTurnDriver(
2004
2062
  acpBashActive = true;
2005
2063
  }
2006
2064
  const acpToolsDirect = deps.engine === "acp" && config.bridgeTools === "all" && acpBashActive;
2065
+ // Lean agent mode: notes suppressed (see toolNotes); latched at factory
2066
+ // time because the spawned process only saw the flag at spawn.
2067
+ const lean = deps.leanAgent === true;
2007
2068
  // The sync orchestrator for THIS pass when the sync gate dispatched; the
2008
2069
  // settle (and the park persist) sit outside the fresh-pass block, so the
2009
2070
  // binding is function-level (the round-1 settle scope trap).
@@ -2019,6 +2080,7 @@ async function runTurnDriver(
2019
2080
  // Dead turn: claim NOW (single-use). A live turn claims after outcome
2020
2081
  // instead — claiming here would eat the post-outcome recovery.
2021
2082
  if (!ephemeral) late.push(...collectStranded());
2083
+ redeliverySideTrip = redeliveryConversation !== undefined && redeliveryConversation !== existing?.conversationId;
2022
2084
  // A steer with a bound conversation leads the fresh dispatch instead of
2023
2085
  // stopping quietly: the trailing user run becomes the prompt, so the
2024
2086
  // message is answered rather than dropped or left to the digest window.
@@ -2201,7 +2263,7 @@ async function runTurnDriver(
2201
2263
  // coordinator calls throw on invariants: both must fail the turn
2202
2264
  // visibly, not surface as an unhandled rejection.
2203
2265
  const input = turn.inputFor({
2204
- prompt: buildFullPrompt(sys, "", userPrompt ?? "", { codemodeOnly: codemodeNote, acpToolsDirect }) + stageImageNote(syncImages),
2266
+ prompt: buildFullPrompt(sys, "", userPrompt ?? "", { codemodeOnly: codemodeNote, acpToolsDirect, lean }) + stageImageNote(syncImages),
2205
2267
  images: syncImages,
2206
2268
  });
2207
2269
  turn.bound(key);
@@ -2231,7 +2293,7 @@ async function runTurnDriver(
2231
2293
  // history to a fresh conversation; the gate re-opens there.
2232
2294
  const fresh = turn.loadFailed({
2233
2295
  prompt:
2234
- buildFullPrompt(config.systemPrompt ? getCurrentSystemPrompt(context.messages) || undefined : undefined, "", userPrompt ?? "", { codemodeOnly: codemodeNote, acpToolsDirect }) +
2296
+ buildFullPrompt(config.systemPrompt ? getCurrentSystemPrompt(context.messages) || undefined : undefined, "", userPrompt ?? "", { codemodeOnly: codemodeNote, acpToolsDirect, lean }) +
2235
2297
  stageImageNote(syncImages),
2236
2298
  images: syncImages,
2237
2299
  });
@@ -2259,9 +2321,14 @@ async function runTurnDriver(
2259
2321
  // agy's server-side prompt cache.
2260
2322
  const wantDigest = (config.digest || compactionHandoff || compactionResume) && !runTruncated;
2261
2323
  const maxChars = digestMaxCharsForEngine(engine, promptBytes);
2324
+ // A late delivery into a conversation agy already holds stays digest-less
2325
+ // (the digest would re-send context agy has); into a fresh conversation
2326
+ // (post-preempt rotation, #33) the late prompt is the FIRST thing agy
2327
+ // sees, so the digest must ship with it.
2328
+ const digestSkipsLate = late.length > 0 && Boolean(existing?.conversationId);
2262
2329
  const digestRes =
2263
2330
  !syncTurn &&
2264
- wantDigest && maxChars !== null && late.length === 0 && !resume
2331
+ wantDigest && maxChars !== null && !digestSkipsLate && !resume
2265
2332
  ? buildContextDigestResult(context.messages, watermark, {
2266
2333
  bound: Boolean(existing?.conversationId),
2267
2334
  seenSummaryId: existing?.digestSummaryId,
@@ -2343,7 +2410,7 @@ async function runTurnDriver(
2343
2410
  const stagedBody = [
2344
2411
  SYSTEM_PROMPT_PREAMBLE,
2345
2412
  rawSysPrompt,
2346
- toolNotes({ codemodeOnly: codemodeNote, acpToolsDirect }),
2413
+ toolNotes({ codemodeOnly: codemodeNote, acpToolsDirect, lean }),
2347
2414
  ].join("\n\n");
2348
2415
  const stagedName = stageSyspromptAgent(stagedBody);
2349
2416
  if (stagedName) {
@@ -2399,7 +2466,7 @@ async function runTurnDriver(
2399
2466
  // Both features off: the variant would equal the plain prompt.
2400
2467
  if (!fbSys && !freshDigest?.text) return undefined;
2401
2468
  return {
2402
- prompt: buildFullPrompt(fbSys, "", deliveredPrompt, { codemodeOnly: codemodeNote, acpToolsDirect }) + stageImageNote(runImages),
2469
+ prompt: buildFullPrompt(fbSys, "", deliveredPrompt, { codemodeOnly: codemodeNote, acpToolsDirect, lean }) + stageImageNote(runImages),
2403
2470
  contextBlock: freshDigest?.text
2404
2471
  ? {
2405
2472
  uri: `urn:pi-bridge:context-digest/fresh/${messageCount}`,
@@ -2409,10 +2476,15 @@ async function runTurnDriver(
2409
2476
  };
2410
2477
  })()
2411
2478
  : undefined;
2479
+ // Late delivery keeps the context-free framing only when agy already
2480
+ // holds the conversation; a fresh conversation gets the full composition
2481
+ // (system prompt + digest) with the late results appended (#33).
2482
+ const freshLate = late.length > 0 && !existing?.conversationId;
2412
2483
  const fullPrompt =
2413
- (late.length > 0
2484
+ (late.length > 0 && !freshLate
2414
2485
  ? buildLateResultPrompt(late, deliveredPrompt || undefined)
2415
- : buildFullPrompt(sysPrompt, embeddedDigest ? "" : digestFinal, deliveredPrompt, { codemodeOnly: codemodeNote, acpToolsDirect })) +
2486
+ : buildFullPrompt(sysPrompt, embeddedDigest ? "" : digestFinal, deliveredPrompt, { codemodeOnly: codemodeNote, acpToolsDirect, lean }) +
2487
+ (freshLate ? `\n\n${buildLateResultPrompt(late)}` : "")) +
2416
2488
  stageImageNote(runImages);
2417
2489
  if (!syncTurn) {
2418
2490
  try {
@@ -2747,8 +2819,12 @@ async function runTurnDriver(
2747
2819
  // #1). The recreation turn itself is past the gate, so it is the
2748
2820
  // documented residual; recovery starts on the next turn.
2749
2821
  if (existing?.conversationId && outcome.conversationId !== existing.conversationId) {
2750
- store.delete(key);
2751
- stagedAgentByConversation.delete(existing.conversationId);
2822
+ if (redeliverySideTrip) {
2823
+ deps.log?.("redelivery-side-trip", { conversation: outcome.conversationId, key }, "info");
2824
+ } else {
2825
+ store.delete(key);
2826
+ stagedAgentByConversation.delete(existing.conversationId);
2827
+ }
2752
2828
  } else if (outcome.status === "OK" && !outcome.aborted) {
2753
2829
  if (rotationGuardArmed()) {
2754
2830
  deps.log?.("rotation-binding-deferred", { conversation: outcome.conversationId, key }, "info");
@@ -2913,6 +2989,9 @@ export function createStreamSimple(
2913
2989
  // and keying the session as @acp would store a stream
2914
2990
  // conversationId under the wrong engine scope.
2915
2991
  engine: selected === deps.acpDriver ? "acp" : "stream-json",
2992
+ // Lean rides the ACP driver only: on the stream fallback the
2993
+ // default-agent carrier surface is the contract.
2994
+ leanAgent: selected === deps.acpDriver ? deps.leanAgent : undefined,
2916
2995
  log: deps.log,
2917
2996
  });
2918
2997
  } else {