@estebanforge/pi-antigravity-bridge 1.13.0 → 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 +16 -0
- package/README.md +9 -5
- package/extensions/index.ts +12 -2
- package/package.json +1 -1
- package/src/acp/connection.ts +19 -0
- package/src/acp/driver.ts +68 -11
- package/src/config.ts +71 -13
- package/src/provider.ts +149 -48
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,22 @@
|
|
|
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
|
+
|
|
13
|
+
## [1.13.1] - 2026-11-21
|
|
14
|
+
|
|
15
|
+
### Fixed
|
|
16
|
+
|
|
17
|
+
- **ACP resume turns no longer re-send `session/load` for a session the agy process already holds (issue #21).** Reloading restarts agy's update stream, and the old stream's completion signal can land after the next `session/prompt`, ending it within a second with replayed history and zero usage (agy 1.5.13; the reporter logged 2 of 47 loads landing exactly on the broken turns). The connection now remembers sessions it created or loaded and the driver skips the reload for them (logged `session-reuse`); a fresh process still loads once. This reduces exposure to the agy-side race, it does not fix the race. Consequence, deliberate: MCP catalog changes reach a held session only on its next reload (a fresh process's first load, or failed-session recovery) or an agy process restart, so the `/agy bridge` toast now points at `/reload` instead of promising the next `session/load`.
|
|
18
|
+
- **A failed prompt or model-selection step on a reused session reloads it once and retries (issue #21).** agy can drop a long-lived session; the removed per-turn reload used to restore it implicitly. The driver logs `session-reload-retry`, drops the session from the held set, reloads, re-applies model/thought-level/mode (a load does not preserve them), re-arms the idle window, and re-runs the step. Only quiet turns retry: a turn that already streamed text, thinking, tool calls, or parked bridge calls settles ERROR instead, because a re-prompt would run a second generation and double native side effects. Closing turns (abort, timer, connection exit) never retry, and a second failure settles the turn as before.
|
|
19
|
+
- **The ACP tool-priority note no longer suggests native background runs or timers (issue #21).** agy's `run_command` backgrounding (`WaitMsBeforeAsync`) and `schedule` timers rely on agy waking itself after the reply ends, and pi never waits for that: a pi-subagents child is already gone when the wake arrives, and a self-wake turn's bridge calls fail with "no active antigravity turn". The note bans both patterns and, instead of advising full-command foreground waits (past pi's idle cap - 5 minutes by default - the turn and connection die), caps native commands at two minutes and routes longer work through the Pi Bridge bash tool.
|
|
20
|
+
|
|
5
21
|
## [1.13.0] - 2026-11-19
|
|
6
22
|
|
|
7
23
|
### 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` | `
|
|
119
|
-
| `webTools` | `
|
|
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. `
|
|
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 `
|
|
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
|
|
package/extensions/index.ts
CHANGED
|
@@ -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
|
|
|
@@ -1741,7 +1751,7 @@ function registerAgyCommand(pi: ExtensionAPI, ctx: AgyCommandCtx): void {
|
|
|
1741
1751
|
ui?.notify(
|
|
1742
1752
|
ctx.getMcpPort() === null
|
|
1743
1753
|
? `bridge ${next.bridgeTools}. The bridge server is not running; /reload to apply.`
|
|
1744
|
-
: `bridge ${next.bridgeTools}. The active catalog and call guard update now; ACP may
|
|
1754
|
+
: `bridge ${next.bridgeTools}. The active catalog and call guard update now; ACP may keep cached tool schemas until a session reloads or an agy process restarts (/reload applies it).`,
|
|
1745
1755
|
"info",
|
|
1746
1756
|
);
|
|
1747
1757
|
} else {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@estebanforge/pi-antigravity-bridge",
|
|
3
|
-
"version": "1.13.
|
|
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/acp/connection.ts
CHANGED
|
@@ -118,6 +118,8 @@ export class AcpConnection {
|
|
|
118
118
|
#killed = false;
|
|
119
119
|
#suppressUpdates = false;
|
|
120
120
|
#updateSessionId: string | null = null;
|
|
121
|
+
/** Sessions this server process created or loaded and may reuse without session/load (issue #21). */
|
|
122
|
+
#heldSessions = new Set<string>();
|
|
121
123
|
agentInfo: Record<string, unknown> | undefined;
|
|
122
124
|
/** Last known mode/model config echo from set_config_option results. */
|
|
123
125
|
lastConfigOptions: unknown = undefined;
|
|
@@ -292,10 +294,26 @@ export class AcpConnection {
|
|
|
292
294
|
throw new Error("ACP session/new returned no sessionId");
|
|
293
295
|
}
|
|
294
296
|
this.#updateSessionId = sessionId;
|
|
297
|
+
this.#heldSessions.add(sessionId);
|
|
295
298
|
this.lastConfigOptions = result.configOptions;
|
|
296
299
|
return { sessionId };
|
|
297
300
|
}
|
|
298
301
|
|
|
302
|
+
/** Select a session this process already holds, without session/load.
|
|
303
|
+
* Re-loading a held session restarts agy's update stream, and the old
|
|
304
|
+
* stream's completion signal can land after the next session/prompt and
|
|
305
|
+
* end it early with replayed history (agy 1.5.13, issue #21). */
|
|
306
|
+
reuseSession(sessionId: string): boolean {
|
|
307
|
+
if (!this.#heldSessions.has(sessionId)) return false;
|
|
308
|
+
this.#updateSessionId = sessionId;
|
|
309
|
+
return true;
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/** Forget a held session after a failure; the next touch reloads it. */
|
|
313
|
+
dropSession(sessionId: string): void {
|
|
314
|
+
this.#heldSessions.delete(sessionId);
|
|
315
|
+
}
|
|
316
|
+
|
|
299
317
|
async loadSession(sessionId: string, cwd: string): Promise<void> {
|
|
300
318
|
this.#updateSessionId = sessionId;
|
|
301
319
|
this.updateSuppression = true;
|
|
@@ -308,6 +326,7 @@ export class AcpConnection {
|
|
|
308
326
|
this.#sessionOpTimeoutMs(),
|
|
309
327
|
)) as Record<string, unknown> | undefined;
|
|
310
328
|
this.lastConfigOptions = result?.configOptions;
|
|
329
|
+
this.#heldSessions.add(sessionId);
|
|
311
330
|
} finally {
|
|
312
331
|
this.updateSuppression = false;
|
|
313
332
|
}
|
package/src/acp/driver.ts
CHANGED
|
@@ -291,14 +291,20 @@ export class AcpDriver implements TurnDriver {
|
|
|
291
291
|
async #executeTurn(turn: ActiveTurn): Promise<void> {
|
|
292
292
|
const request = turn.request;
|
|
293
293
|
const conn = await this.#ensureConnection(request);
|
|
294
|
+
let reused = false;
|
|
294
295
|
|
|
295
296
|
// Session: load (resume) or create. Load failures fall back to a fresh
|
|
296
297
|
// session — a missing conversation must not fail the turn (9.4).
|
|
297
298
|
try {
|
|
298
299
|
if (request.conversationId) {
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
300
|
+
if (conn.reuseSession(request.conversationId)) {
|
|
301
|
+
reused = true;
|
|
302
|
+
this.#log("session-reuse", { sessionId: request.conversationId });
|
|
303
|
+
} else {
|
|
304
|
+
this.#log("session-load", { sessionId: request.conversationId });
|
|
305
|
+
this.#stats.sessionsLoaded += 1;
|
|
306
|
+
await conn.loadSession(request.conversationId, request.cwd);
|
|
307
|
+
}
|
|
302
308
|
turn.sessionId = request.conversationId;
|
|
303
309
|
} else {
|
|
304
310
|
const created = await this.#newSessionWithOptionalRetry(conn, turn);
|
|
@@ -341,17 +347,11 @@ export class AcpDriver implements TurnDriver {
|
|
|
341
347
|
// are a parity break); mode failure is best-effort (auto policy makes
|
|
342
348
|
// the modes converge anyway).
|
|
343
349
|
try {
|
|
344
|
-
await conn
|
|
345
|
-
if (request.effort) await conn.setConfigOption(turn.sessionId, "thought_level", request.effort);
|
|
350
|
+
await this.#sessionStep(conn, turn, reused, () => this.#applyTurnConfig(conn, turn));
|
|
346
351
|
} catch (err) {
|
|
347
352
|
this.#failTurn(turn, `ACP model selection failed: ${describe(err)}`);
|
|
348
353
|
return;
|
|
349
354
|
}
|
|
350
|
-
try {
|
|
351
|
-
await conn.setConfigOption(turn.sessionId, "mode", acpMode(request.mode, request.skipPermissions));
|
|
352
|
-
} catch (err) {
|
|
353
|
-
this.#log("mode-apply-failed", { message: describe(err) });
|
|
354
|
-
}
|
|
355
355
|
if (turn.closed) return;
|
|
356
356
|
|
|
357
357
|
// Timers: overall (turn deadline, pause-aware) + idle (inactivity).
|
|
@@ -365,7 +365,14 @@ export class AcpDriver implements TurnDriver {
|
|
|
365
365
|
try {
|
|
366
366
|
// Nothing to cancel before the prompt RPC exists; see promptStarted.
|
|
367
367
|
turn.promptStarted = true;
|
|
368
|
-
const result = await
|
|
368
|
+
const result = await this.#sessionStep(
|
|
369
|
+
conn,
|
|
370
|
+
turn,
|
|
371
|
+
reused,
|
|
372
|
+
() => conn.prompt(turn.sessionId, request.prompt, request.images, request.contextBlock),
|
|
373
|
+
// A load does not preserve config; re-apply before re-prompting.
|
|
374
|
+
() => this.#applyTurnConfig(conn, turn),
|
|
375
|
+
);
|
|
369
376
|
if (turn.closed) return;
|
|
370
377
|
turn.sawResult = true;
|
|
371
378
|
// Exact PromptResponse.usage supersedes every partial estimate, but
|
|
@@ -405,6 +412,56 @@ export class AcpDriver implements TurnDriver {
|
|
|
405
412
|
}
|
|
406
413
|
}
|
|
407
414
|
|
|
415
|
+
/** Model + thought level (parity-critical), then mode (best-effort: auto
|
|
416
|
+
* policy converges the modes anyway). */
|
|
417
|
+
#applyTurnConfig(conn: AcpConnection, turn: ActiveTurn): Promise<void> {
|
|
418
|
+
const request = turn.request;
|
|
419
|
+
return (async () => {
|
|
420
|
+
await conn.setConfigOption(turn.sessionId, "model", request.model);
|
|
421
|
+
if (request.effort) await conn.setConfigOption(turn.sessionId, "thought_level", request.effort);
|
|
422
|
+
try {
|
|
423
|
+
await conn.setConfigOption(turn.sessionId, "mode", acpMode(request.mode, request.skipPermissions));
|
|
424
|
+
} catch (err) {
|
|
425
|
+
this.#log("mode-apply-failed", { message: describe(err) });
|
|
426
|
+
}
|
|
427
|
+
})();
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
/** Reload-retry for reused sessions: agy may drop a held session, and the
|
|
431
|
+
* reload is the only restore. Only quiet, live turns retry — a turn that
|
|
432
|
+
* already streamed output or parks would double-run side effects, and a
|
|
433
|
+
* closing turn (abort, timer, connection exit) must settle as-is. */
|
|
434
|
+
async #sessionStep<T>(
|
|
435
|
+
conn: AcpConnection,
|
|
436
|
+
turn: ActiveTurn,
|
|
437
|
+
reused: boolean,
|
|
438
|
+
step: () => Promise<T>,
|
|
439
|
+
onReload?: () => Promise<void>,
|
|
440
|
+
): Promise<T> {
|
|
441
|
+
const retryable = () =>
|
|
442
|
+
reused &&
|
|
443
|
+
!turn.closed &&
|
|
444
|
+
!turn.aborted &&
|
|
445
|
+
turn.abortedBy === null &&
|
|
446
|
+
turn.textDeltas === 0 &&
|
|
447
|
+
turn.thoughtDeltas === 0 &&
|
|
448
|
+
turn.toolCalls.size === 0 &&
|
|
449
|
+
turn.parks === 0;
|
|
450
|
+
try {
|
|
451
|
+
return await step();
|
|
452
|
+
} catch (err) {
|
|
453
|
+
if (!retryable()) throw err;
|
|
454
|
+
this.#log("session-reload-retry", { sessionId: turn.sessionId, message: describe(err) });
|
|
455
|
+
conn.dropSession(turn.sessionId);
|
|
456
|
+
this.#stats.sessionsLoaded += 1;
|
|
457
|
+
await conn.loadSession(turn.sessionId, turn.request.cwd);
|
|
458
|
+
if (!retryable()) throw err;
|
|
459
|
+
this.#armIdle(turn);
|
|
460
|
+
if (onReload) await onReload();
|
|
461
|
+
return await step();
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
|
|
408
465
|
#makeHandle(turn: ActiveTurn): TurnHandle {
|
|
409
466
|
return {
|
|
410
467
|
id: turn.id,
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
-
/**
|
|
103
|
-
*
|
|
104
|
-
*
|
|
105
|
-
function
|
|
106
|
-
|
|
107
|
-
if (
|
|
108
|
-
const
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
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
|
-
/**
|
|
120
|
-
*
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
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
|
|
@@ -186,7 +241,7 @@ export const SYSTEM_PROMPT_END = "[END SYSTEM PROMPT]";
|
|
|
186
241
|
* the user's machine must go through the bridge. Rides the systemPrompt
|
|
187
242
|
* gate: the note ships only when the system prompt ships. */
|
|
188
243
|
export const TOOL_PRIORITY_NOTE =
|
|
189
|
-
"[Tool priority: this conversation runs inside pi, not as a standalone agy session; the user only sees what surfaces in pi. Native interactive tools, for example ask_question, never reach the user. When a Pi Bridge tool covers the same purpose, always use the Pi Bridge tool; for user questions use ask_user_question. Your native file tools such as view_file only read brain artifacts and reject real filesystem paths; for any path on the user's machine use the Pi Bridge tools (read, ls, grep, find, edit, execute). Image files are visible to you: the Pi Bridge read tool returns image files as visible images (png, jpg, webp, gif, bmp), so never claim you cannot view images. Extension Pi tools not declared directly are listed in bridge_tool_info; call bridge_tool_info to inspect their description and schema, then call bridge_call_tool to run them. When a bridge call answers STILL RUNNING, poll bridge_poll_result before doing other work: until you poll, the result (including any image) stays undelivered to you. Delegate subagent work the same way: when pi's tool list includes a delegation tool (for example subagent, Agent, agent_spawn, agent_wait, or subagent_run), always delegate through it and never through the native invoke_subagent, run_subagent, or manage_subagents; use native ones only if no pi delegation tool is listed, because native subagents run inside agy and are invisible to pi and anything watching it. Long-running bridge calls do not fail: after ~20 seconds the bridge answers STILL RUNNING with a callId; fetch the result with bridge_poll_result and poll until it lands.
|
|
244
|
+
"[Tool priority: this conversation runs inside pi, not as a standalone agy session; the user only sees what surfaces in pi. Native interactive tools, for example ask_question, never reach the user. When a Pi Bridge tool covers the same purpose, always use the Pi Bridge tool; for user questions use ask_user_question. Your native file tools such as view_file only read brain artifacts and reject real filesystem paths; for any path on the user's machine use the Pi Bridge tools (read, ls, grep, find, edit, execute). Image files are visible to you: the Pi Bridge read tool returns image files as visible images (png, jpg, webp, gif, bmp), so never claim you cannot view images. Extension Pi tools not declared directly are listed in bridge_tool_info; call bridge_tool_info to inspect their description and schema, then call bridge_call_tool to run them. When a bridge call answers STILL RUNNING, poll bridge_poll_result before doing other work: until you poll, the result (including any image) stays undelivered to you. Delegate subagent work the same way: when pi's tool list includes a delegation tool (for example subagent, Agent, agent_spawn, agent_wait, or subagent_run), always delegate through it and never through the native invoke_subagent, run_subagent, or manage_subagents; use native ones only if no pi delegation tool is listed, because native subagents run inside agy and are invisible to pi and anything watching it. Long-running bridge calls do not fail: after ~20 seconds the bridge answers STILL RUNNING with a callId; fetch the result with bridge_poll_result and poll until it lands. Your turn ends when your reply ends, and pi never waits for agy's own wake-ups: never let a native run_command go to the background (keep WaitMsBeforeAsync at 0 for foreground runs and native commands under two minutes, since longer foreground waits hit pi's idle cap and kill the turn; wrap long commands in timeout and run anything longer through the Pi Bridge bash tool, which keeps it inside your turn, and poll bridge_poll_result if it answers STILL RUNNING) and never use the native schedule tool or timers. A task left running when you reply outlives your turn: its wake-up cannot call Pi Bridge tools, and a delegated subagent session is already gone when it fires.]";
|
|
190
245
|
|
|
191
246
|
/** Assemble the full agy prompt: system prompt block, pi-side digest, user
|
|
192
247
|
* prompt. Empty parts are dropped. Pure; exported for unit testing.
|
|
@@ -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 =
|
|
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
|
-
|
|
1626
|
-
|
|
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
|
-
|
|
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,
|
|
1772
|
-
: buildFullPrompt(sysPrompt, embeddedDigest ? "" : digestFinal,
|
|
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({
|