@estebanforge/pi-antigravity-bridge 1.10.9 → 1.12.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,25 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file.
4
4
 
5
+ ## [1.12.0] - 2026-11-19
6
+
7
+ ### Fixed
8
+
9
+ - **Every bridge-owned path now follows pi's agent dir (`PI_CODING_AGENT_DIR` / `getAgentDir()`) instead of hardcoded `~/.pi` (issue #17).** Isolated or rebranded pi homes (Gentle Shell-style wrappers) previously got their config, session bindings, model cache, ACP homes, per-pid agy-mcp dirs, patch backups, support logs, and suppression marker written under `~/.pi` anyway, and skill discovery plus permission-extension detection read the wrong home. All state now derives from one `bridgeDir()`/`extensionsDataDir()` helper pair anchored at `getAgentDir()`, skill discovery mirrors pi's own loader (`<agentDir>/skills` user, `<project>/<CONFIG_DIR_NAME>/skills` project), and detection markers follow each writer's verified layout: gotgenes and monroewilliams resolve globals via `getAgentDir()` (the old literal `~/.agent/pi-permissions.jsonc` marker matched no path any published monroewilliams release ever wrote, so installs it silently missed now detect), while rhedbull and the project policy file stay on the literal `.pi` paths their packages hardcode. Default installs resolve byte-identical to before; env-override users start fresh — existing `sessions.json` conversation bindings and the model cache under the old path are not migrated. `CONFIG_PATH`/`STORE_PATH`/`MODELS_CACHE_PATH`/`BRIDGE_BASE`/`PATCH_BACKUP_DIR` consts became functions (`configPath()` et al.) so the resolution is per-call, and the `{ home }`/`{ cwd }` test seams gained an `agentDir` override.
10
+ - **The approval gate now covers the ACP engine and agy 1.5.11's tool family (issue #18).** Two live-captured gaps closed on the mapping side: `write_file {Path, Content}` was never gated (the system-prompt carrier explicitly requests this tool, so new-file writes sailed past the gate even on stream-json), and `edit_file {Path, Target, Replacement}` mapped to an empty path that permission extensions cannot judge. `write_file` joined `GATED_AGY_TOOLS` (one source feeding the hook matcher, the deny set, and the mapping), the mapping accepts the new arg names with the older spellings as fallbacks, and a gated write/edit whose target path resolves empty (or a multi-replace with no resolvable chunk) now denies before parking instead of forwarding decision garbage; a cross-check test pins every gated name to a working mapping.
11
+ On the engine side, the ACP server was silently excluded: the gate was staged for every session but only the stream-json driver delivered it, so with the gate on, ACP turns (the default engine) ran native tools ungated while `approvals.mode` promised enforcement. A live probe on agy 1.5.12 (`scripts/probe-acp-hooks.mjs`, workspace positive control fired) showed the server honors PreToolUse hooks from the staged home's `config/hooks.json`, so the connection now merges the session's gate group into the staged home at spawn (`mergeGateGroupIntoAcpHome`, foreign groups preserved, no-op when the gate is off). Gate state stays load-latched: mid-session gate changes take effect on the next pi session, same as stream-json staging. Delivery is probe-verified on agy 1.5.12 only; the session wiring warns in the log and /agy doctor lists the gate as delivery-unverified when an older agy serves a gated ACP session, and the full park round trip on a live ACP server remains tracked in docs/TODO.md section 3b.
12
+ - **ACP turns that end without model output now explain themselves (issue #18).** agy 1.5.11 ended a turn with the non-ACP stopReason `stop` after a native `run_command` failed, the driver mapped the unknown reason to a clean OK, and the pi caller received an empty final report with no trace of the failure. Unknown stop reasons are now logged (`acp-unknown-stop-reason`), and an OK turn with no model text whose native tool failed settles with a synthetic report naming the tool and its error instead of silence. Model output still wins: a failed tool followed by a normal answer never gets the note.
13
+
14
+ ## [1.11.0] - 2026-11-18
15
+
16
+ ### Added
17
+
18
+ - **Model-switch handoff toast.** Selecting an Antigravity bridge model with no bound agy conversation (the mid-session switch from another provider) now toasts "handoff context will ship to the new agy conversation", so the fresh-conversation handoff is visible instead of silent. Suppressed on session restore, for bound conversations (they continue as-is), when the digest is off (nothing would ship), and on an empty session (nothing to hand off). UI only; binding is checked with the provider's own `sessionKey` derivation and a failure to compute it stays silent rather than lying.
19
+
20
+ ### Fixed
21
+
22
+ - **Context now hands off to a fresh Antigravity conversation opened mid-session.** Switching pi models onto an Antigravity bridge model (or an engine switch, or issue #1 conversation recreation) opened a fresh agy conversation that received only the latest user prompt - Gemini answered "ok, ready for the task" as if starting from scratch, because the G1 context digest was gated on a config flag that defaulted to off. The digest is now on by default and self-gating: it ships only when the delta window is non-empty and every piece ships exactly once, so pure antigravity sessions keep byte-stable prompts and an intact server-side prompt cache. The builder learns two modes: bound (default, own-provider turns skipped as before) and fresh (own turns and their tool results included, for a conversation whose server-side history is empty). Compaction-aware watermark reset: a compaction shrinks the transcript below the stored `lastMessageCount`, which used to empty the delta window and silently drop every post-compaction turn; the window now restarts after the compaction with the summary shipped once, keyed by summary CONTENT (`digestSummaryId` on the session record - pi puts every post-compaction summary at the transcript front, so index identity would swallow the second compaction). A boundary fingerprint (`digestBoundary`, role+timestamp of the watermark message) resets the delta to the full digest when the transcript mutated under the stored count (/tree, /fork, per-call context-hook rewrites) instead of shipping a silently wrong window; that reset - and a delivered compaction - may re-ship recent user messages agy already holds, bounded by the digest cap, in exchange for never dropping context. Records written before this release keep their stored watermark (no duplicate dump on upgrade) and gain the new fields on their first turn. On stream-json the digest is budgeted under the ~25KB single-prompt silent-drop cap (issue #2) in BYTES, both for the user's prompt and the digest itself, including multibyte content; an oversized compaction summary is clamped (head kept, `[truncated]` marker), and an exhausted budget ships nothing rather than a turn agy would silently drop. `digest: false` / `AGY_DIGEST=0` / `/agy digest off` keeps the old opt-out behavior.
23
+
5
24
  ## [1.10.9] - 2026-11-17
6
25
 
7
26
  ### Fixed
package/README.md CHANGED
@@ -9,7 +9,7 @@ If you also have [`@estebanforge/pi-ask-antigravity`](https://github.com/Esteban
9
9
 
10
10
  You pick a Gemini model in pi's `/model` picker. pi routes each turn through this provider. A single persistent `agy` process runs in your workspace; pi feeds it each turn, parses its stream-json events, and streams the agent text back into pi token by token. Token usage is live.
11
11
 
12
- Multi-turn works. The provider binds a pi session to an agy conversation id (persisted under `~/.pi/agent/antigravity-bridge/sessions.json`) and resumes it on the next turn via `--conversation <id>`. agy keeps its own history, so only the latest user message is sent each turn.
12
+ Multi-turn works. The provider binds a pi session to an agy conversation id (persisted under `<agentDir>/antigravity-bridge/sessions.json`, following `PI_CODING_AGENT_DIR`/`getAgentDir()`) and resumes it on the next turn via `--conversation <id>`. agy keeps its own history, so only the latest user message is sent each turn.
13
13
 
14
14
  ### Two engines
15
15
 
@@ -36,7 +36,7 @@ Residual limits (with or without the bridge):
36
36
 
37
37
  While agy is the active model it normally cannot see pi's universe of extensions: agentmemory, codegraph, web search, slack/asana, the `Ask*` delegations, and any other installed pi tool. This extension optionally bridges that gap.
38
38
 
39
- The bridge starts a localhost MCP server inside pi's process. The exposed catalog is computed live from pi's active tools on every `tools/list` and re-checked immediately before every `tools/call`: the `bridgeTools` mode, the session's `/agy tools` hidden set, and the bridge's own internal tools (`AskAntigravity`, the display-only `antigravity` wrapper, `activate_skill`, `bridge_poll_result`, the `agy_web_search`/`agy_read_url` wrappers) are filtered each time, and a call for anything outside the fresh set is rejected - a cached MCP catalog is not authorization. A call that passes routes into pi's own tool loop via the round-trip described below. Discovery has two layers. The provider's agy gets a per-invocation config: the bridge writes `.agents/mcp_config.json` into a bridge-controlled dir (`~/.pi/agent/antigravity-bridge/agy-mcp-<pid>/`) and the driver passes that dir as an extra `--add-dir` when it spawns agy. A per-pid entry (`pi-bridge-<pid>`) is also registered in the user's global agy config (`~/.gemini/config/mcp_config.json`; foreign servers preserved, stale entries swept at start), so agy builds that read only the global config still find the bridge.
39
+ The bridge starts a localhost MCP server inside pi's process. The exposed catalog is computed live from pi's active tools on every `tools/list` and re-checked immediately before every `tools/call`: the `bridgeTools` mode, the session's `/agy tools` hidden set, and the bridge's own internal tools (`AskAntigravity`, the display-only `antigravity` wrapper, `activate_skill`, `bridge_poll_result`, the `agy_web_search`/`agy_read_url` wrappers) are filtered each time, and a call for anything outside the fresh set is rejected - a cached MCP catalog is not authorization. A call that passes routes into pi's own tool loop via the round-trip described below. Discovery has two layers. The provider's agy gets a per-invocation config: the bridge writes `.agents/mcp_config.json` into a bridge-controlled dir (`<agentDir>/antigravity-bridge/agy-mcp-<pid>/`) and the driver passes that dir as an extra `--add-dir` when it spawns agy. A per-pid entry (`pi-bridge-<pid>`) is also registered in the user's global agy config (`~/.gemini/config/mcp_config.json`; foreign servers preserved, stale entries swept at start), so agy builds that read only the global config still find the bridge.
40
40
 
41
41
  **Upstream pi APIs only.** Bridge calls park in the provider's round-trip store; the provider ends the pi assistant message with a `toolUse` stop reason for the real pi tool, pi executes it in its own loop (native cards, permissions, hooks), and the toolResult completes the parked MCP response on the next stream call.
42
42
 
@@ -73,7 +73,7 @@ cards for read-only steps.
73
73
 
74
74
  ## Approval gate (agy native tools)
75
75
 
76
- agy runs its own agent loop with native tools (`run_command`, `create_file`, `edit_file`, ...), which pi's permission extensions never saw. The optional approval gate routes those calls through a pi-side approval: a staged PreToolUse hook parks the call, the provider surfaces it as a shadow `bash`/`write`/`edit` toolUse, and your permission extension (or the built-in ask/allow/deny fallback) decides before agy executes it. Off by default (`approvals.gateMode: auto` enables it only when a pi permission extension is detected); denials fail closed; read-only agy tools stay ungated. On ACP turns the server has its own per-tool permission ask: when one fires (`skipPermissions` off), the request parks on a real pi dialog instead of a silent deny, and allow-always choices are remembered per connection.
76
+ agy runs its own agent loop with native tools (`run_command`, `create_file`, `edit_file`, ...), which pi's permission extensions never saw. The optional approval gate routes those calls through a pi-side approval: a staged PreToolUse hook parks the call, the provider surfaces it as a shadow `bash`/`write`/`edit` toolUse, and your permission extension (or the built-in ask/allow/deny fallback) decides before agy executes it. Off by default (`approvals.gateMode: auto` enables it only when a pi permission extension is detected); denials fail closed; read-only agy tools stay ungated. Both engines are covered: stream-json receives the staged hooks via `--add-dir`, and the ACP server reads them from the staged home's `config/hooks.json` (issue #18). On ACP turns the server also has its own per-tool permission ask: when one fires (`skipPermissions` off), the request parks on a real pi dialog instead of a silent deny, and allow-always choices are remembered per connection. On ACP turns the server has its own per-tool permission ask: when one fires (`skipPermissions` off), the request parks on a real pi dialog instead of a silent deny, and allow-always choices are remembered per connection.
77
77
 
78
78
  Full mechanics, configuration, and a sample gate extension: [docs/APPROVAL-GATE.md](docs/APPROVAL-GATE.md).
79
79
 
@@ -118,7 +118,7 @@ If `agy models` fails at load (binary missing, auth not done, network stall), a
118
118
  | `askTool` | `on` (register the AskAntigravity delegation tool), `off` (no delegation tool; provider and models only) | `on` |
119
119
  | `webTools` | `off` (no web tools), `on` (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 | `off` |
120
120
  | `bridgeTools` | `none` (bridge off), `all` (every non-builtin tool, incl. other `Ask*` delegations), `mcp` (pi-mcp-adapter tools + skills bridge only) | `all` |
121
- | `digest` | `off` (stable prompts; agy's prompt cache hits) or `on` (inject a delta of pi-side context - compaction summaries, other-provider turns - into each agy prompt; the delta changes every turn, so agy re-bills the full context). Enable for mixed-provider sessions where agy must see pi-side context | `off` |
121
+ | `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. `off` = agy prompts contain only your message; a conversation opened mid-session starts without prior pi-side context | `on` |
122
122
  | `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. 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 `off` (agy-native behavior) | `on` |
123
123
  | `turnTimeoutMin` | Overall cap on ONE agy turn, minutes, both engines. Parked time (pi-tool round-trips, escalated calls, human-gated approvals) does not count against it on either engine: the cap pauses with remaining-budget semantics and resumes on unpark. When it fires, the bridge kills the agy process mid-task ("ACP turn exceeded the 10m deadline" / "agy exceeded the 10m turn timeout") - it is a bridge cap, not a Google server limit. Default is TTY-aware: `0` (no cap) on an interactive pi - you are the backstop with Esc; `20` headless, where nobody can abort and one runaway turn blocks the serialized turn queue. Opt into a gate with 1-1440 (free type via `config.json` or `/agy timeout <1-1440|off>`, or the `/agy` picker's preset list); `0` disables explicitly; anything else falls back to the TTY-aware default. The 5m inactivity stall guard always still bounds a hung server | `0` TTY / `20` headless |
124
124
  | `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,7 +131,7 @@ The `activate_skill` catalog mirrors pi's directory-based skill discovery: the t
131
131
 
132
132
  ### The /agy command
133
133
 
134
- `/agy` configures the provider at runtime. Settings persist to `~/.pi/agent/antigravity-bridge/config.json` and take effect on the next turn.
134
+ `/agy` configures the provider at runtime. Settings persist to `<agentDir>/antigravity-bridge/config.json` (pi's agent dir, so `PI_CODING_AGENT_DIR` is honored) and take effect on the next turn.
135
135
 
136
136
  ```
137
137
  /agy status summary, or open the full settings picker (TUI)
@@ -143,7 +143,7 @@ The `activate_skill` catalog mirrors pi's directory-based skill discovery: the t
143
143
  /agy ask on|off register the AskAntigravity delegation tool (default on; off keeps only the provider and models, even with pi-ask-antigravity installed)
144
144
  /agy model flash|pro|gemini fallback model for the AskAntigravity tool; callers may override per call
145
145
  /agy thinking low|medium|high fallback thinking tier for the AskAntigravity tool; callers may override per call
146
- /agy digest on|off inject pi-side context into agy prompts (default off; see table above)
146
+ /agy digest on|off ship pi-side context to agy when the delta is non-empty (default on; see table above)
147
147
  /agy system-prompt on|off send pi's system prompt + AGENTS.md + the Pi Bridge tool-priority note to new agy conversations (default on)
148
148
  /agy bridge all|mcp|none which pi tools the MCP bridge exposes to agy (default all; none = bridge off; a running server picks up the new catalog immediately, a stopped one on the next start)
149
149
  /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)
@@ -191,7 +191,7 @@ For isolation when running any agent that executes commands without a confirmati
191
191
  | `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. |
192
192
  | `AGY_DEFAULT_THINKING` | Default thinking tier for the `AskAntigravity` tool: `low`/`medium`/`high`. Anything else falls back to `medium`. Wins over the config file. |
193
193
  | `AGY_DEBUG` | `1`/`true`/`on` writes the full trail to the daily log (driver lifecycle, raw bridge traffic). Default off: **only `error` records land on disk** - routine disk writes are zero for regular users, and warnings surface as UI toasts instead. |
194
- | `AGY_APPROVALS` | Approval gate mode: `auto` (default; gate on only when a pi permission extension is detected), `shadow` (force the shadow-tool gate on), `dedicated`, `off`. Unknown values fall back to `auto`, so a typo can never force the gate on. Wins over `config.approvals.gateMode`. |
194
+ | `AGY_APPROVALS` | Approval gate mode: `auto` (default; gate on only when a pi permission extension is detected), `shadow` (force the shadow-tool gate on), `dedicated`, `off`. Unknown values fall back to `auto`, so a typo can never force the gate on. Wins over `config.approvals.gateMode`. Works on both engines: stream-json via `--add-dir`, ACP via the staged home's `config/hooks.json` (issue #18). |
195
195
  | `AGY_APPROVALS_MODE` | Fallback decision when no permission extension answers a gated call: `ask` (interactive prompt), `allow`, `deny` (headless default). Wins over `config.approvals.mode`. |
196
196
 
197
197
  ## Debug logs
@@ -199,9 +199,11 @@ For isolation when running any agent that executes commands without a confirmati
199
199
  The extension keeps a daily log on your machine, sorted by day:
200
200
 
201
201
  ```
202
- ~/.pi/extensions-data/estebanforge/pi-antigravity-bridge/logs/<YYYY-MM-DD>.ndjson
202
+ <configRoot>/extensions-data/estebanforge/pi-antigravity-bridge/logs/<YYYY-MM-DD>.ndjson
203
203
  ```
204
204
 
205
+ `configRoot` is dirname of pi's agent dir (`~/.pi` by default; `PI_CODING_AGENT_DIR` relocates it).
206
+
205
207
  One JSON record per line. Two verbosity tiers keep the disk cost at zero for regular users: by default only `error` records land on disk - everything routine (turn starts, tool calls, escalations, commands, driver failures) is withheld. Warnings are not lost: the extension toasts each one in the pi UI (bridge tool failures, stalls, timeouts, process exits), so users see them and can report them; deliberate aborts and failures pi already renders as the turn's own error block stay silent. Set `AGY_DEBUG=1` before reproducing a problem for the full trail: per-event driver lifecycle (spawn, exit, session load/new, unparks), turn starts and outcomes, bridge tool calls, escalations and poll traffic, late deliveries, list-tools traffic, recycle causes, and the raw bridge chatter. `/agy doctor` prints the log directory.
206
208
 
207
209
  Notes:
@@ -14,7 +14,7 @@
14
14
  // /agy command: full runtime config surface (engine, mode, permissions,
15
15
  // bridge tools, model, thinking, digest, system prompt) plus doctor,
16
16
  // authentication instructions, patch-cleanup, and session clear. Config persists to
17
- // ~/.pi/agent/antigravity-bridge/config.json so toggles survive restarts.
17
+ // <agentDir>/antigravity-bridge/config.json so toggles survive restarts.
18
18
 
19
19
  import os from "node:os";
20
20
  import fs from "node:fs";
@@ -46,8 +46,10 @@ import {
46
46
  defaultEscalateAfterMs,
47
47
  formatEscalatedAck,
48
48
  formatPollAnswer,
49
+ sessionKey,
49
50
  type NativeDisplayEvent,
50
51
  } from "../src/provider.js";
52
+ import { handoffToast } from "../src/handoff-toast.js";
51
53
  import { PollRunFolder, type PollRunData } from "../src/poll-fold.js";
52
54
  import {
53
55
  createShadowTool,
@@ -65,7 +67,7 @@ import { agyAuthenticationMessage } from "../src/agy-install.js";
65
67
  import { createAgySetupOffer } from "../src/agy-setup.js";
66
68
  import { ensureQueuedMessagesDefaults } from "../src/queued-messages.js";
67
69
  import type { TurnDriver, TurnOutcome } from "../src/driver-types.js";
68
- import { CONFIG_PATH, loadConfig, logsDir, MAX_TURN_CAP_MIN, parseCapMinutes, removeLegacyAcpBin, saveConfig, type AcpConfig, type AgyMode, type BridgeTools, type Engine, type ThinkingTier } from "../src/config.js";
70
+ import { configPath, loadConfig, logsDir, MAX_TURN_CAP_MIN, parseCapMinutes, removeLegacyAcpBin, saveConfig, type AcpConfig, type AgyMode, type BridgeTools, type Engine, type ThinkingTier } from "../src/config.js";
69
71
  import { agyMissingMessage, ENGINE_SETTINGS_ROW_ID, engineSettingsRow, isAgyInstalled, savedEngineMessage, showEnginePicker, shouldOfferEnginePicker } from "../src/engine-picker.js";
70
72
  import { agyVersionVerdict, checkAgyCliVersion, describeAgyVersionCheck, MIN_AGY_ACP_VERSION, MIN_AGY_VERSION, MIN_GEMINI_DIR_VERSION, probeGeminiDirFlag, resolveStreamHomeMode } from "../src/agy-version.js";
71
73
  import { isValidAgyAgentName, listAgyAgents } from "../src/agents.js";
@@ -136,7 +138,7 @@ export default async function (pi: ExtensionAPI): Promise<void> {
136
138
  // picker populated so the user gets a clear runtime error from agy rather
137
139
  // than an empty model list. /reload re-runs this and refreshes after an
138
140
  // `agy update`.
139
- // loadModelCatalogRaw serves a short-TTL cache (~/.pi/agent/antigravity-bridge/
141
+ // loadModelCatalogRaw serves a short-TTL cache (<agentDir>/antigravity-bridge/
140
142
  // models-cache.json) so reloads are instant and only re-spawn in the
141
143
  // background when stale. Derive both catalogs from the same raw text
142
144
  // (provider's slugified Gemini entries + the tool's family/version/tier
@@ -164,8 +166,9 @@ export default async function (pi: ExtensionAPI): Promise<void> {
164
166
  const FAIL_REASON_TURN_END = "antigravity turn ended with an unresolved pi tool call";
165
167
  const FAIL_REASON_SHUTDOWN = "antigravity session shut down";
166
168
 
167
- // Daily file log: every sink below feeds ~/.pi/extensions-data/
168
- // estebanforge/pi-antigravity-bridge/logs/<YYYY-MM-DD>.ndjson (see
169
+ // Daily file log: every sink below feeds <configRoot>/extensions-data/
170
+ // estebanforge/pi-antigravity-bridge/logs/<YYYY-MM-DD>.ndjson, where
171
+ // configRoot is dirname(getAgentDir()) (see
169
172
  // src/daily-log.ts). Fire-and-forget, secrets redacted, old days pruned.
170
173
  // Support flow: "attach the last days' files from that dir".
171
174
  const fileLog = createDailyLogger({ dir: logsDir() });
@@ -604,6 +607,32 @@ export default async function (pi: ExtensionAPI): Promise<void> {
604
607
  for (const handle of backgroundWatchers.values()) handle.stop();
605
608
  backgroundWatchers.clear();
606
609
  });
610
+ // Model-switch handoff toast: entering an unbound antigravity model
611
+ // mid-session opens a fresh agy conversation on the next turn; the
612
+ // digest re-delivers pi-side context into it. UI only.
613
+ pi.on("model_select", (event, ctx) => {
614
+ try {
615
+ const msg = handoffToast({
616
+ api: event.model?.api,
617
+ digestEnabled: loadConfig().digest,
618
+ source: event.source,
619
+ bound: (() => {
620
+ // getSessionId is missing from the published ReadonlySessionManager
621
+ // type (dts minification), so shape-cast instead of trusting it.
622
+ const sm = ctx.sessionManager as { getSessionId?: () => string };
623
+ const sid = sm.getSessionId?.();
624
+ const key = sessionKey(sid ? { sessionId: sid } : undefined, ctx.cwd, engine);
625
+ return store.get(key) !== null;
626
+ })(),
627
+ hasContext: ctx.sessionManager
628
+ .getEntries()
629
+ .some((e) => (e as { type?: string }).type === "message"),
630
+ });
631
+ if (msg && ctx.hasUI) ctx.ui.notify(msg, "info");
632
+ } catch (err) {
633
+ fileLog.log("handoff-toast-error", { error: err instanceof Error ? err.message : String(err) }, "warn");
634
+ }
635
+ });
607
636
  const streamSimple = createStreamSimple({
608
637
  entries,
609
638
  store,
@@ -748,7 +777,7 @@ export default async function (pi: ExtensionAPI): Promise<void> {
748
777
  // bridge startup below: on a genuine first run the modal blocks input
749
778
  // anyway, so the delay is invisible.
750
779
  let setupEngine = engine;
751
- if (event.reason === "startup" && ctx.mode === "tui" && shouldOfferEnginePicker(CONFIG_PATH)) {
780
+ if (event.reason === "startup" && ctx.mode === "tui" && shouldOfferEnginePicker(configPath())) {
752
781
  // Best-effort, like the legacy-patch notice below: a picker failure
753
782
  // (mid-prompt TUI teardown, resize races) must never take down the
754
783
  // rest of session_start - the MCP bridge startup included. The
@@ -786,7 +815,7 @@ export default async function (pi: ExtensionAPI): Promise<void> {
786
815
  }
787
816
  if (!legacyFileAcpWarningShown && legacyConfigCleanupFailed) {
788
817
  legacyFileAcpWarningShown = true;
789
- const msg = `Couldn't remove the old "bin" setting from ${CONFIG_PATH} (details in the bridge log). Delete the "bin" line under "acp" by hand; turns run "agy acp" from the CLI.`;
818
+ const msg = `Couldn't remove the old "bin" setting from ${configPath()} (details in the bridge log). Delete the "bin" line under "acp" by hand; turns run "agy acp" from the CLI.`;
790
819
  if (ctx.hasUI) ctx.ui.notify(msg, "warning");
791
820
  else console.error(`[antigravity-bridge] ${msg}`);
792
821
  }
@@ -871,7 +900,7 @@ export default async function (pi: ExtensionAPI): Promise<void> {
871
900
  if (mcpHandle) return; // already running (reload re-fires session_start)
872
901
  // pi loads project skill locations only after the project is trusted;
873
902
  // mirror that gate. Global skill dirs are always scanned.
874
- const skills: SkillLite[] = scanSkills(ctx.isProjectTrusted() ? process.cwd() : undefined);
903
+ const skills: SkillLite[] = scanSkills(ctx.isProjectTrusted() ? { projectDir: process.cwd() } : {});
875
904
  const listTools = () => {
876
905
  // /mcp and pi.setActiveTools() update the same live catalog. ACP gets
877
906
  // this endpoint through session/new or session/load; no global config write.
@@ -1023,6 +1052,15 @@ export default async function (pi: ExtensionAPI): Promise<void> {
1023
1052
  {
1024
1053
  const cfg = loadConfig();
1025
1054
  const mode = resolveGateMode(cfg.approvals.gateMode, detectPermissionGateExtensions());
1055
+ if (mode !== "off" && engine === "acp") {
1056
+ // Staged-home hook delivery is probe-verified on agy 1.5.12
1057
+ // only (issue #18); older ACP builds may not honor it. Warn
1058
+ // so a silently inert gate is at least visible in the log.
1059
+ const cli = await checkAgyCliVersion(resolveAgyBinary());
1060
+ if (cli.status === "ok" && agyVersionVerdict(cli.raw, "1.5.12").status === "unsupported") {
1061
+ fileLog.log("approval-gate-agy-version-unverified", { version: cli.raw }, "warn");
1062
+ }
1063
+ }
1026
1064
  if (mode === "dedicated") {
1027
1065
  // The explicit antigravity_approve variant is planned; until it
1028
1066
  // ships, dedicated stages the same shadow tools. Say so, so the
@@ -1228,7 +1266,7 @@ function statusText(ctx: AgyCommandCtx): string {
1228
1266
  ` models: ${ctx.entries.length} ${source}`,
1229
1267
  ...settingsRows(ctx),
1230
1268
  ` sessions: ${ctx.store.size} bound`,
1231
- ` config: ${CONFIG_PATH}`,
1269
+ ` config: ${configPath()}`,
1232
1270
  "",
1233
1271
  "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, /agy agent <name|off>, /agy subagents, /agy quota, /agy artifacts [open <n|name>], /agy tasks [tail <id>], /agy bridge all|mcp|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",
1234
1272
  ].join("\n");
@@ -1362,7 +1400,7 @@ function registerAgyCommand(pi: ExtensionAPI, ctx: AgyCommandCtx): void {
1362
1400
  ` sessions: ${ctx.store.size} bound`,
1363
1401
  ` models: ${ctx.entries.length} ${ctx.usingFallback ? "FALLBACK (agy models failed)" : "discovered"}`,
1364
1402
  ` agy cli: ${describeAgyVersionCheck(cliCheck)} (min ${cliFloor})`,
1365
- ` config: ${CONFIG_PATH}`,
1403
+ ` config: ${configPath()}`,
1366
1404
  ` logs: ${logsDir()} (attach recent days' files when reporting issues; set AGY_DEBUG=1 to capture details)`,
1367
1405
  ];
1368
1406
  if (snap.engine === "acp" && snap.acp) {
@@ -1384,6 +1422,12 @@ function registerAgyCommand(pi: ExtensionAPI, ctx: AgyCommandCtx): void {
1384
1422
  for (const entry of snap.lifecycle.slice(-5)) lines.push(` ${entry}`);
1385
1423
  }
1386
1424
  if (engine === "acp") lines.push(" acp transport: agy acp (shared CLI authentication, isolated MCP home)");
1425
+ if (engine === "acp" && resolveGateMode(config.approvals.gateMode, detectPermissionGateExtensions()) !== "off"
1426
+ && rawCliCheck.status === "ok" && agyVersionVerdict(rawCliCheck.raw, "1.5.12").status === "unsupported") {
1427
+ // Same condition as the session_start wiring warn, surfaced here
1428
+ // because a daily-log-only signal is easy to miss (review S2).
1429
+ lines.push(` approval gate: ON but hook delivery is verified only on agy >= 1.5.12 (this: ${rawCliCheck.raw}; issue #18)`);
1430
+ }
1387
1431
  if (engine === "stream-json" && ctx.streamIsolated) lines.push(" stream transport: agy stream-json (shared CLI authentication, isolated MCP home)");
1388
1432
  if (engine === "stream-json" && !ctx.streamIsolated) lines.push(" stream transport: agy stream-json (shared CLI authentication, GLOBAL MCP registration: isolation unavailable)");
1389
1433
  const retiredAuth = path.join(os.homedir(), ".gemini", "antigravity-acp");
@@ -1738,8 +1782,8 @@ function registerAgyCommand(pi: ExtensionAPI, ctx: AgyCommandCtx): void {
1738
1782
  const next = saveConfig({ digest: val === "on" });
1739
1783
  ui?.notify(
1740
1784
  next.digest
1741
- ? "digest on. pi-side context (compaction summaries, other-provider turns) is injected into each agy prompt. Note: this defeats agy's prompt cache (~25-30k tokens re-billed per turn)."
1742
- : "digest off. agy prompts contain only your message; agy's prompt cache stays stable. Enable when mixing providers in one session and agy must see pi-side context.",
1785
+ ? "digest on. pi-side context ships when the delta is non-empty (fresh-conversation handoff, other-provider turns, pi-side tool runs, compaction summaries), each piece once. Pure antigravity sessions keep byte-stable prompts."
1786
+ : "digest off. agy prompts contain only your message; a conversation opened mid-session starts without prior pi-side context.",
1743
1787
  "info",
1744
1788
  );
1745
1789
  } else {
@@ -1879,7 +1923,7 @@ async function openAgyPicker(ui: ExtensionUIContext, ctx: AgyCommandCtx): Promis
1879
1923
  id: "digest",
1880
1924
  label: "Context digest",
1881
1925
  description:
1882
- "Inject a delta of pi-side context into each agy prompt. Defeats agy's prompt cache (~25-30k tokens re-billed per turn).",
1926
+ "Ship pi-side context (handoffs, other-provider turns, compactions) to agy when the delta is non-empty. Pure antigravity sessions keep byte-stable prompts.",
1883
1927
  currentValue: config.digest ? "on" : "off",
1884
1928
  values: ["on", "off"],
1885
1929
  },
@@ -1916,7 +1960,7 @@ async function openAgyPicker(ui: ExtensionUIContext, ctx: AgyCommandCtx): Promis
1916
1960
  theme,
1917
1961
  {
1918
1962
  title: "Antigravity provider",
1919
- subtitle: `Config file: ${CONFIG_PATH} — changes save when the dialog closes`,
1963
+ subtitle: `Config file: ${configPath()} — changes save when the dialog closes`,
1920
1964
  rows,
1921
1965
  footer: "↑↓ navigate · Enter/Space cycle · Type to search · Esc close",
1922
1966
  onChange: (id, newValue) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@estebanforge/pi-antigravity-bridge",
3
- "version": "1.10.9",
3
+ "version": "1.12.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",
@@ -19,6 +19,7 @@ import { frameCarriesUsage } from "./events.js";
19
19
  import type { AgyUsage } from "../driver-types.js";
20
20
  import { redactText } from "../redact.js";
21
21
  import { JsonRpcResponseError, JsonRpcSession, JsonRpcTimeoutError } from "./jsonrpc.js";
22
+ import { mergeGateGroupIntoAcpHome } from "../approval-hook.js";
22
23
  import { removeStagedAgyHome, stageAgyHome } from "./home.js";
23
24
 
24
25
  export interface AcpMcpServer {
@@ -171,6 +172,17 @@ export class AcpConnection {
171
172
  const args = [...(this.#opts.binArgs ?? [])];
172
173
  if (this.#opts.isolateHome) {
173
174
  this.#stagedHome = stageAgyHome(typeof this.#opts.isolateHome === "object" ? this.#opts.isolateHome : {});
175
+ // Deliver this session's approval gate group into the staged home:
176
+ // the ACP server honors hooks from config/hooks.json there (issue
177
+ // #18). No-op when the gate is off. A merge failure must not leak
178
+ // the staged home: release it and rethrow so the turn fails closed
179
+ // the same way a spawn failure does.
180
+ try {
181
+ mergeGateGroupIntoAcpHome(this.#stagedHome);
182
+ } catch (err) {
183
+ this.#releaseHome();
184
+ throw err;
185
+ }
174
186
  args.push("--gemini-dir", this.#stagedHome);
175
187
  }
176
188
  let child: ChildProcess;
package/src/acp/driver.ts CHANGED
@@ -23,7 +23,8 @@ import type { UsageEstimate } from "../config.js";
23
23
  import { AcpConnection, type AcpMcpServer, type AcpPermissionRequest } from "./connection.js";
24
24
  import type { AcpPermissionHandler } from "./connection.js";
25
25
  import { JsonRpcTimeoutError } from "./jsonrpc.js";
26
- import { mapStopReason, mapUpdate, TextAccumulator, type AcpEditDiff } from "./events.js";
26
+ import { KNOWN_STOP_REASONS, mapStopReason, mapUpdate, TextAccumulator, type AcpEditDiff } from "./events.js";
27
+ import { redactText } from "../redact.js";
27
28
  import { estimateTokens, synthesizeUsage } from "./usage-estimate.js";
28
29
  import type {
29
30
  AgyUsage,
@@ -121,6 +122,11 @@ interface ActiveTurn {
121
122
  /** toolCallId → tool name + args + optional native diff (diff rides on
122
123
  * the pending tool_call frame; updates don't repeat it). */
123
124
  toolCalls: Map<string, { name: string; args: Record<string, unknown>; diff?: AcpEditDiff; mcpServer?: string }>;
125
+ /** Issue #18 F4: a native tool failed this turn. With an OK stop and no
126
+ * model output the caller would otherwise receive an empty final report
127
+ * (the reporter's stopReason "stop" after a failed run_command). */
128
+ sawToolError: boolean;
129
+ lastToolError: { name: string; message: string } | null;
124
130
  }
125
131
 
126
132
  /** Map our config knobs onto ACP session modes. skipPermissions=false also
@@ -371,6 +377,11 @@ export class AcpDriver implements TurnDriver {
371
377
  this.#emit(turn, { type: "usage", usage: settleUsage });
372
378
  }
373
379
  const mapped = mapStopReason(result.stopReason);
380
+ if (!KNOWN_STOP_REASONS.has(String(result.stopReason))) {
381
+ // "stop" (issue #18 F4) is not an ACP enum value; silence would
382
+ // hide exactly the server drift that produced the empty report.
383
+ this.#log("acp-unknown-stop-reason", { stopReason: result.stopReason });
384
+ }
374
385
  this.#settle(turn, {
375
386
  conversationId: turn.sessionId,
376
387
  status: mapped.status,
@@ -491,6 +502,13 @@ export class AcpDriver implements TurnDriver {
491
502
  const entry = turn.toolCalls.get(mapped.toolCallId);
492
503
  turn.toolCalls.delete(mapped.toolCallId);
493
504
  const name = entry?.name ?? "tool";
505
+ // Only native failures feed the silent-failure note: bridge tool
506
+ // errors are pi's own parking surface (the provider already surfaces
507
+ // them), not an agy-native tool the model failed to recover from.
508
+ if (!mapped.mcpServer) {
509
+ turn.sawToolError = true;
510
+ turn.lastToolError = { name, message: mapped.message };
511
+ }
494
512
  this.#emit(turn, { type: "tool_error", name, message: mapped.message, mcpServer: mapped.mcpServer ?? entry?.mcpServer, toolCallId: mapped.toolCallId });
495
513
  return;
496
514
  }
@@ -664,6 +682,8 @@ export class AcpDriver implements TurnDriver {
664
682
  overallDeadline: null,
665
683
  overallRemainingMs: null,
666
684
  toolCalls: new Map(),
685
+ sawToolError: false,
686
+ lastToolError: null,
667
687
  };
668
688
  return turn;
669
689
  }
@@ -769,6 +789,16 @@ export class AcpDriver implements TurnDriver {
769
789
  this.#emit(turn, { type: "text", delta: flushed });
770
790
  }
771
791
  outcome.response = turn.response.text;
792
+ // Issue #18 F4: a native tool failed, the model never spoke, and the
793
+ // server still ended OK (its "stop" is not even an ACP enum value).
794
+ // An empty final report hides the failure from the pi caller.
795
+ if (outcome.status === "OK" && !outcome.aborted && !outcome.response.trim() && turn.sawToolError && turn.lastToolError) {
796
+ // rawOutput rides unfiltered in the message; redact, collapse to one
797
+ // line and cap - this text lands in the transcript and later in the
798
+ // model's context digest.
799
+ const detail = redactText(turn.lastToolError.message).replace(/\s+/g, " ").trim().slice(0, 300);
800
+ outcome.response = `[bridge] The turn ended without model output. A native tool failed earlier in this turn: ${turn.lastToolError.name}${detail ? ` (${detail})` : ""}.`;
801
+ }
772
802
  // Gate B stopgap: synthesize usage on clean turns while the server sends
773
803
  // none. Runs BEFORE close so the usage activity drains through the
774
804
  // normal #nextActivity loop (provider maps it onto partial.usage).
package/src/acp/events.ts CHANGED
@@ -223,6 +223,17 @@ export function mapStopReason(stopReason: unknown): {
223
223
  }
224
224
  }
225
225
 
226
+ /** Stop reasons the ACP spec defines. Anything else hitting mapStopReason's
227
+ * default (OK) is server drift; the driver logs it (issue #18 F4: agy sent
228
+ * the stream-json-style "stop"). */
229
+ export const KNOWN_STOP_REASONS: ReadonlySet<string> = new Set([
230
+ "end_turn",
231
+ "cancelled",
232
+ "max_tokens",
233
+ "refusal",
234
+ "max_turn_requests",
235
+ ]);
236
+
226
237
  /** Defensive accumulation with the cumulative-resend port. Native agy streams
227
238
  * deltas, so on
228
239
  * a compliant server the resend branch stays inert; it exists because the
package/src/acp/home.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import fs from "node:fs";
2
2
  import os from "node:os";
3
3
  import path from "node:path";
4
+ import { bridgeDir } from "../config.js";
4
5
  import { isPidAlive } from "../mcp-server.js";
5
6
  import { bridgeServerEntry, bridgeServerName, readGlobalMcpConfig } from "../mcp-registration.js";
6
7
 
@@ -17,7 +18,7 @@ function linkDirectory(source: string, target: string): void {
17
18
  * stream-json engine adopting homes; renaming it would strand existing
18
19
  * installs' unswept dirs, so both engines stage under it. */
19
20
  export function agyHomeStagingDir(): string {
20
- return path.join(os.homedir(), ".pi", "agent", "antigravity-bridge", "acp-homes");
21
+ return path.join(bridgeDir(), "acp-homes");
21
22
  }
22
23
 
23
24
  export interface StageAgyHomeOptions {
@@ -12,6 +12,7 @@
12
12
  import fs from "node:fs";
13
13
  import os from "node:os";
14
14
  import path from "node:path";
15
+ import { CONFIG_DIR_NAME, getAgentDir } from "@earendil-works/pi-coding-agent";
15
16
 
16
17
  /** npm names of the audited pi permission packages (docs/TODO.md 2.4). */
17
18
  export const KNOWN_GATE_PACKAGES = [
@@ -82,22 +83,31 @@ function containsName(lower: string, name: string): boolean {
82
83
  /**
83
84
  * Detect installed third-party permission extensions.
84
85
  *
85
- * @param opts.home HOME override for tests.
86
+ * Pi-owned candidates (settings.json) resolve against pi's agent dir and
87
+ * CONFIG_DIR_NAME so isolated or rebranded homes are seen. On-disk markers
88
+ * follow each writer's real layout (verified in the published tarballs,
89
+ * 2026-11-19): gotgenes and monroewilliams resolve globals via getAgentDir(),
90
+ * while rhedbull and the project policy file hardcode literal .pi — those
91
+ * must stay literal or detection misses real installs.
92
+ *
93
+ * @param opts.home HOME override for the literal-.pi markers (tests).
86
94
  * @param opts.cwd project dir override for tests (project settings).
95
+ * @param opts.agentDir pi agent dir override (tests).
87
96
  * @param opts.settingsFiles extra settings files to scan (tests).
88
97
  */
89
98
  export function detectPermissionGateExtensions(
90
- opts: { home?: string; cwd?: string; settingsFiles?: string[] } = {},
99
+ opts: { home?: string; cwd?: string; agentDir?: string; settingsFiles?: string[] } = {},
91
100
  ): GateExtensionHit[] {
92
101
  const home = opts.home ?? os.homedir();
93
102
  const cwd = opts.cwd ?? process.cwd();
103
+ const agentDir = opts.agentDir ?? getAgentDir();
94
104
  const hits: GateExtensionHit[] = [];
95
105
  const seen = new Set<string>();
96
106
 
97
107
  const settingsCandidates = [
98
108
  ...(opts.settingsFiles ?? []),
99
- path.join(home, ".pi", "agent", "settings.json"),
100
- path.join(cwd, ".pi", "settings.json"),
109
+ path.join(agentDir, "settings.json"),
110
+ path.join(cwd, CONFIG_DIR_NAME, "settings.json"),
101
111
  ];
102
112
  for (const file of settingsCandidates) {
103
113
  for (const entry of packagesFrom(file)) {
@@ -109,13 +119,18 @@ export function detectPermissionGateExtensions(
109
119
  }
110
120
  }
111
121
 
112
- // Known config-file markers from the audit. Presence of the config does
113
- // not prove the extension is installed, but every audited package writes
114
- // its config only after install + first run, which is evidence enough for
115
- // an opt-in default.
122
+ // On-disk config markers. Pi-resolved globals first: gotgenes reads
123
+ // getGlobalConfigDir(getAgentDir()); monroewilliams writes
124
+ // join(getAgentDir(), "pi-permissions.jsonc") (its default agent dir is
125
+ // getAgentDir(), so the old literal ~/.agent marker never matched any
126
+ // real install). Literal .pi below: rhedbull hardcodes homedir()/.pi,
127
+ // and both writers of the project policy file hardcode cwd/.pi.
128
+ // Marker presence is install evidence, not proof: every audited package
129
+ // writes its config only after install + first run, which is evidence
130
+ // enough for an opt-in default.
116
131
  const markers: Array<{ file: string; name: string }> = [
117
- { file: path.join(home, ".pi", "agent", "extensions", "pi-permission-system"), name: "@gotgenes/pi-permission-system" },
118
- { file: path.join(home, ".agent", "pi-permissions.jsonc"), name: "@monroewilliams/pi-permission-system" },
132
+ { file: path.join(agentDir, "extensions", "pi-permission-system"), name: "@gotgenes/pi-permission-system" },
133
+ { file: path.join(agentDir, "pi-permissions.jsonc"), name: "@monroewilliams/pi-permission-system" },
119
134
  { file: path.join(home, ".pi", "agent", "extensions", "permissions.json"), name: "@rhedbull/pi-permissions" },
120
135
  { file: path.join(cwd, ".pi", "agent", "pi-permissions.jsonc"), name: "@gotgenes/pi-permission-system" },
121
136
  ];
@@ -87,14 +87,32 @@ export interface ShadowMapping {
87
87
  }
88
88
 
89
89
  /** Map an agy native tool call (hook stdin payload) onto the shadow surface.
90
- * Field names follow the TODO 2.5 table: create_file is live-captured (F1);
91
- * the edit-class arg names are docs-attested and degrade gracefully - a
92
- * wrong guess only weakens the confirm-dialog text, never the decision
93
- * (the tool runs in agy's loop either way). Unknown names return null:
94
- * read-only tools are not gated. */
90
+ * Field names are runtime-attested: create_file is live-captured (F1), the
91
+ * write/edit pairs come from agy 1.5.11 PreToolUse captures (issue #18,
92
+ * Path/Content and Path/Target/Replacement) with the older docs-attested
93
+ * names kept as fallbacks. A gated write/edit whose target path cannot be
94
+ * resolved returns null - the caller denies before parking, because an
95
+ * empty-path shadow is decision garbage for path-prefix permission
96
+ * extensions. Other unknown names return null: read-only tools are not
97
+ * gated. */
95
98
  export function mapNativeToShadow(name: string, args: Record<string, unknown>): ShadowMapping | null {
96
99
  const a = args ?? {};
97
100
  const str = (v: unknown): string => (typeof v === "string" ? v : v === undefined || v === null ? "" : String(v));
101
+ const pick = (...vals: unknown[]): string => {
102
+ for (const v of vals) {
103
+ const s = str(v);
104
+ if (s !== "") return s;
105
+ }
106
+ return "";
107
+ };
108
+ const targetPath = (fallback: unknown): string | null => {
109
+ // A target path must be a non-empty string; anything else (numbers,
110
+ // objects, whitespace) is an unresolved target and denies below.
111
+ for (const v of [a.Path, fallback]) {
112
+ if (typeof v === "string" && v.trim() !== "") return v.trim();
113
+ }
114
+ return null;
115
+ };
98
116
  switch (name) {
99
117
  case "run_command": {
100
118
  const input: Record<string, unknown> = { command: str(a.CommandLine) };
@@ -102,29 +120,36 @@ export function mapNativeToShadow(name: string, args: Record<string, unknown>):
102
120
  return { shadow: "bash", input };
103
121
  }
104
122
  case "write_to_file":
105
- case "create_file":
106
- return { shadow: "write", input: { path: str(a.TargetFile), content: str(a.CodeContent) } };
123
+ case "write_file":
124
+ case "create_file": {
125
+ const path = targetPath(a.TargetFile);
126
+ if (path === null) return null;
127
+ return { shadow: "write", input: { path, content: pick(a.Content, a.CodeContent) } };
128
+ }
107
129
  case "replace_file_content":
108
- case "edit_file":
130
+ case "edit_file": {
131
+ const path = targetPath(a.TargetFile);
132
+ if (path === null) return null;
109
133
  return {
110
134
  shadow: "edit",
111
135
  input: {
112
- path: str(a.TargetFile),
113
- edits: [{ oldText: str(a.SearchText), newText: str(a.ReplacementContent) }],
136
+ path,
137
+ edits: [{ oldText: pick(a.Target, a.SearchText), newText: pick(a.Replacement, a.ReplacementContent) }],
114
138
  },
115
139
  };
140
+ }
116
141
  case "multi_replace_file_content": {
142
+ const path = targetPath(a.TargetFile);
143
+ if (path === null) return null;
117
144
  const chunks = Array.isArray(a.ReplacementChunks) ? a.ReplacementChunks : [];
118
- return {
119
- shadow: "edit",
120
- input: {
121
- path: str(a.TargetFile),
122
- edits: chunks.map((c) => {
123
- const chunk = (c ?? {}) as Record<string, unknown>;
124
- return { oldText: str(chunk.SearchText), newText: str(chunk.ReplacementContent) };
125
- }),
126
- },
127
- };
145
+ const edits = chunks.map((c) => {
146
+ const chunk = (c ?? {}) as Record<string, unknown>;
147
+ return { oldText: pick(chunk.Target, chunk.SearchText), newText: pick(chunk.Replacement, chunk.ReplacementContent) };
148
+ });
149
+ // Fail closed: a path with no resolvable chunk is a shadow edit
150
+ // carrying no change information - deny instead of parking it.
151
+ if (edits.length === 0 || edits.every((e) => e.oldText === "" && e.newText === "")) return null;
152
+ return { shadow: "edit", input: { path, edits } };
128
153
  }
129
154
  default:
130
155
  return null;