@estebanforge/pi-antigravity-bridge 1.13.1 → 1.13.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,14 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file.
4
4
 
5
+ ## [1.13.2] - 2026-11-22
6
+
7
+ ### Fixed
8
+
9
+ - **Consecutive user messages no longer drop earlier prompts or images (issue #24).** The provider read only the LAST message, so a turn stacking `[user prompt, before_agent_start note]` shipped the note as the prompt: digest off lost the real prompt entirely, digest on demoted it into `[earlier user message]` continuity context (and could drop it on stream-json under the byte budget), and images attached to earlier messages never reached agy at all. The provider now joins the trailing run of `role: "user"` messages into one prompt with images unioned in order. The run is watermark-bounded - messages at or before the watermark belong to turns agy already saw, so failed-turn backlog never re-executes as prompt (the issue #1 guard holds) - and compaction summaries, branch summaries, and bash-run texts stop the run instead of sweeping into the prompt. The digest window ends at the run start so nothing double-delivers; a whitespace-only trailing message no longer kills the turn with "No user message"; and a joined run that would cross the stream-json silent-drop cap truncates oldest-first with a visible `[truncated]` marker and ships without the digest instead of a doomed turn.
10
+ - **Parse fallbacks surface where they happen, and `0`/`1` count as booleans (issue #23 review follow-up).** `parseBoolish` now also accepts the JSON numbers `0`/`1`; junk values keep the safe default and now warn on session start (toast in the UI, stderr headless) in addition to the `/agy doctor` row, because a hand editor never runs `/agy`. The README no longer misstates the `webTools` default and documents the env/file grammar asymmetry: `AGY_SKIP_PERMISSIONS` takes only `1`/`true` in the env, and a set env var skips the file parse entirely so it warns nothing about the value it overrides.
11
+ - **String booleans in config.json no longer silently enable a disabled option (issue #23).** The boolean keys (`readOnly`, `skipPermissions`, `askTool`, `webTools`, `digest`, `systemPrompt`, `acp.sessionRetryOnTimeout`) passed raw file values through `??`, so a hand-edited `"off"`, `"false"`, or `"0"` - the exact vocabulary the README and `/agy` display - was a truthy string and switched the option ON. The file path now parses the `/agy` vocabulary (`true`/`false`/`on`/`off`/`1`/`0`, case and whitespace tolerated); env parsing is unchanged. Present-but-unparseable values fall back to the key's default and surface a `config warnings:` row in `/agy doctor` instead of failing silently; `readOnly` fails closed (ON) on junk, mirroring `AGY_READONLY`; and `saveConfig` neither rewrites a hand-edited value on an unrelated toggle nor persists the computed warnings field. The same pass closes a crash in the class the reporter's table exposed: a non-string `defaultThinking`, `bridgeTools`, `approvals.gateMode`, `approvals.mode`, or `agent` threw on every bridge call (`.toLowerCase()`/`.trim()` on a non-string) and now falls back to the default like every other junk value.
12
+
5
13
  ## [1.13.1] - 2026-11-21
6
14
 
7
15
  ### Fixed
package/README.md CHANGED
@@ -115,16 +115,20 @@ If `agy models` fails at load (binary missing, auth not done, network stall), a
115
115
 
116
116
  | Key | Values | Default |
117
117
  | --- | --- | --- |
118
- | `askTool` | `on` (register the AskAntigravity delegation tool), `off` (no delegation tool; provider and models only) | `on` |
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` |
118
+ | `askTool` | `true` (register the AskAntigravity delegation tool), `false` (no delegation tool; provider and models only) | `true` |
119
+ | `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` |
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` | 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
- | `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` |
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. `false` = agy prompts contain only your message; a conversation opened mid-session starts without prior pi-side context | `true` |
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 `false` (agy-native behavior) | `true` |
123
+ | `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` |
124
+ | `skipPermissions` | `true`: pass `--dangerously-skip-permissions` so agy tool calls never hang on an unanswerable prompt in non-interactive runs; DANGEROUS: agy executes commands without per-action review (see [Permissions](#permissions)). `false`: prompt instead - hangs any `run_command` in `-p` mode | `true` |
123
125
  | `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
126
  | `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` |
125
127
  | `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` |
126
128
  | `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` |
127
129
 
130
+ 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.
131
+
128
132
  Env overrides: `AGY_BRIDGE_TOOLS`, `AGY_ASK_TOOL`, `AGY_WEB_TOOLS`, `AGY_DIGEST`, `AGY_SYSTEM_PROMPT`, `AGY_TURN_TIMEOUT_MIN`, `AGY_INACTIVITY_TIMEOUT_MIN`, `AGY_ACP_SESSION_TIMEOUT_MS`, `AGY_ACP_SESSION_RETRY`. Env wins over the file, so while `AGY_DIGEST` or `AGY_SYSTEM_PROMPT` is set, the matching `/agy digest` or `/agy system-prompt` toggle persists a value that never takes effect.
129
133
 
130
134
  The `activate_skill` catalog mirrors pi's directory-based skill discovery: the two global dirs plus project dirs, the latter only when pi has trusted the project (same gate pi itself applies). Pi's other skill sources - the `skills` settings array, `package.json` entries, and `--skill` CLI paths - are not mirrored and won't appear in the catalog.
@@ -166,7 +170,7 @@ Plan mode never receives the flag: the flag auto-approves every permission reque
166
170
 
167
171
  ### readOnly
168
172
 
169
- `"readOnly": true` in the config (or `AGY_READONLY=1`, or `/agy readonly on`) is a fail-closed kill switch: every provider turn AND the `AskAntigravity` tool are refused with a visible error instead of running write-capable under a read-only label. Built for callers like `pi -p --no-tools --model antigravity/...` health checks that must never mutate a workspace: with no review-only enforcement available in the CLI (see Permissions), a visible refusal is the only honest behavior. The knob covers provider turns and the ask tool; the web tools still spawn agy for searches. Default false.
173
+ `"readOnly": true` in the config (or `AGY_READONLY=1`, or `/agy readonly on`) is a fail-closed kill switch: every provider turn AND the `AskAntigravity` tool are refused with a visible error instead of running write-capable under a read-only label. Built for callers like `pi -p --no-tools --model antigravity/...` health checks that must never mutate a workspace: with no review-only enforcement available in the CLI (see Permissions), a visible refusal is the only honest behavior. The knob covers provider turns and the ask tool; the web tools still spawn agy for searches. Default false. In the config file, junk values fail closed too: anything that is not `true`/`false`/`on`/`off`/`1`/`0` (or an explicit empty string) reads as ON and adds a `config warnings:` row in `/agy doctor` (issue #23).
170
174
 
171
175
  For per-action review of agy's mutating native tools (`run_command`, `create_file`, `edit_file`, ...), see the [Approval gate](docs/APPROVAL-GATE.md): with it on, the call must pass a pi-side approval (your permission extension, or the built-in ask/allow/deny fallback) before agy executes it.
172
176
 
@@ -68,7 +68,7 @@ import { agyAuthenticationMessage } from "../src/agy-install.js";
68
68
  import { createAgySetupOffer } from "../src/agy-setup.js";
69
69
  import { ensureQueuedMessagesDefaults } from "../src/queued-messages.js";
70
70
  import type { TurnDriver, TurnOutcome } from "../src/driver-types.js";
71
- 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";
71
+ import { configPath, configWarningsMessage, loadConfig, logsDir, MAX_TURN_CAP_MIN, parseCapMinutes, removeLegacyAcpBin, saveConfig, type AcpConfig, type AgyMode, type BridgeTools, type Engine, type ThinkingTier } from "../src/config.js";
72
72
  import { agyMissingMessage, ENGINE_SETTINGS_ROW_ID, engineSettingsRow, isAgyInstalled, savedEngineMessage, showEnginePicker, shouldOfferEnginePicker } from "../src/engine-picker.js";
73
73
  import { agyVersionVerdict, agyUpdateMessage, checkAgyCliVersion, describeAgyVersionCheck, MIN_AGY_ACP_VERSION, MIN_AGY_VERSION, MIN_GEMINI_DIR_VERSION, probeGeminiDirFlag, resolveStreamHomeMode } from "../src/agy-version.js";
74
74
  import { isValidAgyAgentName, listAgyAgents } from "../src/agents.js";
@@ -844,6 +844,14 @@ export default async function (pi: ExtensionAPI): Promise<void> {
844
844
  if (ctx.hasUI) ctx.ui.notify(msg, "warning");
845
845
  else console.error(`[antigravity-bridge] ${msg}`);
846
846
  }
847
+ // A hand editor never runs /agy: surface parse fallbacks where they
848
+ // happen (issue #23). Headless sessions keep the stderr record.
849
+ const configWarnings = loadConfig().parseWarnings;
850
+ if (configWarnings?.length) {
851
+ const msg = configWarningsMessage(configWarnings);
852
+ if (ctx.hasUI) ctx.ui.notify(msg, "warning");
853
+ else console.error(`[antigravity-bridge] ${msg}`);
854
+ }
847
855
  if (!managedAcpCleanupRan) {
848
856
  managedAcpCleanupRan = true;
849
857
  try {
@@ -1280,6 +1288,8 @@ function settingsRows(ctx: AgyCommandCtx): string[] {
1280
1288
  row("bridge tools:", config.bridgeTools),
1281
1289
  row("digest:", config.digest ? "on" : "off"),
1282
1290
  row("system prompt:", config.systemPrompt ? "on" : "off"),
1291
+ // issue #23: unparseable hand-edited values must not fail silently.
1292
+ ...(config.parseWarnings ?? []).map((w, i) => row(i === 0 ? "config warnings:" : "", w)),
1283
1293
  ];
1284
1294
  }
1285
1295
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@estebanforge/pi-antigravity-bridge",
3
- "version": "1.13.1",
3
+ "version": "1.13.2",
4
4
  "description": "Gemini provider for Pi on the Antigravity ACP server (official Google ACP) or the stream-json agy CLI. Use antigravity/* models in Pi. Full /model picker support. Models runs Pi's tools. ToS safe to use.",
5
5
  "keywords": [
6
6
  "pi-package",
package/src/config.ts CHANGED
@@ -140,6 +140,10 @@ export interface AgyConfig {
140
140
  * on the installed pi. The notice never repeats; /agy patch-cleanup is
141
141
  * always available. */
142
142
  patchCleanupNotified?: boolean;
143
+ /** config.json values that were present but unparseable and fell back or
144
+ * failed closed (issue #23). Surfaced by /agy doctor; undefined when
145
+ * every value parsed. Computed per load, never persisted by saveConfig. */
146
+ parseWarnings?: string[];
143
147
  /** Custom agy agent for stream-json turns (`--agent`, /agy agent).
144
148
  * Absent = agy's default agent. ACP turns ignore it (no protocol slot). */
145
149
  agent?: string;
@@ -261,6 +265,55 @@ export function parseCapMinutes(raw: string | number | undefined, fallback: numb
261
265
  return n >= 1 && n <= MAX_TURN_CAP_MIN ? n : fallback;
262
266
  }
263
267
 
268
+ /** Boolean spellings shared by the AGY_* env grammar and config.json (issue
269
+ * #23): the /agy UI's on/off vocabulary plus the JSON literals and digits. */
270
+ const BOOLISH_TRUE = new Set(["1", "true", "on"]);
271
+ const BOOLISH_FALSE = new Set(["0", "false", "off"]);
272
+
273
+ /** Parse a config.json boolean that a hand editor may have written as a
274
+ * string ("off", "false", "0" - the README and /agy vocabulary) or as the
275
+ * JSON numbers 0/1. Present but unparseable values fall back to the given
276
+ * default and warn; the silence is what made issue #23 invisible. */
277
+ function parseBoolish(raw: unknown, label: string, fallback: boolean, warnings: string[]): boolean {
278
+ if (typeof raw === "boolean") return raw;
279
+ if (raw === 0 || raw === 1) return raw === 1;
280
+ if (typeof raw === "string") {
281
+ const v = raw.trim().toLowerCase();
282
+ if (BOOLISH_TRUE.has(v)) return true;
283
+ if (BOOLISH_FALSE.has(v)) return false;
284
+ }
285
+ if (raw === undefined || raw === null) return fallback;
286
+ warnings.push(`${label}: ${JSON.stringify(raw)} is not a recognized boolean (true/false, on/off, 1/0); using default ${fallback}`);
287
+ return fallback;
288
+ }
289
+
290
+ /** File-path readOnly parse: the AGY_READONLY env grammar mirrored (issue
291
+ * #23). Explicit blank and spelled-out falsities are OFF, every other
292
+ * present value counts as ON so a typo can never disable the safety knob. */
293
+ function parseReadOnlyValue(raw: unknown, warnings: string[]): boolean {
294
+ const failClosed = (rawValue: unknown): boolean => {
295
+ warnings.push(`readOnly: ${JSON.stringify(rawValue)} is not a recognized boolean (true/false, on/off, 1/0); failing closed to true`);
296
+ return true;
297
+ };
298
+ if (typeof raw === "boolean") return raw;
299
+ if (typeof raw === "string") {
300
+ if (raw === "") return false;
301
+ const v = raw.trim().toLowerCase();
302
+ if (BOOLISH_FALSE.has(v)) return false;
303
+ if (BOOLISH_TRUE.has(v)) return true;
304
+ return failClosed(raw);
305
+ }
306
+ if (raw === undefined || raw === null) return DEFAULTS.readOnly;
307
+ return failClosed(raw);
308
+ }
309
+
310
+ /** One-line startup/doctor summary for unparseable config values (issue
311
+ * #23). The toast points at /agy doctor because the per-value detail
312
+ * (label, raw value, fallback) lives in the parseWarnings row list. */
313
+ export function configWarningsMessage(warnings: string[]): string {
314
+ return `config.json: ${warnings.length} unparseable value${warnings.length === 1 ? "" : "s"} fell back to defaults (readOnly fails closed); run /agy doctor for details.`;
315
+ }
316
+
264
317
  /** Read the raw config file (no defaults, no env). Shared by loadConfig and
265
318
  * saveConfig so persisted writes can never bake env overrides into the file. */
266
319
  function readConfigFile(configPath: string): Partial<AgyConfig> {
@@ -294,6 +347,7 @@ export function removeLegacyAcpBin(configFile: string = configPath()): boolean {
294
347
  /** Load config merged over defaults. Env vars override the file when set. */
295
348
  export function loadConfig(configFile: string = configPath()): AgyConfig {
296
349
  let file: Partial<AgyConfig> = readConfigFile(configFile);
350
+ const parseWarnings: string[] = [];
297
351
 
298
352
  // Env overrides file (matches the skipPermissions pattern).
299
353
  // The naive OR `env === "plan" || file.mode === "plan"` would ignore an
@@ -323,7 +377,7 @@ export function loadConfig(configFile: string = configPath()): AgyConfig {
323
377
  const skipPermissions =
324
378
  envPerm !== undefined
325
379
  ? envPerm === "1" || envPerm.toLowerCase() === "true"
326
- : file.skipPermissions ?? DEFAULTS.skipPermissions;
380
+ : parseBoolish(file.skipPermissions, "skipPermissions", DEFAULTS.skipPermissions, parseWarnings);
327
381
 
328
382
  const envReadOnly = process.env.AGY_READONLY;
329
383
  // Fail-closed parse for a safety knob: empty string means the user
@@ -334,7 +388,7 @@ export function loadConfig(configFile: string = configPath()): AgyConfig {
334
388
  ? envReadOnly === ""
335
389
  ? false
336
390
  : !["0", "false", "off"].includes(envReadOnly.trim().toLowerCase())
337
- : file.readOnly ?? DEFAULTS.readOnly;
391
+ : parseReadOnlyValue(file.readOnly, parseWarnings);
338
392
 
339
393
  const defaultModelRaw =
340
394
  process.env.AGY_DEFAULT_MODEL ?? file.defaultModel ?? DEFAULTS.defaultModel;
@@ -342,19 +396,19 @@ export function loadConfig(configFile: string = configPath()): AgyConfig {
342
396
  typeof defaultModelRaw === "string" ? defaultModelRaw.trim() || DEFAULTS.defaultModel : DEFAULTS.defaultModel;
343
397
 
344
398
  const envThink = process.env.AGY_DEFAULT_THINKING;
345
- const thinkRaw = (envThink ?? file.defaultThinking ?? DEFAULTS.defaultThinking).toLowerCase();
399
+ const thinkRaw = String(envThink ?? file.defaultThinking ?? DEFAULTS.defaultThinking).toLowerCase();
346
400
  const defaultThinking: ThinkingTier =
347
401
  thinkRaw === "low" || thinkRaw === "high" ? thinkRaw : "medium";
348
402
 
349
403
  const askTool = process.env.AGY_ASK_TOOL !== undefined
350
404
  ? ["1", "true", "on"].includes(process.env.AGY_ASK_TOOL.toLowerCase())
351
- : file.askTool ?? DEFAULTS.askTool;
405
+ : parseBoolish(file.askTool, "askTool", DEFAULTS.askTool, parseWarnings);
352
406
 
353
407
  const webTools = process.env.AGY_WEB_TOOLS !== undefined
354
408
  ? ["1", "true", "on"].includes(process.env.AGY_WEB_TOOLS.toLowerCase())
355
- : file.webTools ?? DEFAULTS.webTools;
409
+ : parseBoolish(file.webTools, "webTools", DEFAULTS.webTools, parseWarnings);
356
410
 
357
- const bridgeRaw = (process.env.AGY_BRIDGE_TOOLS ?? file.bridgeTools ?? DEFAULTS.bridgeTools).toLowerCase();
411
+ const bridgeRaw = String(process.env.AGY_BRIDGE_TOOLS ?? file.bridgeTools ?? DEFAULTS.bridgeTools).toLowerCase();
358
412
  const bridgeTools: BridgeTools =
359
413
  bridgeRaw === "none" || bridgeRaw === "all" || bridgeRaw === "mcp"
360
414
  ? bridgeRaw
@@ -376,12 +430,12 @@ export function loadConfig(configFile: string = configPath()): AgyConfig {
376
430
 
377
431
  const digest = process.env.AGY_DIGEST !== undefined
378
432
  ? ["1", "true", "on"].includes(process.env.AGY_DIGEST.toLowerCase())
379
- : file.digest ?? true;
433
+ : parseBoolish(file.digest, "digest", DEFAULTS.digest, parseWarnings);
380
434
 
381
435
  const envSys = process.env.AGY_SYSTEM_PROMPT;
382
436
  const systemPrompt = envSys !== undefined
383
437
  ? ["1", "true", "on"].includes(envSys.toLowerCase())
384
- : file.systemPrompt ?? DEFAULTS.systemPrompt;
438
+ : parseBoolish(file.systemPrompt, "systemPrompt", DEFAULTS.systemPrompt, parseWarnings);
385
439
 
386
440
  // Turn caps, minutes. Env wins over the file (same pattern as mode).
387
441
  const turnTimeoutMin = parseCapMinutes(
@@ -395,12 +449,12 @@ export function loadConfig(configFile: string = configPath()): AgyConfig {
395
449
 
396
450
  // Approval gate (docs/TODO.md 2.5). Unknown values fall back to "auto"
397
451
  // so a typo can never silently force the gate on.
398
- const gateRaw = (process.env.AGY_APPROVALS ?? file.approvals?.gateMode ?? DEFAULTS.approvals.gateMode).toLowerCase();
452
+ const gateRaw = String(process.env.AGY_APPROVALS ?? file.approvals?.gateMode ?? DEFAULTS.approvals.gateMode).toLowerCase();
399
453
  const gateMode: GateMode =
400
454
  gateRaw === "shadow" || gateRaw === "dedicated" || gateRaw === "off"
401
455
  ? gateRaw
402
456
  : "auto";
403
- const askRaw = (process.env.AGY_APPROVALS_MODE ?? file.approvals?.mode ?? DEFAULTS.approvals.mode).toLowerCase();
457
+ const askRaw = String(process.env.AGY_APPROVALS_MODE ?? file.approvals?.mode ?? DEFAULTS.approvals.mode).toLowerCase();
404
458
  const gateAskMode: GateAskMode =
405
459
  askRaw === "allow" || askRaw === "deny"
406
460
  ? askRaw
@@ -421,13 +475,14 @@ export function loadConfig(configFile: string = configPath()): AgyConfig {
421
475
  const envSessionRetry = process.env.AGY_ACP_SESSION_RETRY;
422
476
  const sessionRetryOnTimeout = envSessionRetry !== undefined
423
477
  ? ["1", "true", "on"].includes(envSessionRetry.toLowerCase())
424
- : fileAcp.sessionRetryOnTimeout === true;
478
+ : parseBoolish(fileAcp.sessionRetryOnTimeout, "acp.sessionRetryOnTimeout", DEFAULTS.acp.sessionRetryOnTimeout, parseWarnings);
425
479
  const acp: AcpConfig = { usageEstimate, sessionTimeoutMs, sessionRetryOnTimeout };
426
480
 
427
481
  // Custom agent for stream-json turns (--agent). Env wins over the file
428
482
  // (same pattern as mode). Normalized (trim/cap/control-strip); an empty
429
483
  // result means agy's default agent.
430
- const agent = normalizeAgyAgentName(process.env.AGY_AGENT ?? file.agent);
484
+ const agentRaw: unknown = process.env.AGY_AGENT ?? file.agent;
485
+ const agent = normalizeAgyAgentName(typeof agentRaw === "string" ? agentRaw : undefined);
431
486
 
432
487
  return {
433
488
  engine,
@@ -448,6 +503,7 @@ export function loadConfig(configFile: string = configPath()): AgyConfig {
448
503
  agent,
449
504
  approvals: { gateMode, mode: gateAskMode },
450
505
  patchCleanupNotified: file.patchCleanupNotified === true,
506
+ parseWarnings: parseWarnings.length > 0 ? parseWarnings : undefined,
451
507
  };
452
508
  }
453
509
 
@@ -483,7 +539,7 @@ function writeConfigJson(configPath: string, value: unknown): void {
483
539
  * disk on any unrelated save, outliving the env var). Nested objects are
484
540
  * re-normalized to their known keys: a raw passthrough would resurrect
485
541
  * legacy keys (acp.permissions) that loadConfig normalization drops. */
486
- export type ConfigPatch = Partial<Omit<AgyConfig, "acp">> & { acp?: Partial<AcpConfig> };
542
+ export type ConfigPatch = Partial<Omit<AgyConfig, "acp" | "parseWarnings">> & { acp?: Partial<AcpConfig> };
487
543
 
488
544
  export function saveConfig(patch: ConfigPatch, configFile: string = configPath()): AgyConfig {
489
545
  const file = readConfigFile(configFile);
@@ -517,6 +573,8 @@ export function saveConfig(patch: ConfigPatch, configFile: string = configPath()
517
573
  ...restPatch,
518
574
  acp: mergedAcp,
519
575
  engine: narrowEngine(String(persistedEngine).toLowerCase()),
576
+ // Computed per load; a raw file spread must never persist it.
577
+ parseWarnings: undefined,
520
578
  };
521
579
  writeConfigJson(configFile, next);
522
580
  return next;
package/src/provider.ts CHANGED
@@ -99,33 +99,80 @@ function zeroUsage(): Usage {
99
99
  };
100
100
  }
101
101
 
102
- /** Extract the latest user message as a flat prompt string. agy maintains its
103
- * own conversation history via --conversation, so we collapse pi's structured
104
- * message to text. Returns null if the last message isn't a user message. */
105
- function extractUserPrompt(context: TranscriptContext): string | null {
106
- const last = context.messages[context.messages.length - 1];
107
- if (!last || last.role !== "user") return null;
108
- const content = last.content;
109
- if (typeof content === "string") return content;
110
- // Flatten text blocks; images ride separately via extractImages (native
111
- // blocks on ACP, staged files on stream-json via prompt-images.ts).
112
- return content
113
- .filter((b): b is { type: "text"; text: string } => b.type === "text")
114
- .map((b) => b.text)
115
- .join("\n")
116
- .trim() || null;
102
+ /** Flatten one message's text + image blocks (pi-ai ImageContent: base64
103
+ * data + mimeType). The pre-#24 extraction shape, kept for the untrusted-
104
+ * boundary fallback and the single-message resume paths. */
105
+ function lastMessageParts(m: Message | undefined): { text: string | null; images: Array<{ data: string; mimeType: string }> } {
106
+ if (!m || m.role !== "user") return { text: null, images: [] };
107
+ if (typeof m.content === "string") return { text: m.content.trim() || null, images: [] };
108
+ const images: Array<{ data: string; mimeType: string }> = [];
109
+ const texts: string[] = [];
110
+ for (const b of m.content) {
111
+ if (b.type === "text") texts.push(b.text);
112
+ else if (b.type === "image") images.push({ data: b.data, mimeType: b.mimeType });
113
+ }
114
+ return { text: texts.join("\n").trim() || null, images };
117
115
  }
118
116
 
119
- /** Image blocks of the latest user message (pi-ai ImageContent: base64 data
120
- * + mimeType). On the ACP engine they ride session/prompt as native
121
- * content blocks; on stream-json they are staged to temp files and the
122
- * prompt names the paths (see prompt-images.ts). */
123
- function extractImages(context: TranscriptContext): Array<{ data: string; mimeType: string }> {
124
- const last = context.messages[context.messages.length - 1];
125
- if (!last || last.role !== "user" || typeof last.content === "string") return [];
126
- return last.content
127
- .filter((b): b is { type: "image"; data: string; mimeType: string } => b.type === "image")
128
- .map((b) => ({ data: b.data, mimeType: b.mimeType }));
117
+ /** pi-side history shapes that can sit inside a trailing user run; a run
118
+ * member matching one truncates the run to the messages after it. */
119
+ function isBacklogUserShape(text: string): boolean {
120
+ return text.includes(COMPACTION_MARKER) || text.startsWith(BRANCH_SUMMARY_PREFIX) || text.startsWith(BASH_RUN_PREFIX);
121
+ }
122
+
123
+ /** The trailing run of role:"user" messages is the active turn: pi stacks
124
+ * the prompt, queued nextTurn messages, and before_agent_start notes as
125
+ * consecutive user messages, so reading only the LAST one dropped every
126
+ * earlier prompt text and image (issue #24). The run is left-bounded by
127
+ * the validated watermark: messages at or before it belong to turns agy
128
+ * already saw (a failed pass never advances the watermark, so joining them
129
+ * could re-execute a half-run task; they stay digest/continuity context).
130
+ * A mismatched boundary fingerprint makes the count untrustworthy, so the
131
+ * run collapses to the last message - the pre-#24 behavior - instead of
132
+ * guessing. `texts` feeds the stream-json per-member truncation guard. */
133
+ function extractTrailingUserRun(
134
+ messages: Message[],
135
+ watermark: number,
136
+ boundaryTrusted: boolean,
137
+ ): { prompt: string | null; images: Array<{ data: string; mimeType: string }>; runStart: number; texts: string[] } {
138
+ const last = messages.length - 1;
139
+ const empty = { prompt: null, images: [], runStart: messages.length, texts: [] };
140
+ if (last < 0 || messages[last].role !== "user") return empty;
141
+ if (!boundaryTrusted) {
142
+ const only = lastMessageParts(messages[last]);
143
+ return { prompt: only.text, images: only.images, runStart: last, texts: only.text ? [only.text] : [] };
144
+ }
145
+ let start = last;
146
+ while (start > 0 && messages[start - 1].role === "user") start--;
147
+ for (let i = start; i < messages.length; i++) {
148
+ if (isBacklogUserShape(blocksToText(messages[i].content))) start = i + 1;
149
+ }
150
+ if (watermark > start) start = watermark;
151
+ if (start > last) {
152
+ // The stored count reaches past the run (a transcript that shrank
153
+ // under a matching or stale boundary - pi's retry re-emits look
154
+ // exactly like this): the pre-#24 read is the only safe one.
155
+ const only = lastMessageParts(messages[last]);
156
+ return { prompt: only.text, images: only.images, runStart: last, texts: only.text ? [only.text] : [] };
157
+ }
158
+ const texts: string[] = [];
159
+ const images: Array<{ data: string; mimeType: string }> = [];
160
+ for (let i = start; i <= last; i++) {
161
+ const m = messages[i];
162
+ if (typeof m.content === "string") {
163
+ if (m.content.trim()) texts.push(m.content);
164
+ continue;
165
+ }
166
+ for (const b of m.content) {
167
+ if (b.type === "text") {
168
+ if (b.text.trim()) texts.push(b.text);
169
+ } else if (b.type === "image") {
170
+ images.push({ data: b.data, mimeType: b.mimeType });
171
+ }
172
+ }
173
+ }
174
+ const prompt = texts.join("\n\n").trim() || null;
175
+ return { prompt, images, runStart: start, texts };
129
176
  }
130
177
 
131
178
  // --- G1: pi-side context digest --------------------------------------------------
@@ -140,6 +187,14 @@ function extractImages(context: TranscriptContext): Array<{ data: string; mimeTy
140
187
 
141
188
  const COMPACTION_MARKER = "compacted into the following summary";
142
189
 
190
+ /** pi's convertToLlm maps branch summaries and bash runs to role:"user", so
191
+ * a watermark-0 transcript can hold them as backlog inside a trailing user
192
+ * run. Neither contains COMPACTION_MARKER, so the run scan (issue #24)
193
+ * needs their shapes too (core/messages.js BRANCH_SUMMARY_PREFIX /
194
+ * bashExecutionToText). */
195
+ const BRANCH_SUMMARY_PREFIX = "The following is a summary of a branch";
196
+ const BASH_RUN_PREFIX = "Ran `";
197
+
143
198
  /** Synthetic prompt for a resume turn (issue #8): pi's retry dropped the
144
199
  * failed attempt from the projected context (_omitRecoveryAttempt), leaving
145
200
  * a toolResult or assistant tail with no live agy turn. The bound
@@ -253,8 +308,14 @@ export interface DigestOptions {
253
308
  /** Include the trailing message in the delta window instead of reserving
254
309
  * it as the current user prompt. Used when resuming into a fresh
255
310
  * post-compaction conversation whose transcript ends in a toolResult or
256
- * assistant message. Default false. */
311
+ * assistant message. Default false. Ignored when `end` is set. */
257
312
  includeLast?: boolean;
313
+ /** Exclusive window end. The trailing user run (issue #24) joins the
314
+ * prompt, so its members must not reappear as digest continuity
315
+ * context; the provider passes the run's start index here. Default:
316
+ * length-1 (reserve the last message as the prompt), or length when
317
+ * includeLast is set. */
318
+ end?: number;
258
319
  }
259
320
 
260
321
  /** Soft cap on the digest body when no tighter budget applies. */
@@ -367,7 +428,12 @@ export function buildContextDigest(
367
428
  } else if (watermark > messages.length) {
368
429
  start = 0;
369
430
  }
370
- const end = opts.includeLast ? messages.length : Math.max(0, messages.length - 1);
431
+ const end =
432
+ opts.end !== undefined
433
+ ? opts.end
434
+ : opts.includeLast
435
+ ? messages.length
436
+ : Math.max(0, messages.length - 1);
371
437
  for (let i = start; i < end; i++) {
372
438
  const m = messages[i];
373
439
  if (m.role === "assistant") {
@@ -1622,8 +1688,24 @@ async function runTurnDriver(
1622
1688
  return;
1623
1689
  }
1624
1690
  // Fresh pass, or a stranded escalated result being re-delivered.
1625
- const userPrompt = extractUserPrompt(context);
1626
- const images = extractImages(context);
1691
+ // Watermark first: the trailing user run is left-bounded by it, so
1692
+ // failed-turn backlog never joins the prompt (issue #24 / issue #1).
1693
+ const rawWatermark = existing?.lastMessageCount ?? 0;
1694
+ // Boundary fingerprint check (see boundaryFingerprint): a transcript
1695
+ // mutated under the stored count (/tree, /fork, context-hook rewrites)
1696
+ // resets the delta to the full digest instead of a silently wrong one.
1697
+ // Records written before the fingerprint existed (digestBoundary unset)
1698
+ // trust the count: the old code advanced it the same way, so reseting
1699
+ // would dump a one-time full delta of history agy already holds.
1700
+ const storedBoundary = existing?.digestBoundary;
1701
+ const boundaryTrusted =
1702
+ rawWatermark === 0 ||
1703
+ storedBoundary === undefined ||
1704
+ storedBoundary === boundaryFingerprint(context.messages[rawWatermark - 1]);
1705
+ const watermark = rawWatermark > 0 && boundaryTrusted ? rawWatermark : 0;
1706
+ const run = extractTrailingUserRun(context.messages, watermark, boundaryTrusted);
1707
+ const userPrompt = run.prompt;
1708
+ const images = run.images;
1627
1709
  // Resume pass (issue #8): pi's retry dropped the failed attempt from the
1628
1710
  // projected context, so the transcript ends in a toolResult or assistant
1629
1711
  // message and there is no user prompt, no pending park, and nothing
@@ -1666,20 +1748,6 @@ async function runTurnDriver(
1666
1748
  finalize(stream, blocks, "error", "No user message to send to agy.");
1667
1749
  return;
1668
1750
  }
1669
- const rawWatermark = existing?.lastMessageCount ?? 0;
1670
- // Boundary fingerprint check (see boundaryFingerprint): a transcript
1671
- // mutated under the stored count (/tree, /fork, context-hook rewrites)
1672
- // resets the delta to the full digest instead of a silently wrong one.
1673
- // Records written before the fingerprint existed (digestBoundary unset)
1674
- // trust the count: the old code advanced it the same way, so reseting
1675
- // would dump a one-time full delta of history agy already holds.
1676
- const storedBoundary = existing?.digestBoundary;
1677
- const watermark =
1678
- rawWatermark > 0 &&
1679
- (storedBoundary === undefined ||
1680
- storedBoundary === boundaryFingerprint(context.messages[rawWatermark - 1]))
1681
- ? rawWatermark
1682
- : 0;
1683
1751
  // Late and resume turns re-open the conversation with a synthetic
1684
1752
  // prompt; the digest would re-send context agy already holds (against a
1685
1753
  // stale watermark: a failed pass never advances it), so skip it.
@@ -1687,15 +1755,48 @@ async function runTurnDriver(
1687
1755
  // once even if config.digest is false, because the old agy conversation
1688
1756
  // was rotated and the fresh conversation has no prior history.
1689
1757
  const engine = deps.engine ?? config.engine;
1690
- const promptBytes = Buffer.byteLength(prompt ?? "", "utf8");
1758
+ // A joined run can outgrow the stream-json silent-drop cap on its own
1759
+ // (issue #24): the digest budget used to absorb these bytes. Truncate
1760
+ // oldest-first, keeping the newest run members; synthetic resume
1761
+ // prompts have no run behind them and keep their existing behavior.
1762
+ let deliveredPrompt = prompt ?? "";
1763
+ let runTruncated = false;
1764
+ if (engine !== "acp" && run.texts.length > 0) {
1765
+ const budget = STREAM_JSON_PROMPT_CAP - STREAM_JSON_PROMPT_MARGIN;
1766
+ if (Buffer.byteLength(deliveredPrompt, "utf8") > budget) {
1767
+ const kept: string[] = [];
1768
+ let used = 0;
1769
+ for (let i = run.texts.length - 1; i >= 0; i--) {
1770
+ const cost = Buffer.byteLength(run.texts[i], "utf8") + 2;
1771
+ if (used + cost > budget - 16) break;
1772
+ kept.unshift(run.texts[i]);
1773
+ used += cost;
1774
+ }
1775
+ runTruncated = true;
1776
+ if (kept.length > 0) {
1777
+ deliveredPrompt = `[truncated]\n${kept.join("\n\n")}`;
1778
+ } else {
1779
+ // A single member bigger than the whole budget: hard-slice it
1780
+ // (visible truncation) rather than ship a silently dropped
1781
+ // turn (issue #2) or an empty prompt.
1782
+ const head = Buffer.from(run.texts[run.texts.length - 1], "utf8").subarray(0, Math.max(0, budget - 32));
1783
+ deliveredPrompt = `[truncated]\n${head.toString("utf8")}`;
1784
+ }
1785
+ }
1786
+ }
1787
+ const promptBytes = Buffer.byteLength(deliveredPrompt, "utf8");
1788
+ // A truncated run ships alone: the digest budget is spent, and a
1789
+ // marker-only digest beside a sliced prompt is noise that also breaks
1790
+ // agy's server-side prompt cache.
1791
+ const wantDigest = (config.digest || compactionHandoff || compactionResume) && !runTruncated;
1691
1792
  const maxChars = digestMaxCharsForEngine(engine, promptBytes);
1692
- const wantDigest = config.digest || compactionHandoff || compactionResume;
1693
1793
  const digest =
1694
1794
  wantDigest && maxChars !== null && late.length === 0 && !resume
1695
1795
  ? buildContextDigest(context.messages, watermark, {
1696
1796
  bound: Boolean(existing?.conversationId),
1697
1797
  seenSummaryId: existing?.digestSummaryId,
1698
1798
  maxChars,
1799
+ end: run.runStart,
1699
1800
  includeLast: compactionResume,
1700
1801
  })
1701
1802
  : "";
@@ -1768,8 +1869,8 @@ async function runTurnDriver(
1768
1869
  const runImages = [...images, ...late.flatMap((l) => l.images ?? [])];
1769
1870
  const fullPrompt =
1770
1871
  (late.length > 0
1771
- ? buildLateResultPrompt(late, prompt || undefined)
1772
- : buildFullPrompt(sysPrompt, embeddedDigest ? "" : digestFinal, prompt ?? "")) +
1872
+ ? buildLateResultPrompt(late, deliveredPrompt || undefined)
1873
+ : buildFullPrompt(sysPrompt, embeddedDigest ? "" : digestFinal, deliveredPrompt)) +
1773
1874
  stageImageNote(runImages);
1774
1875
  try {
1775
1876
  handle = await deps.driver.run({