@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/CHANGELOG.md CHANGED
@@ -2,6 +2,27 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file.
4
4
 
5
+ ## [1.18.0] - 2026-12-02
6
+
7
+ ### Added
8
+
9
+ - A lean agent mode for the ACP engine (off by default): `acp.leanAgent` (env `AGY_ACP_LEAN_AGENT`, `/agy lean on|off`, and a settings row) spawns agy with a staged custom agent whose frontmatter excludes the default components, so the model's only tool is the generic `call_mcp_tool` wrapper reaching the bridge MCP server instead of agy's full native tool set and default prompt — measured ~0.6-0.9k input tokens on a trivial first turn versus ~19.3k for the default agent on agy 1.5.22. The agent file stages per spawn inside the isolated ACP home (the staged agents junction is replaced by a real dir with the user's own agents re-linked entry by entry, never the lean agent's own name), so nothing lands in the global agents dir — a user agent named `pi-bridge-lean` is never linked or overwritten — and cleanup rides the staged-home sweep; the mcpServers entry carries only the server name because session/new supplies the url and credential header. The agent body is generated from the live bridge catalog at spawn: under `bridgeTools: "codemode"` it teaches the script path (one visible tool; scripts reach everything pi-side), under `"all"` it names the seven direct builtins plus the discovery pair, and it always teaches the STILL RUNNING poll discipline. Every provider prompt note asserts a typed per-tool surface a lean agent never has, so notes are suppressed in lean mode and the agent body is the sole protocol source. The `call_mcp_tool` frames the lean model produces (`{ServerName, ToolName, Arguments}`) are unwrapped in the ACP event mapping, so the pi-bridge display filter, poll folding and round-trip tracking keep working; `bridge_tool_info` serves the full authorized catalog under lean (typed per-tool definitions never reach the model). Session keys gain an `@lean` marker so flipping the setting never resumes a conversation recorded under the other agent mode. Caveats: verified on agy 1.5.22; `manage_task`, `list_resources` and `read_resource` stay model-visible above the bridge surface (agy keeps them under exclusion); changing the setting requires a pi restart (the agent file stages at spawn, and an unknown `--agent` name hangs session/new); lean is ACP-only — the stream-json carrier deliberately keeps agy defaults.
10
+
11
+ ## [1.17.3] - 2026-12-02
12
+
13
+ ### Fixed
14
+
15
+ - The stream-json consent modal is paused: no path shows it any more. The warning was built on one fact, and that fact is gone: Google weighted custom-agent turns at 4x Gemini quota per token on agy 1.5.17 and then reverted the change server-side on 2026-11-30, before the modal shipped in 1.17.0. A reproduction on agy 1.5.20 measured the same quota rate for a custom agent and the default agent, and the vendor confirmed the revert. The modal therefore asked users to consent to a cost that was not being charged, on the first-run picker, at session_start, on `/agy engine stream-json` and on the settings row: all four call sites are unwired, and the copy no longer states a 4x rate as current. The gate itself (the modal, the copy, the `streamJsonAcknowledged` config flag) is kept, not deleted: the vendor said it will look for other ways to curb abuse, so a reweighting can return without notice, and the rewire is four call sites plus a copy update. The copy now states the history (weighted on 1.5.17, reverted on 2026-11-30) instead of a live rate, and the docs match. Users on stream-json see no change in behavior; users who had not answered the old modal are not asked again.
16
+
17
+ ## [1.17.2] - 2026-11-30
18
+
19
+ ### Fixed
20
+
21
+ - 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.
22
+ - 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.
23
+
24
+ - 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.
25
+
5
26
  ## [1.17.1] - 2026-11-29
6
27
 
7
28
  ### Fixed
