@estebanforge/pi-antigravity-bridge 1.17.1 → 1.17.2

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 CHANGED
@@ -2,6 +2,15 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file.
4
4
 
5
+ ## [1.17.2] - 2026-11-30
6
+
7
+ ### Fixed
8
+
9
+ - pi 1.x builtin MCP and `tool_search` tools are now visible to agy in the all, mcp and codemode modes (issue #34, thanks to mfirdausazizi for the report and the patch). Pi 1.x stamps the builtin `mcp` and `tool-search` extensions' tools (direct MCP tools, deferred MCP tools, MCP resource tools) with `sourceInfo.source === "builtin"`, the same source as pi's core builtins, so the catalog's builtin filter dropped them all: pi-configured MCP servers were invisible to agy, deferred servers could not be discovered or called, and resource tools were unreachable. The catalog now distinguishes by `sourceInfo.path`: an exact allowlist (`builtin:mcp`, `builtin:tool-search`) bridges those tools through the proxied info/call pair on BOTH engines (they run pi-side with no agy-native twin; the stream-json contract that stays native now reads "the seven DEFAULT builtins", and this fix widens the stream-json catalog deliberately). Security notes, unchanged mechanics but a wider surface: bridged tools execute pi-side and bypass `approvals.mode`/`skipPermissions`, so your pi-configured MCP servers (filesystem, shell, SaaS writes) become reachable by agy under "all"; authenticated servers act with your credentials at agy's direction, and agy's native web tools make this an untrusted-content-to-action path (web content agy reads can steer calls to your MCP write tools) - tighten pi-side with a permission extension or the approval gate if you need them gated; `tool_search`, once bridged, lets agy activate registered-but-deferred tools by writing pi's active set, which persists on the pi branch and is also visible to pi's own model (bounded to what you registered); `/agy tools hide` still wins, but hides are session-only and exact-name (a restart drops them, and a hide must exist before the hidden tool becomes useful to agy); MCP servers configured with pi's `exposure: "codemode"` still activate the codemode builtin rather than tool_search, so they stay invisible to agy in "all" mode unless you activate tool_search manually - a known limit shared with the deferred codemode-in-all question.
10
+ - Auto-compaction no longer stalls (and no longer loses the handoff) when it fires while an agy turn is parked on a bridge tool call (issue #33). The compaction summarizer shares the turn driver with the live session, so its one summary turn queued behind a parked turn that only the post-compaction continuation could unpark - a hard stall. A `session_before_compact` handler now closes a pi-blocked parked turn before the summary runs: the turn settles as a failed recycle (the user gets a warning notice), pending parks are denied fail-closed (their results keep late-delivery tombstones so the work still reaches agy after the rotation), and escalated calls are left alone since agy holds their poll handles and the turn is not blocked on pi - those turns can delay a compaction summary by up to the poll-handoff window (a few minutes) but cannot deadlock it. The close is time-bounded so a stuck child teardown cannot stall pi's compaction. Late-delivery follow-through fixed too: a late result reaching a conversation agy has never seen (post-rotation) now ships with the compaction digest and the system prompt instead of as a context-free late prompt, and the handoff latch is only consumed by a pass that actually shipped it; a strand redelivery into a conversation other than the current binding is treated as a side trip so the fresh binding survives the settle. Two related guards: throwaway helper passes (summaries, cache warming) never resolve a pending park or re-attach to the live turn, and a post-rotation handoff pass with no continuable turn ships the digest instead of settling quietly over a stale escalation ack.
11
+
12
+ - Native ACP tool activity now survives compaction (issue #32). agy's native reads and edits were display-only cards the compaction summarizer never saw, so after pi compacted and the bridge rotated to a fresh agy conversation, neither pi's summary nor the handoff digest mentioned the files agy had already read — and the fresh conversation paid quota re-reading them. A `session_before_compact` handler now folds those paths into pi's compaction file lists, so every summary carries deterministic `<read-files>`/`<modified-files>` sections (mutating tools listed as modified, agy's internal brain artifacts and third-party MCP calls excluded) and the lists carry forward across later compactions. Capture widened to match: read cards show the file's basename, search cards show the query (replacing the output-text fallback), and mutating paths resolve absolute like edits.
13
+
5
14
  ## [1.17.1] - 2026-11-29
6
15
 
7
16
  ### Fixed
package/README.md CHANGED
@@ -44,7 +44,7 @@ The bridge starts a localhost MCP server inside pi's process. The exposed catalo
44
44
 
45
45
  **Session isolation.** Both engines keep their agy in a private MCP home with every global `pi-bridge` and `pi-bridge-<pid>` entry filtered out (issue #14): ACP via per-session `mcpServers`, stream-json via the top-level `--gemini_dir` flag, which a quota-free capability probe verifies per agy version. If the running CLI refuses the flag or the home cannot be staged, stream-json falls back to the legacy global per-pid registration plus the delegation suppression machinery, with a one-time warning. The home shares CLI credentials, settings, and conversation state without inheriting another pi session's bridge.
46
46
 
47
- **Engine split.** ACP is the primary engine; stream-json is the maintained fallback. The engines agree on one structural fact: on BOTH, agy's native tool calls execute agy-side (on ACP after a permission frame; on stream-json pi only re-executes read-only calls for card rendering and displays mutating ones through the wrapper). The escalation, poll long-wait, and turn-end handoff machinery covers MCP-routed bridge calls on both engines; a silent native command outlasting the idle guard dies on both (ACP: the bridge's 5-minute stall guard; stream-json: pi's idle cap, issue #21). The engines differ in the catalog: `bridgeTools: "all"` declares pi's default builtins (read, ls, grep, find, edit, write, bash) directly on ACP, making pi's tool surface reachable and long commands protectable; the stream-json CATALOG stays builtin-free (the fallback contract), though the engine-wide prompt note, 110s poll window, and turn-end handoff apply on both engines (the staged stream-json agent file re-stages once). The system prompt ships an ACP note (only when bash is actually active) steering anything longer than a minute onto the bridge bash. One asymmetry to know: bridged tools execute pi-side and are not gated by `approvals.mode` or `skipPermissions` (true for extension tools since the first bridge, and for bash/edit/write on ACP since this change); tighten pi-side with a permission extension or the approval gate if you need those gated too.
47
+ **Engine split.** ACP is the primary engine; stream-json is the maintained fallback. The engines agree on one structural fact: on BOTH, agy's native tool calls execute agy-side (on ACP after a permission frame; on stream-json pi only re-executes read-only calls for card rendering and displays mutating ones through the wrapper). The escalation, poll long-wait, and turn-end handoff machinery covers MCP-routed bridge calls on both engines; a silent native command outlasting the idle guard dies on both (ACP: the bridge's 5-minute stall guard; stream-json: pi's idle cap, issue #21). The engines differ in the catalog: `bridgeTools: "all"` declares pi's default builtins (read, ls, grep, find, edit, write, bash) directly on ACP, making pi's tool surface reachable and long commands protectable; the stream-json CATALOG stays default-builtin-free (the fallback contract), though the engine-wide prompt note, 110s poll window, and turn-end handoff apply on both engines (the staged stream-json agent file re-stages once). Pi 1.x builtin MCP and `tool_search` tools are the exception on both engines: they run pi-side with no agy-native twin, so they bridge through the info/call pair like any extension tool (issue #34). The system prompt ships an ACP note (only when bash is actually active) steering anything longer than a minute onto the bridge bash. One asymmetry to know: bridged tools execute pi-side and are not gated by `approvals.mode` or `skipPermissions` (true for extension tools since the first bridge, and for bash/edit/write on ACP since this change; pi 1.x builtin MCP tools since the #34 change - your pi-configured MCP servers, including filesystem/shell/write-capable ones, become reachable by agy); tighten pi-side with a permission extension or the approval gate if you need those gated too.
48
48
 
49
49
  **Recursion safety.** Only the provider's agy receives the extra `--add-dir`. `AskAntigravity` is also filtered from the exposed tool list. Its delegated `agy -p` spawns with just the workspace, and for the whole delegated run the bridge hides its global per-pid entries: disabled before the spawn, released only on process close or error - agy watches the config and hot-reloads MCP servers on file changes, so a mid-run re-enable would poke the live delegation back into pi. A cross-process marker (`suppression.json` in the bridge's extensions-data dir) coordinates concurrent delegations: entries come back only when no live delegation remains, a session starting mid-delegation registers its own entry disabled, and the session-start heal re-enables only once the last delegator is gone (dead entries pruned by pid liveness with a 24h age bound). The inner agy therefore sees no bridge and cannot re-enter pi. Foreign servers in the global config are never touched.
50
50
 
@@ -121,7 +121,7 @@ If `agy models` fails at load (binary missing, auth not done, network stall), a
121
121
  | --- | --- | --- |
122
122
  | `askTool` | `true` (register the AskAntigravity delegation tool), `false` (no delegation tool; provider and models only) | `true` |
123
123
  | `webTools` | `false` (no web tools), `true` (register `agy_web_search` + `agy_read_url` as Pi tools, usable by ANY provider's model). Each call spawns a one-shot search-only `agy` agent (plan mode, bridge MCP inheritance off), gates the answer on an observed native `search_web`/`read_url_content` step, and spends Antigravity quota. Off by default: Antigravity sessions already have native web tools on both engines; these serve other providers | `false` |
124
- | `bridgeTools` | `none` (no pi tools; an active approval gate still starts the listener gate-only, and no global registration is written), `all` (every non-builtin tool, incl. other `Ask*` delegations; on ACP also pi's builtins - read, ls, grep, find, edit, write, bash - declared directly, since ACP's native tool calls execute agy-side and would otherwise bypass pi entirely), `mcp` (pi-mcp-adapter tools + skills bridge only), `codemode` (pi's `codemode` tool + the info/call pair only; requires pi's codemode tool to be active, e.g. `--tools codemode`) | `all` |
124
+ | `bridgeTools` | `none` (no pi tools; an active approval gate still starts the listener gate-only, and no global registration is written), `all` (every pi tool except the core builtins, incl. other `Ask*` delegations; pi 1.x builtin MCP and `tool_search` tools bridge on both engines through the info/call pair, and on ACP pi's builtins - read, ls, grep, find, edit, write, bash - are declared directly, since ACP's native tool calls execute agy-side and would otherwise bypass pi entirely), `mcp` (pi-mcp-adapter tools, pi 1.x builtin MCP and `tool_search` tools + skills bridge only), `codemode` (pi's `codemode` tool + the info/call pair only; requires pi's codemode tool to be active, e.g. `--tools codemode`) | `all` |
125
125
  | `digest` | Self-gating delta of pi-side context (compaction summaries, other-provider turns, handoffs after a mid-session switch) shipped to agy only when the delta is non-empty, each piece once. Pure antigravity sessions get byte-stable prompts and an intact prompt cache. `false` = agy prompts contain only your message; a conversation opened mid-session starts without prior pi-side context | `true` |
126
126
  | `systemPrompt` | `on` (send pi's system prompt - operating instructions plus the global agent-dir `AGENTS.md` and ancestor `AGENTS.md`/`CLAUDE.md` - to the first prompt of each new agy conversation, plus a tool-priority note: Pi Bridge tools win over agy's native interactive ones, which never reach the user; on ACP with `bridgeTools: "all"` and bash active, an extra ACP note steers long commands onto the bridge bash (a silent native command past the stall guard is killed). Delivery: stream-json stages it as an agy agent file via `--agent`, off the prompt line - the CLI silently drops single prompts past a ~25KB cap and the dropped turn kills the conversation; the carrier declares the productive toolset explicitly (omitting `tools:` reads as a read-only set upstream, issue #13) plus `subagent: false` + `agents: []` so the native subagent tools stay masked (ACP carries no agent file, so its natives remain and the tool-priority note steers the model to pi delegation). ACP prepends it to the first prompt) or `false` (agy-native behavior) | `true` |
127
127
  | `readOnly` | `true`: fail-closed kill switch - every provider turn and the `AskAntigravity` tool are refused with a visible error (the CLI has no review-only enforcement, see [Permissions](#permissions) and [readOnly](#readonly)). In the file, any value that is not a recognized boolean spelling (or an explicit blank) also fails closed to `true` | `false` |
@@ -51,6 +51,8 @@ import {
51
51
  type NativeDisplayEvent,
52
52
  } from "../src/provider.js";
53
53
  import { handoffToast } from "../src/handoff-toast.js";
54
+ import { collectNativeFileOps } from "../src/native-fileops.js";
55
+ import { preemptParkedTurnForCompaction } from "../src/compaction-preempt.js";
54
56
  import { PollRunFolder, type PollRunData } from "../src/poll-fold.js";
55
57
  import {
56
58
  createShadowTool,
@@ -425,7 +427,7 @@ export default async function (pi: ExtensionAPI): Promise<void> {
425
427
  // display text). The name is NOT a fallback here - it rendered "ls ls"
426
428
  // duplication whenever the event carried neither path nor command.
427
429
  const firstLine = (value: string | undefined): string | undefined => value?.split(/\r?\n/, 1)[0].trim() || undefined;
428
- const detail = event?.path ? path.basename(event.path) : firstLine(event?.command) ?? firstLine(event?.output);
430
+ const detail = event?.path ? path.basename(event.path) : firstLine(event?.query) ?? firstLine(event?.command) ?? firstLine(event?.output);
429
431
  const status = event?.status === "failed" ? theme.fg("error", "✗") : theme.fg("success", "✓");
430
432
  const lines = [`${status} ${theme.fg("toolTitle", event?.name ?? "Antigravity")}${detail ? ` ${theme.fg("muted", detail.slice(0, 160))}` : ""}`];
431
433
  if (expanded) {
@@ -491,11 +493,13 @@ export default async function (pi: ExtensionAPI): Promise<void> {
491
493
  pendingNativeTools = Math.max(0, pendingNativeTools - 1);
492
494
  if (pendingNativeTools === 0) activeUi?.setStatus("agy-native", undefined);
493
495
  // Bound persisted session size; the ACP result and diff may be megabytes.
496
+ // path stays whole: the compaction fileOps (#32) fold it verbatim.
494
497
  pi.appendEntry<NativeDisplayEvent>("agy-native-event", {
495
498
  ...event,
496
499
  output: event.output?.slice(0, 4000),
497
500
  diff: event.diff?.slice(0, 12000),
498
501
  command: event.command?.slice(0, 500),
502
+ query: event.query?.slice(0, 500),
499
503
  });
500
504
  };
501
505
  // Native re-exec only emits for builtins actually active in the session;
@@ -676,6 +680,35 @@ export default async function (pi: ExtensionAPI): Promise<void> {
676
680
  backgroundWatchers.clear();
677
681
  pendingCompactionHandoff.clear();
678
682
  });
683
+ pi.on("session_before_compact", async (event) => {
684
+ try {
685
+ // Native ACP activity lives only in display entries the summarizer
686
+ // never sees; fileOps is what carries it into the summary (#32).
687
+ // Older peer builds may omit branchEntries despite the type (#32).
688
+ collectNativeFileOps(event.branchEntries ?? [], event.preparation.fileOps);
689
+ } catch (err) {
690
+ fileLog.log("native-fileops-error", { error: err instanceof Error ? err.message : String(err) }, "warn");
691
+ }
692
+ try {
693
+ // A parked turn can only be unparked by the continuation the
694
+ // summarizer itself blocks, so close it before the summary runs (#33).
695
+ const preempted = await preemptParkedTurnForCompaction(activeDriver(), roundTrips, {
696
+ log: (msg, data, level) => fileLog.log(msg, data, level ?? "info"),
697
+ });
698
+ if (preempted && activeUi) {
699
+ activeUi.notify(
700
+ "Compaction interrupted a parked agy turn; its tool results will be re-sent to the next agy conversation.",
701
+ "warning",
702
+ );
703
+ }
704
+ } catch (err) {
705
+ fileLog.log(
706
+ "compaction-preempt-error",
707
+ { error: err instanceof Error ? err.message : String(err) },
708
+ "warn",
709
+ );
710
+ }
711
+ });
679
712
  pi.on("session_compact", (_event, ctx) => {
680
713
  try {
681
714
  // Shape-cast as in model_select below: tolerate pi builds whose dts
@@ -1955,7 +1988,7 @@ function registerAgyCommand(pi: ExtensionAPI, ctx: AgyCommandCtx): void {
1955
1988
  );
1956
1989
  }
1957
1990
  } else {
1958
- ui?.notify(`bridge: ${loadConfig().bridgeTools}\nusage: /agy bridge all|mcp|codemode|none\n all: active non-builtin pi tools (ACP: pi's builtins too, declared directly). mcp: active pi-mcp-adapter tools + skills. codemode: the codemode tool + info/call pair only (pi's codemode tool must be active; without it this behaves like all). none: no pi tools (an active approval gate still runs the listener gate-only).`, "info");
1991
+ ui?.notify(`bridge: ${loadConfig().bridgeTools}\nusage: /agy bridge all|mcp|codemode|none\n all: active pi tools except the core builtins (ACP declares the seven defaults directly; pi 1.x builtin MCP and tool_search tools bridge on both engines). mcp: active pi-mcp-adapter tools, pi 1.x builtin MCP and tool_search tools + skills. codemode: the codemode tool + info/call pair only (pi's codemode tool must be active; without it this behaves like all, minus ACP's direct builtins). none: no pi tools (an active approval gate still runs the listener gate-only).`, "info");
1959
1992
  }
1960
1993
  return;
1961
1994
  }
@@ -2144,7 +2177,7 @@ async function openAgyPicker(ui: ExtensionUIContext, ctx: AgyCommandCtx): Promis
2144
2177
  id: "bridge",
2145
2178
  label: "Bridge tools",
2146
2179
  description:
2147
- "Which pi tools the MCP bridge exposes to agy. all (default): every non-builtin tool; on ACP also pi's builtins (read, ls, grep, find, edit, write, bash), declared directly so long commands ride the poll machinery. mcp: pi-mcp-adapter tools + skills. codemode: the codemode tool + info/call pair only (pi's codemode tool must be active, e.g. --tools codemode). none: no pi tools (an active approval gate still runs the listener gate-only).",
2180
+ "Which pi tools the MCP bridge exposes to agy. all (default): every pi tool except the core builtins; pi 1.x builtin MCP and tool_search tools ride the proxied pair on both engines, and on ACP the builtins (read, ls, grep, find, edit, write, bash) are declared directly so long commands ride the poll machinery. mcp: pi-mcp-adapter tools, pi 1.x builtin MCP and tool_search tools + skills. codemode: the codemode tool + info/call pair only (pi's codemode tool must be active, e.g. --tools codemode). none: no pi tools (an active approval gate still runs the listener gate-only).",
2148
2181
  currentValue: config.bridgeTools,
2149
2182
  values: ["all", "mcp", "codemode", "none"],
2150
2183
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@estebanforge/pi-antigravity-bridge",
3
- "version": "1.17.1",
3
+ "version": "1.17.2",
4
4
  "description": "Gemini provider for Pi on the Antigravity ACP server (official Google ACP) or the stream-json agy CLI. Use antigravity/* models in Pi. Full /model picker support. Models runs Pi's tools. ToS safe to use.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -6,7 +6,9 @@ export interface BridgeToolInfo {
6
6
  name: string;
7
7
  description?: string;
8
8
  parameters?: object;
9
- sourceInfo?: { source?: string };
9
+ // Pi 1.x carries the full source identity: core builtins and builtin
10
+ // extensions share source "builtin"; only path distinguishes them.
11
+ sourceInfo?: { source?: string; path?: string };
10
12
  }
11
13
 
12
14
  export const TOOL_INFO_TOOL_NAME = "bridge_tool_info";
@@ -16,6 +18,21 @@ const MAX_INFO_TOOLS_PER_CALL = 20;
16
18
 
17
19
  /** Pi's seven built-in default tools; only these stay always-loaded when active. */
18
20
  const PI_DEFAULT_TOOLS = new Set(["read", "bash", "edit", "write", "grep", "find", "ls"]);
21
+ /** Pi 1.x builtin extensions whose tools run pi-side (the engine has no native
22
+ * twin), so they bridge on both engines through the proxied info/call pair. */
23
+ const PI_BUILTIN_MCP_PATHS = new Set(["builtin:mcp", "builtin:tool-search"]);
24
+
25
+ function isBuiltinMcp(tool: BridgeToolInfo): boolean {
26
+ const info = tool.sourceInfo;
27
+ return info?.source === "builtin" && PI_BUILTIN_MCP_PATHS.has(info.path ?? "");
28
+ }
29
+
30
+ /** Core builtins (builtin:read, builtin:powershell, builtin:codemode, ...):
31
+ * the native-execution concern of the engine carve-outs applies to these
32
+ * only; builtin MCP/discovery tools are not core builtins for filtering. */
33
+ function isCoreBuiltin(tool: BridgeToolInfo): boolean {
34
+ return tool.sourceInfo?.source === "builtin" && !isBuiltinMcp(tool);
35
+ }
19
36
 
20
37
  const BRIDGE_INTERNAL_TOOLS = new Set([
21
38
  "AskAntigravity",
@@ -57,19 +74,21 @@ export function bridgedPiTools(
57
74
  (mode === "codemode"
58
75
  // Codemode mode: pi's builtin codemode tool is the one builtin that
59
76
  // bridges (scripts reach the rest pi-side); the info/call pair covers
60
- // tools the engine should not call directly.
61
- ? tool.name === "codemode" || tool.sourceInfo?.source !== "builtin"
77
+ // tools the engine should not call directly. Builtin MCP/discovery
78
+ // tools run pi-side, so they ride the pair here too (#34).
79
+ ? tool.name === "codemode" || !isCoreBuiltin(tool)
62
80
  : mode === "mcp"
63
- ? /pi-mcp-adapter/.test(tool.sourceInfo?.source ?? "")
81
+ ? /pi-mcp-adapter/.test(tool.sourceInfo?.source ?? "") || isBuiltinMcp(tool)
64
82
  // ACP must declare pi's default builtins directly: its native tool
65
83
  // calls execute agy-side (provider Gate C), so pi's tools would be
66
84
  // unreachable pi-side and long commands would bypass the poll
67
85
  // machinery entirely. Limited to the seven defaults: a builtin like
68
86
  // codemode stays codemode-mode-only on both engines. stream-json
69
- // keeps them out: its native commands also run agy-side (pi only
70
- // re-executes read-only calls for card rendering), so the catalog
71
- // there stays exactly as it shipped.
72
- : tool.sourceInfo?.source !== "builtin" || (engine === "acp" && PI_DEFAULT_TOOLS.has(tool.name))),
87
+ // keeps the DEFAULTS native too: its native commands also run
88
+ // agy-side (pi only re-executes read-only calls for card
89
+ // rendering). Builtin MCP/discovery tools are different: they run
90
+ // pi-side on both engines, so they bridge like any extension tool.
91
+ : !isCoreBuiltin(tool) || (engine === "acp" && PI_DEFAULT_TOOLS.has(tool.name))),
73
92
  );
74
93
  }
75
94
 
@@ -0,0 +1,69 @@
1
+ // Compaction preempt (#33): closes the pi-blocked parked agy turn so the
2
+ // compaction summarizer can dispatch instead of queueing behind it forever.
3
+ // Tombstoned parks keep late delivery after the rotation; escalated calls
4
+ // are spared (agy holds their poll handle, the turn is not blocked on pi).
5
+
6
+ import type { TurnDriver } from "./driver-types.js";
7
+ import type { ToolRoundTrips } from "./provider.js";
8
+
9
+ /** close() cause recorded in the recycle stats and the settled outcome
10
+ * error, so a preempted turn is identifiable in the file log. */
11
+ export const COMPACTION_PREEMPT_CAUSE = "compaction";
12
+
13
+ const DEFAULT_CLOSE_TIMEOUT_MS = 5_000;
14
+
15
+ export interface PreemptOpts {
16
+ /** Bounds driver.close(): a stuck child teardown must not stall pi's
17
+ * compaction flow, which awaits this handler. */
18
+ closeTimeoutMs?: number;
19
+ log?: (msg: string, data?: unknown, level?: "debug" | "info" | "warn" | "error") => void;
20
+ }
21
+
22
+ /** True when the active turn is waiting on pi: any pending park that is not
23
+ * an escalated bridge call (approvals and native rt round-trips included -
24
+ * all of them settle only via a pi toolResult). */
25
+ export function turnBlockedOnPi(roundTrips: ToolRoundTrips): boolean {
26
+ return roundTrips.pendingIds.some((id) => !roundTrips.poll(id));
27
+ }
28
+
29
+ /** Close the pi-blocked parked turn so the compaction summarizer can
30
+ * dispatch. Returns false when there is nothing to preempt (no active
31
+ * turn, or every pending park is escalated). The existing onTurnEnd hook
32
+ * denies approval parks and moves bridge parks to tombstones; late
33
+ * delivery re-prompts agy with the results after the rotation. */
34
+ export async function preemptParkedTurnForCompaction(
35
+ driver: TurnDriver,
36
+ roundTrips: ToolRoundTrips,
37
+ opts: PreemptOpts = {},
38
+ ): Promise<boolean> {
39
+ if (!driver.activeHandle || !turnBlockedOnPi(roundTrips)) return false;
40
+ const log = opts.log;
41
+ const closeTimeoutMs = opts.closeTimeoutMs ?? DEFAULT_CLOSE_TIMEOUT_MS;
42
+ // Both engines settle the active turn inside close("recycle") and stay
43
+ // usable for the summarizer's fresh dispatch. The race bounds a hung
44
+ // child teardown: compaction must proceed even if close cannot finish.
45
+ const closed = driver
46
+ .close("recycle", COMPACTION_PREEMPT_CAUSE)
47
+ .then(
48
+ () => true,
49
+ (err: unknown) => {
50
+ log?.(
51
+ "compaction-preempt-close-error",
52
+ { error: err instanceof Error ? err.message : String(err) },
53
+ "warn",
54
+ );
55
+ return true;
56
+ },
57
+ );
58
+ let timer: ReturnType<typeof setTimeout> | undefined;
59
+ const timedOut = new Promise<"timeout">((resolve) => {
60
+ timer = setTimeout(() => resolve("timeout"), closeTimeoutMs);
61
+ });
62
+ const result = await Promise.race([closed, timedOut]);
63
+ if (timer) clearTimeout(timer);
64
+ if (result === "timeout") {
65
+ log?.("compaction-preempt-close-timeout", { closeTimeoutMs }, "warn");
66
+ }
67
+ log?.("compaction-preempt", { cause: COMPACTION_PREEMPT_CAUSE }, "info");
68
+ return true;
69
+ }
package/src/config.ts CHANGED
@@ -159,10 +159,13 @@ export interface AgyConfig {
159
159
  * Absent = agy's default agent. ACP turns ignore it (no protocol slot). */
160
160
  agent?: string;
161
161
  /** Which pi tools the MCP bridge exposes to agy: "none" (bridge off),
162
- * "all" (every registered non-builtin tool incl. other Ask* delegations;
162
+ * "all" (every registered non-core-builtin tool incl. other Ask*
163
+ * delegations; pi 1.x builtin MCP/discovery tools ride the proxied pair on
164
+ * both engines, and ACP declares the seven default builtins directly;
163
165
  * default - users expect the bridge working out of the box, and the
164
166
  * "mcp" surface serves an empty catalog on installs without
165
- * pi-mcp-adapter), "mcp" (pi-mcp-adapter tools + skills bridge only). */
167
+ * pi-mcp-adapter), "mcp" (pi-mcp-adapter tools, pi 1.x builtin MCP and
168
+ * tool_search tools + skills bridge only). */
166
169
  bridgeTools: BridgeTools;
167
170
  /** Extra pi tool names that get the long (120s) synchronous escalation
168
171
  * window, in addition to delegation-shaped names (subagent_run,
@@ -0,0 +1,40 @@
1
+ // Compaction file lists for native ACP tool activity (#32): those calls are
2
+ // display-only entries the summarizer never sees, so their paths are folded
3
+ // into session_before_compact's preparation.fileOps instead.
4
+
5
+ import type { CustomEntry, FileOperations, SessionEntry } from "@earendil-works/pi-coding-agent";
6
+ import type { NativeDisplayEvent } from "./provider.js";
7
+
8
+ /** agy ACP tools whose call lands content on disk; their paths belong in the
9
+ * modified list, not read-only. Shared with the provider's diff gate. */
10
+ export const ACP_MUTATING_TOOLS = new Set([
11
+ "edit_file",
12
+ "write_to_file",
13
+ "create_file",
14
+ "write_file",
15
+ "replace_file_content",
16
+ "multi_replace_file_content",
17
+ ]);
18
+
19
+ export function createFileOps(): FileOperations {
20
+ return { read: new Set(), written: new Set(), edited: new Set() };
21
+ }
22
+
23
+ /** Fold agy-native-event entries into fileOps. Only completed non-MCP calls
24
+ * count; agy's own brain artifacts are internal, not user files. Mutating
25
+ * tools land in `edited` so computeFileLists keeps their paths out of
26
+ * read-only; Sets dedupe, so folding across compaction boundaries is safe
27
+ * (pi's carry-forward re-adds prior lists anyway). */
28
+ export function collectNativeFileOps(entries: readonly SessionEntry[], into?: FileOperations): FileOperations {
29
+ const fileOps = into ?? createFileOps();
30
+ for (const entry of entries) {
31
+ if (entry.type !== "custom" || (entry as CustomEntry).customType !== "agy-native-event") continue;
32
+ const event = (entry as CustomEntry<NativeDisplayEvent>).data;
33
+ if (!event?.path || event.status !== "completed") continue;
34
+ if (event.mcpServer) continue;
35
+ if (event.path.includes("/.system_generated/") || event.path.includes("/brain/")) continue;
36
+ if (ACP_MUTATING_TOOLS.has(event.name)) fileOps.edited.add(event.path);
37
+ else fileOps.read.add(event.path);
38
+ }
39
+ return fileOps;
40
+ }
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";
@@ -669,6 +670,9 @@ export interface NativeDisplayEvent {
669
670
  * extension resolve the polled pi tool via the escalation registry. */
670
671
  callId?: string;
671
672
  path?: string;
673
+ /** Search target of a search-class native call (grep pattern, web
674
+ * query); read and command calls leave it undefined. */
675
+ query?: string;
672
676
  command?: string;
673
677
  output?: string;
674
678
  diff?: string;
@@ -1645,11 +1649,14 @@ function emitToolUse(
1645
1649
  stream.end();
1646
1650
  }
1647
1651
 
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"]);
1652
+ /** ACP tool names that carry a file-path arg and land the file on disk.
1653
+ * Shared with the compaction fileOps classification (native-fileops.ts),
1654
+ * so the diff gate and the <modified-files> list agree on what an edit is. */
1655
+ const ACP_EDIT_TOOLS = ACP_MUTATING_TOOLS;
1656
+
1657
+ /** agy ACP tools that read a file's content; the only native calls whose
1658
+ * path belongs in the compaction read list (#32). */
1659
+ const ACP_READ_TOOLS = new Set(["read_file", "view_file"]);
1653
1660
 
1654
1661
  export function consumeActivity(
1655
1662
  stream: AssistantMessageEventStream,
@@ -1694,16 +1701,25 @@ function callIdArg(args: Record<string, unknown>): string | undefined {
1694
1701
  return typeof v === "string" && v.length > 0 ? v : undefined;
1695
1702
  }
1696
1703
 
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 {
1704
+ /** File-path argument of an ACP tool call (observed: `file_path` on edits,
1705
+ * `AbsolutePath` on view_file). Returns undefined when no path-like arg
1706
+ * exists. */
1707
+ function acpFileArg(args: Record<string, unknown>): string | undefined {
1701
1708
  for (const [k, v] of Object.entries(args)) {
1702
1709
  if (typeof v === "string" && v.trim() && /file|path/i.test(k)) return v;
1703
1710
  }
1704
1711
  return undefined;
1705
1712
  }
1706
1713
 
1714
+ /** Search-target argument of an ACP search call (observed: grep_search's
1715
+ * `pattern`, search-family `query`). Returns undefined for other calls. */
1716
+ function acpQueryArg(args: Record<string, unknown>): string | undefined {
1717
+ for (const [k, v] of Object.entries(args)) {
1718
+ if (typeof v === "string" && v.trim() && /query|pattern/i.test(k)) return v;
1719
+ }
1720
+ return undefined;
1721
+ }
1722
+
1707
1723
  case "tool_done": {
1708
1724
  // Gate C (ACP): the server already executed the tool; nothing parks.
1709
1725
  // Edit display has TWO paths on ACP:
@@ -1714,7 +1730,7 @@ function acpEditFileArg(args: Record<string, unknown>): string | undefined {
1714
1730
  // output the stream-json engine produces, one readFileSync.
1715
1731
  if (feats.engine === "acp") {
1716
1732
  const d = activity.diff;
1717
- const editFile = ACP_EDIT_TOOLS.has(activity.name) ? acpEditFileArg(activity.args) : undefined;
1733
+ const editFile = ACP_EDIT_TOOLS.has(activity.name) ? acpFileArg(activity.args) : undefined;
1718
1734
  const file = d?.path ?? (editFile ? (path.isAbsolute(editFile) ? editFile : path.resolve(cwd, editFile)) : undefined);
1719
1735
  let diffText = d ? formatInlineDiff(d.oldText ?? "", d.newText) : undefined;
1720
1736
  if (!d && file) {
@@ -1727,10 +1743,18 @@ function acpEditFileArg(args: Record<string, unknown>): string | undefined {
1727
1743
  diffText = diffCtx.diffEdit(file, disk).text;
1728
1744
  }
1729
1745
  const command = ["CommandLine", "command_line", "command"].map((k) => activity.args[k]).find((v): v is string => typeof v === "string" && v.length > 0);
1746
+ // Read/search calls carry no diff; capture their target so the
1747
+ // entry keeps the path/query and the compaction fileOps (#32)
1748
+ // can list what agy read. Allowlist beats arg shape: a rename
1749
+ // degrades to no capture, while shape-matching would list
1750
+ // directories and command working dirs as read files.
1751
+ const query = !d && !editFile && !command ? acpQueryArg(activity.args) : undefined;
1752
+ const readArg = !d && !editFile && !command && !query && ACP_READ_TOOLS.has(activity.name) ? acpFileArg(activity.args) : undefined;
1753
+ const readPath = readArg ? (path.isAbsolute(readArg) ? readArg : path.resolve(cwd, readArg)) : undefined;
1730
1754
  let displayed = false;
1731
1755
  try {
1732
1756
  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) });
1757
+ 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
1758
  displayed = true;
1735
1759
  }
1736
1760
  } catch { /* A stale renderer must never fail the model turn. */ }
@@ -1857,7 +1881,15 @@ async function runTurnDriver(
1857
1881
  // Continuation: resolve parked round-trips from pi's toolResult messages,
1858
1882
  // then re-attach to the still-running agy turn. No new user event is sent:
1859
1883
  // agy receives the result via the bridge's MCP HTTP response.
1860
- const results = collectToolResults(context.messages, deps.roundTrips.pendingIds);
1884
+ // Ephemeral passes (summaries, cache warming) and handoff passes with no
1885
+ // live turn to reattach to never continue (#33): a stale pending
1886
+ // toolResult would let a throwaway caller consume the live turn, or let
1887
+ // the digest dispatch settle quietly over a stale escalated ack instead
1888
+ // of shipping the handoff.
1889
+ const collectibleIds = ephemeral || (compactionHandoff && !deps.driver.activeHandle)
1890
+ ? []
1891
+ : deps.roundTrips.pendingIds;
1892
+ const results = collectToolResults(context.messages, collectibleIds);
1861
1893
  const isContinuation = results.length > 0;
1862
1894
  // Scanned before the resolve loop: the pending set must still contain the
1863
1895
  // parks being resolved. The steering floor is the session's dispatch
@@ -1927,6 +1959,11 @@ async function runTurnDriver(
1927
1959
  // that survives its first pass is only findable here. Claims are
1928
1960
  // single-use; entries stay pollable for a late model poll.
1929
1961
  let redeliveryConversation: string | undefined;
1962
+ // A strand redelivery into a conversation other than the current binding
1963
+ // is a side trip: the answer belongs where the question was asked. The
1964
+ // settle must keep the fresh record - the recreate check below must not
1965
+ // read this as a mid-turn conversation recreation (#33).
1966
+ let redeliverySideTrip = false;
1930
1967
  const collectStranded = (): LateToolResult[] =>
1931
1968
  deps.roundTrips.claimAllUndelivered().map((view) => {
1932
1969
  redeliveryConversation ??= view.conversationId;
@@ -2019,6 +2056,7 @@ async function runTurnDriver(
2019
2056
  // Dead turn: claim NOW (single-use). A live turn claims after outcome
2020
2057
  // instead — claiming here would eat the post-outcome recovery.
2021
2058
  if (!ephemeral) late.push(...collectStranded());
2059
+ redeliverySideTrip = redeliveryConversation !== undefined && redeliveryConversation !== existing?.conversationId;
2022
2060
  // A steer with a bound conversation leads the fresh dispatch instead of
2023
2061
  // stopping quietly: the trailing user run becomes the prompt, so the
2024
2062
  // message is answered rather than dropped or left to the digest window.
@@ -2259,9 +2297,14 @@ async function runTurnDriver(
2259
2297
  // agy's server-side prompt cache.
2260
2298
  const wantDigest = (config.digest || compactionHandoff || compactionResume) && !runTruncated;
2261
2299
  const maxChars = digestMaxCharsForEngine(engine, promptBytes);
2300
+ // A late delivery into a conversation agy already holds stays digest-less
2301
+ // (the digest would re-send context agy has); into a fresh conversation
2302
+ // (post-preempt rotation, #33) the late prompt is the FIRST thing agy
2303
+ // sees, so the digest must ship with it.
2304
+ const digestSkipsLate = late.length > 0 && Boolean(existing?.conversationId);
2262
2305
  const digestRes =
2263
2306
  !syncTurn &&
2264
- wantDigest && maxChars !== null && late.length === 0 && !resume
2307
+ wantDigest && maxChars !== null && !digestSkipsLate && !resume
2265
2308
  ? buildContextDigestResult(context.messages, watermark, {
2266
2309
  bound: Boolean(existing?.conversationId),
2267
2310
  seenSummaryId: existing?.digestSummaryId,
@@ -2409,10 +2452,15 @@ async function runTurnDriver(
2409
2452
  };
2410
2453
  })()
2411
2454
  : undefined;
2455
+ // Late delivery keeps the context-free framing only when agy already
2456
+ // holds the conversation; a fresh conversation gets the full composition
2457
+ // (system prompt + digest) with the late results appended (#33).
2458
+ const freshLate = late.length > 0 && !existing?.conversationId;
2412
2459
  const fullPrompt =
2413
- (late.length > 0
2460
+ (late.length > 0 && !freshLate
2414
2461
  ? buildLateResultPrompt(late, deliveredPrompt || undefined)
2415
- : buildFullPrompt(sysPrompt, embeddedDigest ? "" : digestFinal, deliveredPrompt, { codemodeOnly: codemodeNote, acpToolsDirect })) +
2462
+ : buildFullPrompt(sysPrompt, embeddedDigest ? "" : digestFinal, deliveredPrompt, { codemodeOnly: codemodeNote, acpToolsDirect }) +
2463
+ (freshLate ? `\n\n${buildLateResultPrompt(late)}` : "")) +
2416
2464
  stageImageNote(runImages);
2417
2465
  if (!syncTurn) {
2418
2466
  try {
@@ -2747,8 +2795,12 @@ async function runTurnDriver(
2747
2795
  // #1). The recreation turn itself is past the gate, so it is the
2748
2796
  // documented residual; recovery starts on the next turn.
2749
2797
  if (existing?.conversationId && outcome.conversationId !== existing.conversationId) {
2750
- store.delete(key);
2751
- stagedAgentByConversation.delete(existing.conversationId);
2798
+ if (redeliverySideTrip) {
2799
+ deps.log?.("redelivery-side-trip", { conversation: outcome.conversationId, key }, "info");
2800
+ } else {
2801
+ store.delete(key);
2802
+ stagedAgentByConversation.delete(existing.conversationId);
2803
+ }
2752
2804
  } else if (outcome.status === "OK" && !outcome.aborted) {
2753
2805
  if (rotationGuardArmed()) {
2754
2806
  deps.log?.("rotation-binding-deferred", { conversation: outcome.conversationId, key }, "info");