@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/acp/events.ts CHANGED
@@ -65,12 +65,13 @@ export function mapUpdate(update: unknown): MappedUpdate {
65
65
  const id = stringField(u.toolCallId);
66
66
  if (!id) return null;
67
67
  const nativeMcp = nativeMcpTool(u);
68
+ const lean = leanMcpTool(u);
68
69
  return {
69
70
  kind: "tool_start",
70
71
  toolCallId: id,
71
- name: metaToolName(u._meta) ?? nativeMcp?.name ?? stringField(u.name) ?? toolName(u.title, u.kind),
72
- args: rawArguments(u.rawInput),
73
- mcpServer: stringField(recordField(recordField(u._meta).mcp).server) ?? nativeMcp?.server,
72
+ name: metaToolName(u._meta) ?? lean?.name ?? nativeMcp?.name ?? stringField(u.name) ?? toolName(u.title, u.kind),
73
+ args: lean?.args ?? rawArguments(u.rawInput),
74
+ mcpServer: stringField(recordField(recordField(u._meta).mcp).server) ?? lean?.server ?? nativeMcp?.server,
74
75
  // Edits carry their native diff HERE, on the pending tool_call
75
76
  // frame (run 6:10) — the completed update carries only display
76
77
  // text. contentDiff on the update stays as a future-build
@@ -89,7 +90,7 @@ export function mapUpdate(update: unknown): MappedUpdate {
89
90
  // failure next to a successful edit.
90
91
  const raw = stringField(u.rawOutput);
91
92
  if (raw?.includes("approved but never executed")) return null;
92
- const mcpServer = stringField(recordField(recordField(u._meta).mcp).server) ?? nativeMcpTool(u)?.server;
93
+ const mcpServer = stringField(recordField(recordField(u._meta).mcp).server) ?? leanMcpTool(u)?.server ?? nativeMcpTool(u)?.server;
93
94
  return { kind: "tool_error", toolCallId: id, message: raw ?? "tool failed", ...(mcpServer ? { mcpServer } : {}) };
94
95
  }
95
96
  if (u.status === "completed") {
@@ -97,7 +98,7 @@ export function mapUpdate(update: unknown): MappedUpdate {
97
98
  // often just the server's display title, not the result (probe
98
99
  // 2026-09-03: completed MCP call, rawOutput "Call bridge_echo").
99
100
  const diff = contentDiff(u.content);
100
- const mcpServer = stringField(recordField(recordField(u._meta).mcp).server) ?? nativeMcpTool(u)?.server;
101
+ const mcpServer = stringField(recordField(recordField(u._meta).mcp).server) ?? leanMcpTool(u)?.server ?? nativeMcpTool(u)?.server;
101
102
  return {
102
103
  kind: "tool_done",
103
104
  toolCallId: id,
@@ -132,6 +133,21 @@ function nativeMcpTool(update: Record<string, unknown>): { name: string; server:
132
133
  return match ? { server: match[1]!, name: match[2]! } : undefined;
133
134
  }
134
135
 
136
+ /** Lean-agent frames (excludeDefaultComponents agents): the model's only tool
137
+ * is the generic call_mcp_tool wrapper and the real call hides in
138
+ * rawInput {ServerName, ToolName, Arguments} — no _meta.mcp, no
139
+ * mcp_<server>_<tool> name. Without this unwrap the pi-bridge display
140
+ * filter, poll folding and round-trip tracking all miss the call
141
+ * (live-captured fixture, agy 1.5.22, 2026-12-02). */
142
+ function leanMcpTool(update: Record<string, unknown>): { server: string; name: string; args: Record<string, unknown> } | undefined {
143
+ if (stringField(update.name) !== "call_mcp_tool") return undefined;
144
+ const raw = recordField(update.rawInput);
145
+ const server = stringField(raw.ServerName);
146
+ const name = stringField(raw.ToolName);
147
+ if (!server || !name) return undefined;
148
+ return { server, name, args: recordField(raw.Arguments) };
149
+ }
150
+
135
151
  /** Clean tool name for MCP tools: the title is "<server>_<tool>" (e.g.
136
152
  * "pi-bridge_bridge_echo") and the real name hides in _meta.mcp.tool. */
137
153
  function metaToolName(meta: unknown): string | undefined {
@@ -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
@@ -96,6 +96,11 @@ export interface AcpConfig {
96
96
  * recover if the server process itself has a wedged socket.
97
97
  * Env AGY_ACP_SESSION_RETRY wins over the file. */
98
98
  sessionRetryOnTimeout: boolean;
99
+ /** Lean agent mode: spawn the ACP engine with a staged lean agent file
100
+ * (default components excluded) so the model's only tool is the bridge
101
+ * MCP surface. Default false; changing it requires a pi restart (the
102
+ * agent file stages at spawn). Env AGY_ACP_LEAN_AGENT wins over the file. */
103
+ leanAgent: boolean;
99
104
  }
100
105
 
101
106
  export interface AgyConfig {
@@ -146,10 +151,11 @@ export interface AgyConfig {
146
151
  * always available. */
147
152
  patchCleanupNotified?: boolean;
148
153
  /** Consent record for the stream-json warning modal (google-antigravity/
149
- * antigravity-cli#1890: 4x custom-agent quota rate on agy 1.5.17+, and the
150
- * engine runs outside Google's sanctioned integration surface). Set when
151
- * the user explicitly keeps stream-json or switches away; absent/false
152
- * re-asks on the next TUI start. Never set by headless runs. */
154
+ * antigravity-cli#1890: the staged prompt rides `--agent`, so turns bill
155
+ * as custom-agent requests; Google weighted those at 4x quota on agy
156
+ * 1.5.17 and reverted it server-side on 2026-11-30). The modal is PAUSED
157
+ * (no call site shows it), so this flag is written by nothing today and
158
+ * kept only for the rewire. */
153
159
  streamJsonAcknowledged?: boolean;
154
160
  /** config.json values that were present but unparseable and fell back or
155
161
  * failed closed (issue #23). Surfaced by /agy doctor; undefined when
@@ -159,10 +165,13 @@ export interface AgyConfig {
159
165
  * Absent = agy's default agent. ACP turns ignore it (no protocol slot). */
160
166
  agent?: string;
161
167
  /** Which pi tools the MCP bridge exposes to agy: "none" (bridge off),
162
- * "all" (every registered non-builtin tool incl. other Ask* delegations;
168
+ * "all" (every registered non-core-builtin tool incl. other Ask*
169
+ * delegations; pi 1.x builtin MCP/discovery tools ride the proxied pair on
170
+ * both engines, and ACP declares the seven default builtins directly;
163
171
  * default - users expect the bridge working out of the box, and the
164
172
  * "mcp" surface serves an empty catalog on installs without
165
- * pi-mcp-adapter), "mcp" (pi-mcp-adapter tools + skills bridge only). */
173
+ * pi-mcp-adapter), "mcp" (pi-mcp-adapter tools, pi 1.x builtin MCP and
174
+ * tool_search tools + skills bridge only). */
166
175
  bridgeTools: BridgeTools;
167
176
  /** Extra pi tool names that get the long (120s) synchronous escalation
168
177
  * window, in addition to delegation-shaped names (subagent_run,
@@ -247,6 +256,7 @@ const DEFAULTS: AgyConfig = {
247
256
  usageEstimate: "estimate",
248
257
  sessionTimeoutMs: 20_000,
249
258
  sessionRetryOnTimeout: false,
259
+ leanAgent: false,
250
260
  },
251
261
  };
252
262
 
@@ -521,7 +531,16 @@ export function loadConfig(configFile: string = configPath()): AgyConfig {
521
531
  const sessionRetryOnTimeout = envSessionRetry !== undefined
522
532
  ? ["1", "true", "on"].includes(envSessionRetry.toLowerCase())
523
533
  : parseBoolish(fileAcp.sessionRetryOnTimeout, "acp.sessionRetryOnTimeout", DEFAULTS.acp.sessionRetryOnTimeout, parseWarnings);
524
- const acp: AcpConfig = { usageEstimate, sessionTimeoutMs, sessionRetryOnTimeout };
534
+ const envLeanRaw = process.env.AGY_ACP_LEAN_AGENT;
535
+ const leanAgent =
536
+ envLeanRaw === undefined
537
+ ? parseBoolish(fileAcp.leanAgent, "acp.leanAgent", DEFAULTS.acp.leanAgent, parseWarnings)
538
+ : (parseBoolishLiteral(envLeanRaw) ?? (() => {
539
+ // Issue #23 convention: junk falls back to the default AND warns.
540
+ parseWarnings.push(`AGY_ACP_LEAN_AGENT: ${JSON.stringify(envLeanRaw)} is not a recognized boolean (true/false, on/off, 1/0); using default ${DEFAULTS.acp.leanAgent}`);
541
+ return DEFAULTS.acp.leanAgent;
542
+ })());
543
+ const acp: AcpConfig = { usageEstimate, sessionTimeoutMs, sessionRetryOnTimeout, leanAgent };
525
544
 
526
545
  // Custom agent for stream-json turns (--agent). Env wins over the file
527
546
  // (same pattern as mode). Normalized (trim/cap/control-strip); an empty
@@ -597,6 +616,10 @@ export function saveConfig(patch: ConfigPatch, configFile: string = configPath()
597
616
  patchAcp?.sessionRetryOnTimeout
598
617
  ?? parseBoolishLiteral(fileAcp.sessionRetryOnTimeout)
599
618
  ?? DEFAULTS.acp.sessionRetryOnTimeout,
619
+ leanAgent:
620
+ patchAcp?.leanAgent
621
+ ?? parseBoolishLiteral(fileAcp.leanAgent)
622
+ ?? DEFAULTS.acp.leanAgent,
600
623
  };
601
624
  // The DEFAULTS 0 is a load-time placeholder (defaultTurnTimeoutMin resolves
602
625
  // per TTY state); persisting it would flip absence into "cap disabled"
@@ -85,21 +85,24 @@ export function engineSettingsRow(engine: Engine): DialogRow {
85
85
  };
86
86
  }
87
87
 
88
- /** Consent gate for the stream-json engine (google-antigravity/antigravity-cli#1890):
89
- * the staged carrier rides `--agent`, so on agy 1.5.17+ its turns bill at
90
- * Google's custom-agent quota rate, and the engine is not a sanctioned
91
- * third-party integration surface (clause 6 of the Antigravity terms).
92
- * The modal offers the switch to acp and records an explicit keep; esc
93
- * decides later (re-asks next TUI start, same contract as the picker). */
88
+ /** Consent gate for the stream-json engine (google-antigravity/antigravity-cli#1890).
89
+ *
90
+ * PAUSED, no call site shows the modal. Google weighted custom-agent
91
+ * requests at 4x quota from agy 1.5.17 and reverted it server-side on
92
+ * 2026-11-30; the vendor said it will look for other ways to curb abuse,
93
+ * so the rate can move again without notice. Kept dormant on purpose: this
94
+ * is the ready response if it does. Rewire by restoring the four call sites
95
+ * in extensions/index.ts (first-run picker, session_start, /agy engine
96
+ * stream-json, the settings row). */
94
97
  export const STREAM_JSON_WARNING_INTRO = [
95
- "The stream-json engine stages your system prompt as a custom --agent file. On agy 1.5.17 and later those turns bill at the custom-agent quota rate: 4× Gemini quota per token (google-antigravity/antigravity-cli#1890, closed as intentional).",
98
+ "The stream-json engine stages your system prompt as a custom --agent file, so its turns bill as custom-agent requests. Google charged those at 4× Gemini quota per token from agy 1.5.17 until it reverted the change server-side on 2026-11-30 (google-antigravity/antigravity-cli#1890), and said it will look for other ways to curb abuse.",
96
99
  "",
97
- "It is also not a Google-documented integration path for third-party clients. ACP (agy acp) is the documented, standard-rate path.",
100
+ "It is also not a Google-documented integration path for third-party clients. ACP (agy acp) is the documented path.",
98
101
  ].join("\n");
99
102
 
100
103
  export const SHOW_STREAM_JSON_WARNING_ITEMS: ChoiceOption[] = [
101
104
  { value: "acp", label: "Switch to ACP (recommended)", description: "standard rate · Google's documented surface" },
102
- { value: "keep", label: "Keep stream-json", description: "4× quota rate on agy 1.5.17+" },
105
+ { value: "keep", label: "Keep stream-json", description: "custom-agent rate · can change without notice" },
103
106
  ];
104
107
 
105
108
  /** True when the engine in play is stream-json and the user has not yet made
@@ -111,7 +114,7 @@ export function shouldWarnStreamJson(engine: Engine, streamJsonAcknowledged?: bo
111
114
  /** One-line copy for surfaces without the modal (headless /agy engine) and
112
115
  * for the keep verdict's toast. */
113
116
  export function streamJsonKeptMessage(): string {
114
- return "stream-json selected: turns bill at the 4× custom-agent quota rate on agy 1.5.17+ and this is not a Google-documented integration path (google-antigravity/antigravity-cli#1890).";
117
+ return "stream-json selected: turns bill as custom-agent requests and this is not a Google-documented integration path (google-antigravity/antigravity-cli#1890).";
115
118
  }
116
119
 
117
120
  /** The saveConfig patch for an engine choice that went through the gate: the
@@ -0,0 +1,134 @@
1
+ // Lean ACP agent (off by default, config.acp.leanAgent): stage a minimal
2
+ // custom agent into the isolated agy home so the spawned engine runs with
3
+ // agy's default components excluded — the model's only tool becomes the
4
+ // generic call_mcp_tool wrapper reaching the bridge MCP server, instead of
5
+ // agy's full native tool set and default prompt (~19k tokens).
6
+ //
7
+ // Probe-verified on agy 1.5.22 (2026-12-02):
8
+ // - the frontmatter below yields the lean surface (689 input tokens vs
9
+ // ~19,300 default); ANY tools key — top-level or nested in an mcpServers
10
+ // entry — resurrects the default component set or invalidates the file;
11
+ // - the mcpServers entry needs only the server NAME: session/new carries the
12
+ // url and the credential header;
13
+ // - the agent file must exist before the agy process spawns (an unknown
14
+ // --agent name makes session/new hang);
15
+ // - agent files staged INSIDE the --gemini-dir home are discovered, so the
16
+ // lean agent never lands in the user's global agents dir.
17
+
18
+ import fs from "node:fs";
19
+ import os from "node:os";
20
+ import path from "node:path";
21
+
22
+ export const LEAN_AGENT_NAME = "pi-bridge-lean";
23
+
24
+ /** pi's seven default builtins, the direct-call surface under bridgeTools
25
+ * "all" on ACP (mirrors bridge-catalog PI_DEFAULT_TOOLS; kept in sync by
26
+ * the catalog tests). */
27
+ const DIRECT_TOOL_NAMES = ["read", "bash", "edit", "write", "grep", "find", "ls"] as const;
28
+
29
+ export interface LeanAgentTool {
30
+ name: string;
31
+ description?: string;
32
+ }
33
+
34
+ /** Body for the lean agent file, derived from the LIVE authorized bridge
35
+ * catalog at spawn time: the three runtime shapes (codemode bridged /
36
+ * defaults bridged / pair only) each get the protocol their surface needs.
37
+ * The default-agent prompt notes cannot serve here: they claim typed
38
+ * per-tool surfaces a lean agent never has. */
39
+ export function leanAgentBody({ tools }: { tools: ReadonlyArray<LeanAgentTool> }): string {
40
+ const available = new Set(tools.map((t) => t.name));
41
+ const direct = DIRECT_TOOL_NAMES.filter((n) => available.has(n));
42
+ const parts: string[] = [
43
+ 'You run embedded in pi as a lean agent: your only tool is call_mcp_tool, and it reaches exactly one MCP server, "pi-bridge" (the pi extension bridge).',
44
+ 'Call it with ServerName "pi-bridge", ToolName set to the pi tool name, and Arguments set to that tool\'s arguments object.',
45
+ ];
46
+ if (direct.length > 0) {
47
+ parts.push(`Direct pi tools, call by ToolName with their arguments: ${direct.join(", ")}.`);
48
+ }
49
+ if (available.has("codemode")) {
50
+ parts.push(
51
+ 'All pi tool work runs through ToolName "codemode": Arguments {"code": "<JavaScript source>"}. Scripts run pi-side as the body of an async function: top-level await and return work; call pi tools as tools.<name>(args) (tools.read, tools.bash, tools.edit, tools.write, tools.grep, tools.find, tools.ls, plus every extension tool); ALL_TOOLS lists every callable tool and searchTools("<query>") ranks them. Batch related steps into one script instead of many calls.',
52
+ );
53
+ }
54
+ parts.push(
55
+ 'Other pi tools (extensions) are not advertised by name: call ToolName "bridge_tool_info" with Arguments {"names":["*"]} to list them, or {"names":["<tool>"]} for one tool\'s schema, then run the tool by its ToolName.',
56
+ );
57
+ parts.push(
58
+ 'When a call answers STILL RUNNING with a callId, call ToolName "bridge_poll_result" with Arguments {"callId":"<id>"} until it settles. If the poll answer tells you to stop polling and end the turn, obey it: the settled result arrives as your next message.',
59
+ );
60
+ parts.push(
61
+ "Your native task and subagent tools are not pi's: never delegate through native subagent tools, do the work yourself through the pi tools above, and keep results in your reply. The pi read tool returns image files as visible images. When you need the user's input, ask through pi's ask_user_question tool (discover it with bridge_tool_info).",
62
+ );
63
+ return `${parts.join("\n\n")}\n`;
64
+ }
65
+
66
+ /** Static frontmatter + body for the lean agent file. The mcpServers entry
67
+ * is deliberately NAME-ONLY: the bridge's session/new declaration carries
68
+ * the url and credential header; a url here would go stale per session. */
69
+ export function leanAgentMd(name: string, body: string): string {
70
+ return [
71
+ "---",
72
+ `name: ${name}`,
73
+ 'description: "pi-bridge lean agent (pi tools only)"',
74
+ "mainAgent: true",
75
+ "model: inherit",
76
+ "subagent: false",
77
+ "agents: []",
78
+ "excludeDefaultComponents: true",
79
+ "inheritCustomizations: false",
80
+ "mcpServers:",
81
+ " - name: pi-bridge",
82
+ "---",
83
+ "",
84
+ body,
85
+ ].join("\n");
86
+ }
87
+
88
+ export interface StageLeanAgentOptions {
89
+ /** The staged home (stageAgyHome output). */
90
+ stagedHome: string;
91
+ name: string;
92
+ body: string;
93
+ /** Override for tests; defaults to ~/.gemini. */
94
+ geminiHome?: string;
95
+ }
96
+
97
+ /** Write the lean agent INSIDE the staged home. stageAgyHome junctions the
98
+ * global agents dir when it exists; that junction must become a REAL dir
99
+ * here (the lean agent file must not leak into the user's global agents
100
+ * dir) with the user's own agents re-linked entry by entry so they stay
101
+ * discoverable. Cleanup rides the staged-home sweep: nothing to unregister. */
102
+ export function stageLeanAgentInHome(opts: StageLeanAgentOptions): void {
103
+ const configDir = path.join(opts.stagedHome, "config");
104
+ const stagedAgents = path.join(configDir, "agents");
105
+ const globalAgents = path.join(opts.geminiHome ?? path.join(os.homedir(), ".gemini"), "config", "agents");
106
+ fs.mkdirSync(configDir, { recursive: true, mode: 0o700 });
107
+ try {
108
+ if (fs.lstatSync(stagedAgents).isSymbolicLink()) fs.unlinkSync(stagedAgents);
109
+ } catch (err) {
110
+ // ENOENT: stageAgyHome found no global agents dir, nothing was linked.
111
+ // Anything else (EPERM on a foreign junction) must fail the stage:
112
+ // writing through a live link would land in the user's global dir.
113
+ if ((err as NodeJS.ErrnoException).code !== "ENOENT") throw err;
114
+ }
115
+ fs.mkdirSync(stagedAgents, { recursive: true, mode: 0o700 });
116
+ let userEntries: fs.Dirent[] = [];
117
+ try {
118
+ userEntries = fs.readdirSync(globalAgents, { withFileTypes: true });
119
+ } catch {
120
+ // No global agents dir: nothing to preserve.
121
+ }
122
+ for (const entry of userEntries) {
123
+ // Never link our own name: the write below must land in the REAL dir
124
+ // we just created, not through a link into the user's global agent.
125
+ if (entry.name === opts.name) continue;
126
+ if (!entry.isDirectory() && !entry.isSymbolicLink()) continue;
127
+ const target = path.join(stagedAgents, entry.name);
128
+ if (fs.existsSync(target)) continue;
129
+ fs.symlinkSync(path.join(globalAgents, entry.name), target, "junction");
130
+ }
131
+ const leanDir = path.join(stagedAgents, opts.name);
132
+ fs.mkdirSync(leanDir, { recursive: true, mode: 0o700 });
133
+ fs.writeFileSync(path.join(leanDir, "agent.md"), leanAgentMd(opts.name, opts.body), { mode: 0o600 });
134
+ }
@@ -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
+ }