package/README.md CHANGED
@@ -16,9 +16,9 @@ Multi-turn works. The provider binds a pi session to an agy conversation id (per
16
16
  Turns run through one of two engines behind the same provider surface (`config.engine`, default `acp`):
17
17
 
18
18
  - **acp** (default): the ACP server built into the `agy` CLI (`agy acp`), JSON-RPC 2.0 over stdio. Verified live on agy 1.5.3: text streaming, exact token usage, multi-turn resume via `session/load`, bridge tools, separate model/thinking options, and notification-based cancellation. Client-side usage estimates remain as a fallback if the server omits usage.
19
- - **stream-json** (fallback): the persistent `agy` CLI process. Live token usage; conversation resume via `--conversation`. On agy 1.5.17 and later, its turns bill at the custom-agent quota rate (4× Gemini quota per token): the staged system prompt goes through `--agent`, and the higher rate is vendor-intentional ([google-antigravity/antigravity-cli#1890](https://github.com/google-antigravity/antigravity-cli/issues/1890)). The acp engine never passes `--agent` and keeps the standard rate.
19
+ - **stream-json** (fallback): the persistent `agy` CLI process. Live token usage; conversation resume via `--conversation`. Its turns go through `--agent` (the staged system prompt), so they bill as custom-agent requests. Google weighted those at 4× Gemini quota per token on agy 1.5.17 and reverted the change server-side on 2026-11-30 ([google-antigravity/antigravity-cli#1890](https://github.com/google-antigravity/antigravity-cli/issues/1890)); the vendor said it will look for other ways to curb abuse, so check `/usage` before trusting a quota assumption. The acp engine never passes `--agent`.
20
20
 
21
- The choice of engine is left to the user: a first-run picker asks once on a fresh install (acp preselected; `esc` defers), and `/agy engine` reopens it anytime. Selecting stream-json anywhere (first-run picker, `/agy engine`, settings row) shows a one-time warning modal first; keeping it records the acknowledgment and the warning never re-asks, esc decides later. Both engines use the same `agy` installation and cached Google credentials. A restart applies an engine switch. Sessions are engine-scoped, so switching engines never crosses conversations.
21
+ The choice of engine is left to the user: a first-run picker asks once on a fresh install (acp preselected; `esc` defers), and `/agy engine` reopens it anytime. Both engines use the same `agy` installation and cached Google credentials. A restart applies an engine switch. Sessions are engine-scoped, so switching engines never crosses conversations.
22
22
 
23
23
  Full capability comparison, switching, and setup/auth details: [docs/ENGINES.md](docs/ENGINES.md). Existing installs remove only old ACP builds with managed-install evidence under the bridge's old install root. Unmarked binaries and unrelated files stay untouched. Retired standalone credentials are reported for manual removal, never deleted automatically.
24
24
 
@@ -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` |
@@ -130,6 +130,7 @@ If `agy models` fails at load (binary missing, auth not done, network stall), a
130
130
  | `inactivityTimeoutMin` | Silence cap, minutes, both engines: no stream-json stdout / no ACP session/update for this long fails the turn as a stall. `0` disables the guard. Parks (bridge calls, escalated calls, ACP permission dialogs) pause it; agy-native long steps such as builds do not. A false kill costs the whole turn, and on stream-json a stall kill with no result frame clears the conversation binding. Keep `5`; use `2`-`3` only when native steps are known to be short; do not use `1` | `5` |
131
131
  | `acp.sessionTimeoutMs` | Timeout in ms for ACP `session/new`, `session/load`, `session/set_config_option`, and `session/close`. Valid range: `1000`-`300000`. Raise only on slow or proxied networks | `20000` |
132
132
  | `acp.sessionRetryOnTimeout` | Advanced: transparently retry `session/new` once when it times out while `agy acp` is still alive. **Warning:** doubles total wait time on dead networks and may not recover if `agy`'s internal socket is wedged | `false` |
133
+ | `acp.leanAgent` | Lean agent mode for the ACP engine: spawns agy with a staged custom agent that excludes the default components, so the model's only tool is the generic `call_mcp_tool` wrapper reaching the bridge MCP server — no native read/command/subagent tools and a much smaller first-turn context (measured ~0.6-0.9k vs ~19.3k input tokens on agy 1.5.22). The agent body is generated from the live bridge catalog at spawn: under `bridgeTools: "codemode"` the model works through one codemode script tool; under `"all"` the seven pi builtins are callable by name and extension tools via `bridge_tool_info`. The agent file stages inside the isolated ACP home per spawn (nothing lands in the global agents dir; a global agent named `pi-bridge-lean` is never touched); the tool protocol rides the agent body (all provider prompt notes are suppressed); session keys gain an `@lean` marker so a flip starts a fresh conversation. Restart applies; bridge-surface changes after a spawn (`/agy bridge`, `/agy tools`) leave the staged body stale until the next pi start. `manage_task`/`list_resources`/`read_resource` stay model-visible (agy keeps them under exclusion). ACP only | `false` |
133
134
 
134
135
  Boolean keys (`readOnly`, `skipPermissions`, `askTool`, `webTools`, `digest`, `systemPrompt`, `acp.sessionRetryOnTimeout`) take JSON booleans, the `/agy` vocabulary as strings (`on`/`off`, `1`/`0`, case and whitespace tolerated), and the JSON numbers `0`/`1`, so a hand-edited `"off"` means off instead of silently on (issue #23). Unrecognized values fall back to the key's default - `readOnly` falls closed to `true` - and surface a `config warnings:` row in `/agy doctor` plus a startup warning toast. The `AGY_*` env vars keep their own grammars: notably `AGY_SKIP_PERMISSIONS` does not accept `on` (only `1`/`true` enable there), and while an env var is set the matching file value is never parsed, so it emits no warning for the value it overrides.
135
136
 
@@ -153,6 +154,7 @@ The `activate_skill` catalog mirrors pi's directory-based skill discovery: the t
153
154
  /agy thinking low|medium|high fallback thinking tier for the AskAntigravity tool; callers may override per call
154
155
  /agy digest on|off ship pi-side context to agy when the delta is non-empty (default on; see table above)
155
156
  /agy system-prompt on|off send pi's system prompt + AGENTS.md + the Pi Bridge tool-priority note to new agy conversations (default on)
157
+ /agy lean on|off lean ACP agent: bridge MCP tools only, no native agy tools (ACP engine only; restart applies; a flip starts a fresh conversation)
156
158
  /agy bridge all|mcp|codemode|none which pi tools the MCP bridge exposes to agy (default all; codemode = scripts only; none = bridge off; a running server picks up the new catalog immediately, a stopped one on the next start)
157
159
  /agy tools [hide|show <name>|reset] session-only bridge-catalog hides (multi-word names OK; reset restores the full set; bare lists exposed + hidden; never touches saved config)
158
160
  /agy web on|off register the agy_web_search + agy_read_url pi tools for ANY provider's model (default off; applies on the next pi start or /reload; every call spawns agy and spends Antigravity quota)
@@ -195,6 +197,7 @@ For isolation when running any agent that executes commands without a confirmati
195
197
  | `AGY_SKIP_PERMISSIONS` | `1`/`true` (default) to pass `--dangerously-skip-permissions` so commands don't hang on an unanswerable prompt in `-p` mode. `0`/`false` to prompt (hangs any `run_command` non-interactively). Wins over the config file. |
196
198
  | `AGY_USAGE_ESTIMATE` | Fallback ACP token display when the server omits usage: `estimate` (default; live client-side per-delta estimates), `direct`, `off`. Exact server usage always wins. Wins over the config file. |
197
199
  | `AGY_ACP_SESSION_TIMEOUT_MS` | Timeout in ms for ACP `session/new`, `session/load`, `session/set_config_option`, and `session/close` (`1000`-`300000`, default `20000`). Wins over `config.acp.sessionTimeoutMs`. |
200
+ | `AGY_ACP_LEAN_AGENT` | `1`/`true`/`on` spawns the ACP engine with the staged lean agent: bridge MCP tools only, no native agy tools (default off; restart applies). Wins over `config.acp.leanAgent`. |
198
201
  | `AGY_ACP_SESSION_RETRY` | `1`/`true`/`on` to retry ACP `session/new` once on silent timeout while `agy acp` is alive (default off). Warning: doubles wait time on dead networks and may not clear a wedged socket. Wins over `config.acp.sessionRetryOnTimeout`. |
199
202
  | `AGY_DEFAULT_MODEL` | Default model for the `AskAntigravity` tool: `flash`/`pro`/`gemini`, or an exact id such as `gemini-4-hydrogen`. Default `gemini-4-hydrogen`; the tier suffix rides `AGY_DEFAULT_THINKING`. Wins over the config file. |
200
203
  | `AGY_DEFAULT_THINKING` | Default thinking tier for the `AskAntigravity` tool: `low`/`medium`/`high`. Anything else falls back to `medium`. Wins over the config file. |
@@ -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,
@@ -70,7 +72,7 @@ import { createAgySetupOffer } from "../src/agy-setup.js";
70
72
  import { ensureQueuedMessagesDefaults } from "../src/queued-messages.js";
71
73
  import type { TurnDriver, TurnOutcome } from "../src/driver-types.js";
72
74
  import { configPath, configWarningsMessage, loadConfig, logsDir, MAX_TURN_CAP_MIN, migrateStaleDigestDefault, parseCapMinutes, removeLegacyAcpBin, saveConfig, type AcpConfig, type AgyMode, type BridgeTools, type Engine, type ThinkingTier } from "../src/config.js";
73
- import { agyMissingMessage, ENGINE_SETTINGS_ROW_ID, engineSettingsRow, isAgyInstalled, savedEngineMessage, shouldOfferEnginePicker, shouldWarnStreamJson, showEnginePicker, showStreamJsonWarning, streamJsonKeptMessage, streamJsonSavePatch } from "../src/engine-picker.js";
75
+ import { agyMissingMessage, ENGINE_SETTINGS_ROW_ID, engineSettingsRow, isAgyInstalled, savedEngineMessage, shouldOfferEnginePicker, showEnginePicker } from "../src/engine-picker.js";
74
76
  import { agyVersionVerdict, agyUpdateMessage, checkAgyCliVersion, describeAgyVersionCheck, MIN_AGY_ACP_VERSION, MIN_AGY_VERSION, MIN_GEMINI_DIR_VERSION, probeGeminiDirFlag, resolveStreamHomeMode } from "../src/agy-version.js";
75
77
  import { isValidAgyAgentName, listAgyAgents } from "../src/agents.js";
76
78
  import { formatSubagentRoster, SubagentRoster } from "../src/subagent-roster.js";
@@ -83,6 +85,7 @@ import { showTasksBrowser } from "../src/tasks-ui.js";
83
85
  import { agyConversationDir } from "../src/agy-paths.js";
84
86
  import { armBackgroundWatch, rearmPlansFromEntries, type BackgroundWatchEntry, type BackgroundWatchHandle } from "../src/background-watch.js";
85
87
  import { redactText } from "../src/redact.js";
88
+ import { leanAgentBody, LEAN_AGENT_NAME } from "../src/lean-agent.js";
86
89
  import { createDailyLogger, type DailyLogger } from "../src/daily-log.js";
87
90
  import { registerAskAntigravityTool, toolModelsFromRaw } from "../src/ask-tool.js";
88
91
  import { registerWebTools } from "../src/web-tools.js";
@@ -161,6 +164,11 @@ export default async function (pi: ExtensionAPI): Promise<void> {
161
164
  // config reads would let a mid-session flip leave ToolRoundTrips,
162
165
  // kickIdle, and reentry pointing at the other engine (round-7 finding).
163
166
  const engine: Engine = loadConfig().engine;
167
+ // Lean agent mode, LATCHED like the engine: the spawned agy process only
168
+ // sees the flag at spawn (agent file + --agent), so every lean-dependent
169
+ // surface (notes, catalog, session keys, the driver resolver) follows
170
+ // this value, never a live config read. Changing it is restart-applies.
171
+ const leanAgent = engine === "acp" && loadConfig().acp.leanAgent;
164
172
  // Engine switching requires a restart, so the catalog-time engine read is
165
173
  // authoritative for input advertising. Both engines accept images: ACP
166
174
  // rides native content blocks; stream-json stages user attachments to
@@ -344,10 +352,31 @@ export default async function (pi: ExtensionAPI): Promise<void> {
344
352
  const level = expectedExit ? "debug" : acpFailures.has(msg) ? "warn" : msg === "turn-start" ? "info" : "debug";
345
353
  fileLog.log(msg, data, level);
346
354
  };
355
+ let leanSkippedWarned = false;
347
356
  const acpDriver = new AcpDriver({
348
357
  bin: binary,
349
358
  binArgs: ["acp"],
350
359
  isolateHome: true,
360
+ // Lean agent mode (restart-applies, but resolved per spawn so a flip
361
+ // mid-session takes effect when the driver recycles instead of
362
+ // desyncing the staged agent file from the argv): one resolution per
363
+ // spawn supplies both the --agent name and the agent body, derived
364
+ // from the live bridge catalog (leanAgentBody). Off = default agent.
365
+ leanAgent: () => {
366
+ // Latched at factory time (see the const above): the flag and the
367
+ // staged file must move together per spawn.
368
+ if (!leanAgent) return undefined;
369
+ // No bridge, no lean: the body would teach a tool surface nothing
370
+ // exposes (bridgeTools none, or the listener never started).
371
+ if (!mcpHandle || getBridgeTools().length === 0) {
372
+ if (!leanSkippedWarned) {
373
+ leanSkippedWarned = true;
374
+ fileLog.log("lean-skipped", { reason: "no bridge tools" }, "warn");
375
+ }
376
+ return undefined;
377
+ }
378
+ return { name: LEAN_AGENT_NAME, body: leanAgentBody({ tools: getBridgeTools() }) };
379
+ },
351
380
  // Resolved per turn: /agy and AGY_USAGE_ESTIMATE changes apply without
352
381
  // a restart. Without this the driver defaults to "estimate" and the
353
382
  // config knob (incl. "off") is dead.
@@ -425,7 +454,7 @@ export default async function (pi: ExtensionAPI): Promise<void> {
425
454
  // display text). The name is NOT a fallback here - it rendered "ls ls"
426
455
  // duplication whenever the event carried neither path nor command.
427
456
  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);
457
+ const detail = event?.path ? path.basename(event.path) : firstLine(event?.query) ?? firstLine(event?.command) ?? firstLine(event?.output);
429
458
  const status = event?.status === "failed" ? theme.fg("error", "✗") : theme.fg("success", "✓");
430
459
  const lines = [`${status} ${theme.fg("toolTitle", event?.name ?? "Antigravity")}${detail ? ` ${theme.fg("muted", detail.slice(0, 160))}` : ""}`];
431
460
  if (expanded) {
@@ -491,11 +520,13 @@ export default async function (pi: ExtensionAPI): Promise<void> {
491
520
  pendingNativeTools = Math.max(0, pendingNativeTools - 1);
492
521
  if (pendingNativeTools === 0) activeUi?.setStatus("agy-native", undefined);
493
522
  // Bound persisted session size; the ACP result and diff may be megabytes.
523
+ // path stays whole: the compaction fileOps (#32) fold it verbatim.
494
524
  pi.appendEntry<NativeDisplayEvent>("agy-native-event", {
495
525
  ...event,
496
526
  output: event.output?.slice(0, 4000),
497
527
  diff: event.diff?.slice(0, 12000),
498
528
  command: event.command?.slice(0, 500),
529
+ query: event.query?.slice(0, 500),
499
530
  });
500
531
  };
501
532
  // Native re-exec only emits for builtins actually active in the session;
@@ -676,13 +707,42 @@ export default async function (pi: ExtensionAPI): Promise<void> {
676
707
  backgroundWatchers.clear();
677
708
  pendingCompactionHandoff.clear();
678
709
  });
710
+ pi.on("session_before_compact", async (event) => {
711
+ try {
712
+ // Native ACP activity lives only in display entries the summarizer
713
+ // never sees; fileOps is what carries it into the summary (#32).
714
+ // Older peer builds may omit branchEntries despite the type (#32).
715
+ collectNativeFileOps(event.branchEntries ?? [], event.preparation.fileOps);
716
+ } catch (err) {
717
+ fileLog.log("native-fileops-error", { error: err instanceof Error ? err.message : String(err) }, "warn");
718
+ }
719
+ try {
720
+ // A parked turn can only be unparked by the continuation the
721
+ // summarizer itself blocks, so close it before the summary runs (#33).
722
+ const preempted = await preemptParkedTurnForCompaction(activeDriver(), roundTrips, {
723
+ log: (msg, data, level) => fileLog.log(msg, data, level ?? "info"),
724
+ });
725
+ if (preempted && activeUi) {
726
+ activeUi.notify(
727
+ "Compaction interrupted a parked agy turn; its tool results will be re-sent to the next agy conversation.",
728
+ "warning",
729
+ );
730
+ }
731
+ } catch (err) {
732
+ fileLog.log(
733
+ "compaction-preempt-error",
734
+ { error: err instanceof Error ? err.message : String(err) },
735
+ "warn",
736
+ );
737
+ }
738
+ });
679
739
  pi.on("session_compact", (_event, ctx) => {
680
740
  try {
681
741
  // Shape-cast as in model_select below: tolerate pi builds whose dts
682
742
  // omits getSessionId.
683
743
  const sm = ctx.sessionManager as { getSessionId?: () => string };
684
744
  const sid = sm.getSessionId?.();
685
- const key = sessionKey(sid ? { sessionId: sid } : undefined, ctx.cwd, engine);
745
+ const key = sessionKey(sid ? { sessionId: sid } : undefined, ctx.cwd, engine, leanAgent);
686
746
  const rotated = rotateSessionOnCompaction(store, key, pendingCompactionHandoff);
687
747
  if (rotated) {
688
748
  fileLog.log("session-compact-rotate", { key, previousConversation: rotated }, "info");
@@ -705,7 +765,7 @@ export default async function (pi: ExtensionAPI): Promise<void> {
705
765
  // builds whose dts omits getSessionId.
706
766
  const sm = ctx.sessionManager as { getSessionId?: () => string };
707
767
  const sid = sm.getSessionId?.();
708
- const key = sessionKey(sid ? { sessionId: sid } : undefined, ctx.cwd, engine);
768
+ const key = sessionKey(sid ? { sessionId: sid } : undefined, ctx.cwd, engine, leanAgent);
709
769
  return store.get(key) !== null;
710
770
  })(),
711
771
  hasContext: ctx.sessionManager
@@ -732,6 +792,7 @@ export default async function (pi: ExtensionAPI): Promise<void> {
732
792
  pendingCompactionHandoff,
733
793
  hasActiveTool: (name) => pi.getActiveTools().includes(name),
734
794
  engine,
795
+ leanAgent,
735
796
  log: fileLog.log.bind(fileLog),
736
797
  });
737
798
 
@@ -898,63 +959,15 @@ export default async function (pi: ExtensionAPI): Promise<void> {
898
959
  try {
899
960
  const picked = await showEnginePicker(ctx.ui);
900
961
  if (picked) {
901
- // Consent gate: a first-run stream-json pick gets the same
902
- // warning as every other path before it persists anything.
903
- let chosen: Engine | undefined = picked;
904
- if (picked === "stream-json") {
905
- const verdict = await showStreamJsonWarning(ctx.ui);
906
- if (verdict === undefined) {
907
- // Decide later: nothing persisted, this session runs the
908
- // acp default, the picker re-asks next start.
909
- ctx.ui.notify("Stream-json not confirmed; this session runs the acp default. Decide later with /agy engine.", "info");
910
- chosen = undefined;
911
- } else {
912
- chosen = verdict === "acp" ? "acp" : "stream-json";
913
- if (chosen === "stream-json") ctx.ui.notify(streamJsonKeptMessage(), "warning");
914
- }
915
- }
916
- if (chosen) {
917
- setupEngine = chosen;
918
- saveConfig(streamJsonSavePatch(chosen, chosen === "stream-json"));
919
- ctx.ui.notify(savedEngineMessage(chosen), "info");
920
- }
962
+ setupEngine = picked;
963
+ saveConfig({ engine: picked });
964
+ ctx.ui.notify(savedEngineMessage(picked), "info");
921
965
  }
922
966
  } catch (err) {
923
967
  fileLog.log("engine-picker", { error: String(err) }, "warn");
924
968
  console.error(`[antigravity-bridge] engine picker failed: ${String(err)}`);
925
969
  }
926
970
  }
927
- // stream-json consent migration (google-antigravity/antigravity-cli#1890):
928
- // existing installs resolved to stream-json (the legacy silent fallback or
929
- // an old explicit choice) see the warning once; esc re-asks next start,
930
- // exactly like the first-run picker. AGY_ENGINE=stream-json skips the
931
- // modal: typing the env var is the explicit act. The switch persists for
932
- // the next start (drivers wire at load), like /agy engine.
933
- try {
934
- const cfg = loadConfig();
935
- if (
936
- (event.reason === "startup" || event.reason === "resume") &&
937
- ctx.mode === "tui" &&
938
- process.env.AGY_ENGINE === undefined &&
939
- shouldWarnStreamJson(cfg.engine, cfg.streamJsonAcknowledged)
940
- ) {
941
- const verdict = await showStreamJsonWarning(ctx.ui);
942
- if (verdict === "keep") {
943
- saveConfig(streamJsonSavePatch("stream-json", true));
944
- ctx.ui.notify(streamJsonKeptMessage(), "warning");
945
- } else if (verdict === "acp" && loadConfig().mode !== "plan") {
946
- saveConfig(streamJsonSavePatch("acp", true));
947
- ctx.ui.notify(savedEngineMessage("acp"), "info");
948
- } else if (verdict === "acp") {
949
- // Plan mode blocks ACP: refuse without persisting so the
950
- // modal re-asks once the mode allows the switch.
951
- ctx.ui.notify("mode is plan; provider plan turns are disabled on ACP. /agy mode accept-edits first.", "warning");
952
- }
953
- }
954
- } catch (err) {
955
- fileLog.log("streamjson-warning", { error: String(err) }, "warn");
956
- console.error(`[antigravity-bridge] stream-json warning failed: ${String(err)}`);
957
- }
958
971
  // The retired acp.bin key heals itself in the config file; the env var
959
972
  // lives outside our reach, so it is the only case that still warns.
960
973
  // Independent once-flags: a failed cleanup must never suppress the
@@ -1112,7 +1125,7 @@ export default async function (pi: ExtensionAPI): Promise<void> {
1112
1125
  inputSchema: serializeToolSchema(t.parameters),
1113
1126
  }));
1114
1127
  const tools = directDefs;
1115
- const proxiedForInfo = codemode ? codemode.proxied : proxied;
1128
+ const proxiedForInfo = leanAgent ? authorized : codemode ? codemode.proxied : proxied;
1116
1129
  if (mode !== "none" && proxiedForInfo.length > 0) {
1117
1130
  tools.push(bridgeToolInfoDef(proxiedForInfo), bridgeCallToolDef());
1118
1131
  }
@@ -1154,8 +1167,8 @@ export default async function (pi: ExtensionAPI): Promise<void> {
1154
1167
  return answerPoll(roundTrips, wanted, signal, mcpLog);
1155
1168
  }
1156
1169
  if (name === TOOL_INFO_TOOL_NAME) {
1157
- const { proxied } = partitionBridgeTools(getBridgeTools());
1158
- return Promise.resolve(formatBridgeToolInfo(proxied, args.names));
1170
+ const authorized = getBridgeTools();
1171
+ return Promise.resolve(formatBridgeToolInfo(leanAgent ? authorized : partitionBridgeTools(authorized).proxied, args.names));
1159
1172
  }
1160
1173
  const dispatchPiTool = (targetName: string, targetArgs: Record<string, unknown>) =>
1161
1174
  roundTrips.onToolCall(callId, targetName, targetArgs, signal).then((r) => {
@@ -1454,6 +1467,7 @@ function settingsRows(ctx: AgyCommandCtx): string[] {
1454
1467
  row("AskAntigravity model:", config.defaultModel),
1455
1468
  row("AskAntigravity thinking:", config.defaultThinking),
1456
1469
  row("bridge tools:", config.bridgeTools),
1470
+ row("lean agent:", config.engine === "acp" ? (config.acp.leanAgent ? "on (restart applies to flip)" : "off") : "off (ACP engine only)"),
1457
1471
  row("digest:", config.digest ? "on" : "off"),
1458
1472
  row("system prompt:", config.systemPrompt ? "on" : "off"),
1459
1473
  // issue #23: unparseable hand-edited values must not fail silently.
@@ -1472,7 +1486,7 @@ function statusText(ctx: AgyCommandCtx): string {
1472
1486
  ` sessions: ${ctx.store.size} bound`,
1473
1487
  ` config: ${configPath()}`,
1474
1488
  "",
1475
- "Subcommands: /agy auth, /agy auth-manual, /agy engine stream-json|acp, /agy mode plan|accept-edits, /agy readonly on|off, /agy permissions on|off, /agy ask on|off, /agy model <alias>, /agy thinking low|medium|high|xhigh, /agy agent <name|off>, /agy subagents, /agy quota, /agy artifacts [open <n|name>], /agy tasks [tail <id>], /agy bridge all|mcp|codemode|none, /agy tools [hide|show <name>|reset], /agy web on|off, /agy digest on|off, /agy system-prompt on|off, /agy timeout <1-1440|off>, /agy patch-cleanup, /agy clear, /agy doctor",
1489
+ "Subcommands: /agy auth, /agy auth-manual, /agy engine stream-json|acp, /agy mode plan|accept-edits, /agy readonly on|off, /agy permissions on|off, /agy ask on|off, /agy model <alias>, /agy thinking low|medium|high|xhigh, /agy agent <name|off>, /agy subagents, /agy quota, /agy artifacts [open <n|name>], /agy tasks [tail <id>], /agy bridge all|mcp|codemode|none, /agy lean on|off, /agy tools [hide|show <name>|reset], /agy web on|off, /agy digest on|off, /agy system-prompt on|off, /agy timeout <1-1440|off>, /agy patch-cleanup, /agy clear, /agy doctor",
1476
1490
  ].join("\n");
1477
1491
  }
1478
1492
 
@@ -1480,7 +1494,7 @@ function statusText(ctx: AgyCommandCtx): string {
1480
1494
  function registerAgyCommand(pi: ExtensionAPI, ctx: AgyCommandCtx): void {
1481
1495
  pi.registerCommand("agy", {
1482
1496
  description:
1483
- "Antigravity provider: doctor (health + settings), settings picker, clear sessions. Usage: /agy [doctor|auth|auth-manual|engine stream-json|acp|mode plan|accept-edits|readonly on|off|permissions on|off|ask on|off|model <alias>|thinking low|medium|high|xhigh|agent <name|off>|subagents|quota|artifacts [open <n|name>]|tasks [tail <id>]|bridge all|mcp|codemode|none|tools [hide|show <name>|reset]|web on|off|digest on|off|system-prompt on|off|timeout <1-1440|off>|patch-cleanup|clear]",
1497
+ "Antigravity provider: doctor (health + settings), settings picker, clear sessions. Usage: /agy [doctor|auth|auth-manual|engine stream-json|acp|mode plan|accept-edits|readonly on|off|permissions on|off|ask on|off|model <alias>|thinking low|medium|high|xhigh|agent <name|off>|subagents|quota|artifacts [open <n|name>]|tasks [tail <id>]|bridge all|mcp|codemode|none|lean on|off|tools [hide|show <name>|reset]|web on|off|digest on|off|system-prompt on|off|timeout <1-1440|off>|patch-cleanup|clear]",
1484
1498
  handler: async (args, cmdCtx: ExtensionCommandContext) => {
1485
1499
  const ui = cmdCtx.ui;
1486
1500
  if (ui) ctx.setActiveUi(ui);
@@ -1549,30 +1563,7 @@ function registerAgyCommand(pi: ExtensionAPI, ctx: AgyCommandCtx): void {
1549
1563
  ui?.notify("mode is plan; provider plan turns are disabled on ACP. /agy mode accept-edits first.", "warning");
1550
1564
  return;
1551
1565
  }
1552
- // Consent gate (google-antigravity/antigravity-cli#1890): the
1553
- // TUI warning modal runs once, before stream-json ever takes
1554
- // effect. Headless has no modal surface: apply with the
1555
- // one-line notice instead.
1556
- let engineChoice: "acp" | "stream-json" = val;
1557
- let warned = false;
1558
- if (engineChoice === "stream-json" && shouldWarnStreamJson("stream-json", loadConfig().streamJsonAcknowledged)) {
1559
- if (!ui || mode !== "tui") {
1560
- ui?.notify(streamJsonKeptMessage(), "warning");
1561
- } else {
1562
- const verdict = await showStreamJsonWarning(ui);
1563
- if (verdict === undefined) {
1564
- ui.notify(`engine unchanged: ${loadConfig().engine}.`, "info");
1565
- return;
1566
- }
1567
- if (verdict === "acp" && loadConfig().mode === "plan") {
1568
- ui.notify("mode is plan; provider plan turns are disabled on ACP. /agy mode accept-edits first.", "warning");
1569
- return;
1570
- }
1571
- engineChoice = verdict === "acp" ? "acp" : "stream-json";
1572
- warned = true;
1573
- }
1574
- }
1575
- const next = saveConfig(streamJsonSavePatch(engineChoice, warned));
1566
+ const next = saveConfig({ engine: val });
1576
1567
  if (next.engine !== "acp") {
1577
1568
  ui?.notify("engine set to stream-json. Takes effect on the next pi start (or /reload).", "info");
1578
1569
  return;
@@ -1955,7 +1946,7 @@ function registerAgyCommand(pi: ExtensionAPI, ctx: AgyCommandCtx): void {
1955
1946
  );
1956
1947
  }
1957
1948
  } 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");
1949
+ 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
1950
  }
1960
1951
  return;
1961
1952
  }
@@ -2043,6 +2034,24 @@ function registerAgyCommand(pi: ExtensionAPI, ctx: AgyCommandCtx): void {
2043
2034
  return;
2044
2035
  }
2045
2036
 
2037
+ if (sub === "lean") {
2038
+ if (val === "on" || val === "off") {
2039
+ const next = saveConfig({ acp: { leanAgent: val === "on" } });
2040
+ ui?.notify(
2041
+ next.acp.leanAgent
2042
+ ? "lean on (ACP engine only). The spawned agent runs with the default components excluded: no native file/command/subagent tools, the bridge MCP surface only. Changing it requires a pi restart; a flip starts a fresh conversation."
2043
+ : "lean off. The spawned agent uses the default components. Changing it requires a pi restart; a flip starts a fresh conversation.",
2044
+ "info",
2045
+ );
2046
+ if (next.acp.leanAgent && ctx.engine !== "acp") {
2047
+ ui?.notify("lean is an ACP-engine setting and the active engine is stream-json: the flag is stored but inert until the engine switches.", "warning");
2048
+ }
2049
+ } else {
2050
+ ui?.notify(`lean: ${loadConfig().acp.leanAgent ? "on" : "off"} (ACP engine only)\nusage: /agy lean on|off — runs the spawned agent with the default components excluded (bridge MCP tools only). Restart applies.`, "info");
2051
+ }
2052
+ return;
2053
+ }
2054
+
2046
2055
  if (sub === "thinking") {
2047
2056
  if (val === "low" || val === "medium" || val === "high" || val === "xhigh") {
2048
2057
  const next = saveConfig({ defaultThinking: val as ThinkingTier });
@@ -2144,7 +2153,7 @@ async function openAgyPicker(ui: ExtensionUIContext, ctx: AgyCommandCtx): Promis
2144
2153
  id: "bridge",
2145
2154
  label: "Bridge tools",
2146
2155
  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).",
2156
+ "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
2157
  currentValue: config.bridgeTools,
2149
2158
  values: ["all", "mcp", "codemode", "none"],
2150
2159
  },
@@ -2188,6 +2197,14 @@ async function openAgyPicker(ui: ExtensionUIContext, ctx: AgyCommandCtx): Promis
2188
2197
  currentValue: config.acp.sessionRetryOnTimeout ? "on" : "off",
2189
2198
  values: ["off", "on"],
2190
2199
  },
2200
+ {
2201
+ id: "acp-lean-agent",
2202
+ label: "ACP lean agent",
2203
+ description:
2204
+ "ACP engine only. Spawn agy with a staged lean agent: default components excluded, no native file/command/subagent tools, the bridge MCP surface only (a much smaller first-turn context). Tool protocol rides the agent body; prompt notes are suppressed. Restart applies; a flip starts a fresh conversation. Bridge-surface changes after a spawn (/agy bridge, /agy tools) leave the staged body stale until the next pi start.",
2205
+ currentValue: config.acp.leanAgent ? "on" : "off",
2206
+ values: ["off", "on"],
2207
+ },
2191
2208
  ];
2192
2209
 
2193
2210
  const resolved = await ui.custom<string | undefined>(
@@ -2233,6 +2250,11 @@ async function openAgyPicker(ui: ExtensionUIContext, ctx: AgyCommandCtx): Promis
2233
2250
  ...pending.acp,
2234
2251
  sessionRetryOnTimeout: newValue === "on",
2235
2252
  };
2253
+ } else if (id === "acp-lean-agent") {
2254
+ pending.acp = {
2255
+ ...pending.acp,
2256
+ leanAgent: newValue === "on",
2257
+ };
2236
2258
  }
2237
2259
  },
2238
2260
  },
@@ -2289,6 +2311,7 @@ async function openAgyPicker(ui: ExtensionUIContext, ctx: AgyCommandCtx): Promis
2289
2311
  pending.acp?.sessionRetryOnTimeout !== undefined
2290
2312
  ? `ACP session/new retry=${next.acp.sessionRetryOnTimeout ? "on" : "off"}`
2291
2313
  : null,
2314
+ pending.acp?.leanAgent !== undefined ? `ACP lean agent=${next.acp.leanAgent ? "on" : "off"} (restart applies)` : null,
2292
2315
  ]
2293
2316
  .filter(Boolean)
2294
2317
  .join(", ");
@@ -2308,7 +2331,7 @@ async function openAgyPicker(ui: ExtensionUIContext, ctx: AgyCommandCtx): Promis
2308
2331
  * same semantics: plan blocks acp and restart applies the switch. */
2309
2332
  async function runEngineModal(ui: ExtensionUIContext, ctx: AgyCommandCtx): Promise<void> {
2310
2333
  const current = loadConfig().engine;
2311
- let picked = await showEnginePicker(ui);
2334
+ const picked = await showEnginePicker(ui);
2312
2335
  if (picked === undefined) {
2313
2336
  ui.notify(`engine unchanged: ${current}.`, "info");
2314
2337
  return;
@@ -2317,22 +2340,6 @@ async function runEngineModal(ui: ExtensionUIContext, ctx: AgyCommandCtx): Promi
2317
2340
  ui.notify(`engine is already ${current}. Restart applies it if set this session.`, "info");
2318
2341
  return;
2319
2342
  }
2320
- // Consent gate: picking stream-json in the picker resolves only after the
2321
- // warning; esc lands here as undefined above, so nothing is persisted.
2322
- if (picked === "stream-json" && shouldWarnStreamJson("stream-json", loadConfig().streamJsonAcknowledged)) {
2323
- const verdict = await showStreamJsonWarning(ui);
2324
- if (verdict === undefined) {
2325
- ui.notify(`engine unchanged: ${current}.`, "info");
2326
- return;
2327
- }
2328
- if (verdict === "keep") {
2329
- saveConfig({ engine: "stream-json", streamJsonAcknowledged: true });
2330
- ui.notify(streamJsonKeptMessage(), "warning");
2331
- ui.notify("Takes effect on the next pi start (or /reload).", "info");
2332
- return;
2333
- }
2334
- picked = "acp";
2335
- }
2336
2343
  if (picked === "acp" && loadConfig().mode === "plan") {
2337
2344
  ui.notify("mode is plan; provider plan turns are disabled on ACP. /agy mode accept-edits first.", "warning");
2338
2345
  return;
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.18.0",
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",
@@ -20,6 +20,7 @@ import type { AgyUsage } from "../driver-types.js";
20
20
  import { redactText } from "../redact.js";
21
21
  import { JsonRpcResponseError, JsonRpcSession, JsonRpcTimeoutError } from "./jsonrpc.js";
22
22
  import { mergeGateGroupIntoAcpHome } from "../approval-hook.js";
23
+ import { stageLeanAgentInHome } from "../lean-agent.js";
23
24
  import { removeStagedAgyHome, stageAgyHome } from "./home.js";
24
25
 
25
26
  export interface AcpMcpServer {
@@ -51,6 +52,11 @@ export interface AcpConnectionOptions {
51
52
  binArgs?: string[];
52
53
  /** Native agy only: filter per-pid bridges out of inherited global MCP. */
53
54
  isolateHome?: boolean | { geminiHome?: string; parentDir?: string };
55
+ /** Lean agent mode: stage this agent file into the isolated home and run
56
+ * agy with `--agent <name>`. Undefined = off (the default agent). The
57
+ * file must exist before spawn (an unknown --agent makes session/new
58
+ * hang), so it is staged here, never lazily. */
59
+ leanAgent?: { name: string; body: string };
54
60
  extraEnv?: Record<string, string>;
55
61
  log: (msg: string, data?: unknown) => void;
56
62
  /** Verified `session/update` payloads (post-suppression). */
@@ -184,6 +190,12 @@ export class AcpConnection {
184
190
  async start(): Promise<void> {
185
191
  if (this.#child) return;
186
192
  const args = [...(this.#opts.binArgs ?? [])];
193
+ // The lean agent file can only be staged into a home we own. Without
194
+ // isolation --agent would name a file that does not exist, and agy
195
+ // hangs session/new forever on an unknown agent (fail closed instead).
196
+ if (this.#opts.leanAgent && !this.#opts.isolateHome) {
197
+ throw new Error("lean agent mode requires an isolated home (isolateHome)");
198
+ }
187
199
  if (this.#opts.isolateHome) {
188
200
  this.#stagedHome = stageAgyHome(typeof this.#opts.isolateHome === "object" ? this.#opts.isolateHome : {});
189
201
  // Deliver this session's approval gate group into the staged home:
@@ -197,6 +209,19 @@ export class AcpConnection {
197
209
  this.#releaseHome();
198
210
  throw err;
199
211
  }
212
+ if (this.#opts.leanAgent) {
213
+ try {
214
+ stageLeanAgentInHome({
215
+ stagedHome: this.#stagedHome,
216
+ name: this.#opts.leanAgent.name,
217
+ body: this.#opts.leanAgent.body,
218
+ geminiHome: typeof this.#opts.isolateHome === "object" ? this.#opts.isolateHome.geminiHome : undefined,
219
+ });
220
+ } catch (err) {
221
+ this.#releaseHome();
222
+ throw err;
223
+ }
224
+ }
200
225
  args.push("--gemini-dir", this.#stagedHome);
201
226
  }
202
227
  let child: ChildProcess;
package/src/acp/driver.ts CHANGED
@@ -46,6 +46,11 @@ export interface AcpDriverOptions {
46
46
  binArgs?: string[] | (() => string[]);
47
47
  /** Native agy only: isolate inherited global MCP from other pi sessions. */
48
48
  isolateHome?: boolean;
49
+ /** Lean agent mode, resolved once per spawn. When defined, the connection
50
+ * stages the agent file into the isolated home and `--agent <name>` is
51
+ * appended to the spawned argv. Undefined = off. Resolving HERE (not in
52
+ * binArgs) keeps the agent name and body from one config read. */
53
+ leanAgent?: () => { name: string; body: string } | undefined;
49
54
  extraEnv?: Record<string, string>;
50
55
  /** Bridge registration for session/new AND session/load. */
51
56
  mcpServers?: () => AcpMcpServer[];
@@ -619,7 +624,9 @@ export class AcpDriver implements TurnDriver {
619
624
  // Only native failures feed the silent-failure note: bridge tool
620
625
  // errors are pi's own parking surface (the provider already surfaces
621
626
  // them), not an agy-native tool the model failed to recover from.
622
- if (!mapped.mcpServer) {
627
+ // entry?.mcpServer covers lean update frames stripped of
628
+ // name/rawInput: the start frame's unwrapped server decides.
629
+ if (!(mapped.mcpServer ?? entry?.mcpServer)) {
623
630
  turn.sawToolError = true;
624
631
  turn.lastToolError = { name, message: mapped.message };
625
632
  }
@@ -675,10 +682,13 @@ export class AcpDriver implements TurnDriver {
675
682
  this.#generation += 1;
676
683
  this.#state = "starting";
677
684
  this.#stats.spawns += 1;
685
+ const lean = this.#opts.leanAgent?.();
686
+ const binArgs = typeof this.#opts.binArgs === "function" ? this.#opts.binArgs() : this.#opts.binArgs;
678
687
  const conn = new AcpConnection({
679
688
  bin: typeof this.#opts.bin === "function" ? this.#opts.bin() : this.#opts.bin,
680
- binArgs: typeof this.#opts.binArgs === "function" ? this.#opts.binArgs() : this.#opts.binArgs,
689
+ binArgs: lean ? [...(binArgs ?? []), "--agent", lean.name] : binArgs,
681
690
  isolateHome: this.#opts.isolateHome,
691
+ leanAgent: lean,
682
692
  extraEnv: this.#opts.extraEnv,
683
693
  cwd: request.cwd,
684
694
  mcpServers: this.#opts.mcpServers,