@timmyjl12/pi-agy-bridge 0.3.1 → 0.3.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/ARCHITECTURE.md CHANGED
@@ -8,10 +8,16 @@ pi-agy-bridge is a pi provider (`createProvider` from pi-ai 1.5) whose models ar
8
8
  pi -> streamAgy(model, context, options)
9
9
  1 splitContext system prompt + current tools | history (up to the last assistant message) | latest input
10
10
  2 hashChain sha256 chain over [system, tools, model, thought] then each message
11
+ 2b context guard estimateContextTokens + 15% safety + output reserve must fit model.contextWindow;
12
+ on provider/api handoff, recompute from all pi messages instead of trusting the old provider's usage
13
+ otherwise context_length_exceeded before any agy call, so pi compacts and retries
11
14
  3 pool.acquire reuse a pooled agy session only if it already holds exactly this prefix
12
15
  otherwise session/new (+ system prompt and tool protocol as _meta append, or inline in step 4 when
13
16
  PI_AGY_SYSTEM_PROMPT=inline or the append was refused earlier) and set model / thought_level
14
- 4 buildPrompt [resource pi://conversation.md (history, only for a fresh session)] + text(latest input) + images
17
+ 4 buildPrompt fresh session: [resource pi://conversation.md, ?part=2, ... (history, <=128 KiB each)]
18
+ + text(latest input, <=128 KiB chunks) + images
19
+ 4b sequential replay when total replay exceeds 128 KiB: each part is acknowledged in its own bounded prompt turn
20
+ within that agy session, then the actual request is sent; usage from every part is aggregated
15
21
  5 session/prompt agy streams agent_thought_chunk / agent_message_chunk
16
22
  6 Translator thought -> thinking block; message -> ToolCallStreamParser -> text blocks | toolCall
17
23
  7 first complete <pi_tool_call> block -> toolCall block, session/cancel, stopReason toolUse
@@ -28,7 +34,7 @@ pi then executes the tool and calls again with the result; the request that carr
28
34
  | `index.ts` | extension entry: provider, `/agy-bridge`, shutdown handling, one-time notices |
29
35
  | `provider.ts` | `createProvider`: cheap `check`, `resolve`, `fetchModels`, `filterModels`, stream functions |
30
36
  | `runtime.ts` | config, shared pool, compatibility report, availability hint, observed context windows |
31
- | `stream.ts` | `streamAgy`: events, silence/total timeouts, cancel, usage, error mapping |
37
+ | `stream.ts` | `streamAgy`: events, silence/idle timeouts, sequential UTF-8 replay, cancel, usage, error mapping |
32
38
  | `session-pool.ts` | the shared `agy acp` process and pooled sessions; reuse rule; TTL, LRU, idle exit; invalidation |
33
39
  | `transcript.ts` | context split, history/latest serialisation, canonical messages, hash chain |
34
40
  | `tool-protocol.ts` | protocol prompt + tool catalogue, streaming parser for `<pi_tool_call>` blocks |
@@ -59,7 +65,9 @@ A pooled session is reused only when all of these hold:
59
65
  3. the number of new messages equals the new input (`latestCount`)
60
66
  4. the pi session id matches and nobody invalidated it
61
67
 
62
- Invalidation comes from three places: pi-context's rewrite registry (`Symbol.for("claude-bridge:markRebuildHooks")`), pi-ai `cleanupSessionResources` (`/fresh`, session end), and the prefix check itself as the backstop. Replaying is always correct; reuse saves a `session/new` (about a second), the resent history and, above roughly 16k prompt tokens, most of the prompt cost: agy's cache works only inside a continuing session (three fresh sessions with an identical 22.9k prefix cached nothing). A session that ended at a tool call is kept for `PI_AGY_TOOL_TTL_MIN` (30 min) because pi may run a long tool; any retained session also keeps the process alive.
68
+ Invalidation comes from three places: pi-context's rewrite registry (`Symbol.for("claude-bridge:markRebuildHooks")`), pi-ai `cleanupSessionResources` (`/fresh`, session end), and the prefix check itself as the backstop. Boundary compaction and rollover notify the registry; pi-context shake currently does not, but its edits change the hash chain and therefore force the same safe fresh-session replay even without a notification. Busy/opening leases use invalidation sequence markers, and repeat invalidation refreshes recency before the bounded map evicts its oldest entry. Replaying is always correct; reuse saves a `session/new` (about a second), the resent history and, above roughly 16k prompt tokens, most of the prompt cost: agy's cache works only inside a continuing session (three fresh sessions with an identical 22.9k prefix cached nothing). A session that ended at a tool call is kept for `PI_AGY_TOOL_TTL_MIN` (30 min) because pi may run a long tool; any retained session also keeps the process alive.
69
+
70
+ agy truncates oversized converted prompt content (a real failure retained roughly 192 KiB). `buildPrompt` therefore splits replayed history, inline instructions and latest input into ordered blocks of at most 128 KiB of UTF-8. Embedded history uses `pi://conversation.md`, then `?part=2`, `?part=3`, and so on; the plain-text fallback splits its combined text the same way. Chunking never splits a Unicode codepoint. When total replay exceeds that budget, the blocks become sequential bounded prompt turns within one agy session: the model acknowledges each historical part, receives the actual request only after every part arrives, and the bridge aggregates usage from all parts instead of hiding replay cost. The completed session is then reused under the normal exact-prefix rule. Before acquisition, a separate model-window guard uses pi-ai's `estimateContextTokens` plus 15% safety and the output reserve (up to 32,768 tokens); if that cannot fit `model.contextWindow`, the bridge returns `context_length_exceeded` before any model call so pi compacts instead of replaying beyond the backend limit. The last assistant's usage is used only when it belongs to the same provider/api; on a handoff (for example agy → neuralwatt), every pi message is re-estimated because the old provider's usage can describe a compacted session mirror rather than pi's full history. The 8 MiB `PI_AGY_MAX_REPLAY_KB` total guard remains independent of these per-block and token-window limits. A real agy check with a late-history synthetic fact returned the fact with zero truncation markers and 42,164 cacheRead tokens.
63
71
 
64
72
  ## Process model
65
73
 
package/README.md CHANGED
@@ -4,7 +4,7 @@ Use Google Antigravity models (Gemini, Claude, GPT-OSS) in [pi](https://github.c
4
4
 
5
5
  It follows the design of `pi-claude-code`: **pi keeps the conversation, the approvals and the tool execution; agy is only the model.** Every pi request becomes one ACP prompt turn. When the model wants a pi tool it writes a small tool-call block, pi runs the tool, and the next request carries the result. Nothing is parked between requests, so a slow tool (a long `pytest` run, a user dialog) can take as long as it needs and there is no turn time limit.
6
6
 
7
- > Status: 0.3.1. Active agy turns no longer hit pi's idle request timeout merely because their total duration exceeds it: every ACP update refreshes that deadline, while the independent silence guard still cancels inactive turns. 0.3.0: agy 1.5.16 and the `google-antigravity` SDK 0.1.24 are now tested. agy 1.5.16 retired `gemini-pro-orchestrator-g1-pro`; its orchestrators are now `gemini-pro-orchestrator` (Carbon), `gemini-pro-orchestrator-argon` and `gemini-pro-orchestrator-neon`, and Gemini 4 Carbon (low, medium, high) is new. The SDK change (a removed `InputConfig.use_interactions_api` field) does not touch the bridge, which uses the SDK only as a drift canary. Stalls and timeouts are now easier to diagnose: an extra account keeps its previous agy log as `acp.prev.log`, and with `PI_AGY_TRACE=1` a stalled or timed-out turn records what agy last sent and when. agy 1.5.16 also forwards subagent and workflow questions to the editor; the bridge's carrier agent has no agy tools, subagents or skills, so agy never asks them here. 0.2.1: Extra-account sign-in works on agy 1.5.14: agy now prints a link and waits for the authorization code, so the bridge opens the link and asks for the code in a dialog. 0.2.0: Multiple Antigravity accounts: each extra account runs as its own provider `agy-<alias or id>` with its own login, managed from `/agy-bridge menu` or the `/agy-bridge` account commands; verified live on agy 1.5.14 with two Google accounts answering side by side. agy 1.5.14 is now tested: it refuses pi's appended system prompt silently (no notice for ~2 min), which `auto` now detects with a 30 s refusal probe and answers inline (see [Multiple Antigravity accounts](#multiple-antigravity-accounts)). 0.1.5: the default bridge home now honors Pi's configured agent directory (`PI_CODING_AGENT_DIR`). Every Pi session shutdown now recycles the outgoing runtime instead of permanently latching it shut, so a late pi-advisor retry can start a fresh ACP process; explicit terminal disposal remains terminal. The compatibility probe passed on `agy 1.5.8`, `1.5.9` and `1.5.12`; the drift from 1.5.9 to 1.5.12 is additive only (the `gemini-4-neon` family, `gemini-pro-orchestrator-neon`, and `xhigh` as a `thought_level`). The `google-antigravity` SDK was then current at `0.1.23`. On 2026-11-14 (agy 1.5.9) the Antigravity backend began refusing pi's default system prompt sent through the append hook with `RESOURCE_EXHAUSTED`; live `gemini-4-hydrogen` turns and pi-subagents runs succeed through the `auto` inline fallback (see `PI_AGY_SYSTEM_PROMPT`). Earlier live bridge checks passed on `agy 1.5.8`. Live turns succeeded on `gemini-3.8-flash`, `gemini-4-hydrogen` (including `xhigh`), and `gemini-pro-orchestrator-g1-pro`. A real pi surface check with the configured extensions also passed. Claude, GPT-OSS and the `gemini-4-neon` family have not been exercised in a live model turn.
7
+ > Status: 0.3.2. Large conversation replay is now sequential and bounded, model-window overflow triggers pi compaction before any model call, and switching providers recomputes context from the full pi transcript. agy 1.5.17 and google-antigravity SDK 0.1.24 are tested. 0.3.1: active agy turns no longer hit pi's idle request timeout merely because their total duration exceeds it: every ACP update refreshes that deadline, while the independent silence guard still cancels inactive turns. 0.3.0: agy 1.5.16 and the `google-antigravity` SDK 0.1.24 are now tested; agy 1.5.17 is also recorded and tested with an identical ACP contract. agy 1.5.16 retired `gemini-pro-orchestrator-g1-pro`; its orchestrators are now `gemini-pro-orchestrator` (Carbon), `gemini-pro-orchestrator-argon` and `gemini-pro-orchestrator-neon`, and Gemini 4 Carbon (low, medium, high) is new. The SDK change (a removed `InputConfig.use_interactions_api` field) does not touch the bridge, which uses the SDK only as a drift canary. Stalls and timeouts are now easier to diagnose: an extra account keeps its previous agy log as `acp.prev.log`, and with `PI_AGY_TRACE=1` a stalled or timed-out turn records what agy last sent and when. agy 1.5.16 also forwards subagent and workflow questions to the editor; the bridge's carrier agent has no agy tools, subagents or skills, so agy never asks them here. 0.2.1: Extra-account sign-in works on agy 1.5.14: agy now prints a link and waits for the authorization code, so the bridge opens the link and asks for the code in a dialog. 0.2.0: Multiple Antigravity accounts: each extra account runs as its own provider `agy-<alias or id>` with its own login, managed from `/agy-bridge menu` or the `/agy-bridge` account commands; verified live on agy 1.5.14 with two Google accounts answering side by side. agy 1.5.14 is now tested: it refuses pi's appended system prompt silently (no notice for ~2 min), which `auto` now detects with a 30 s refusal probe and answers inline (see [Multiple Antigravity accounts](#multiple-antigravity-accounts)). 0.1.5: the default bridge home now honors Pi's configured agent directory (`PI_CODING_AGENT_DIR`). Every Pi session shutdown now recycles the outgoing runtime instead of permanently latching it shut, so a late pi-advisor retry can start a fresh ACP process; explicit terminal disposal remains terminal. The compatibility probe passed on `agy 1.5.8`, `1.5.9` and `1.5.12`; the drift from 1.5.9 to 1.5.12 is additive only (the `gemini-4-neon` family, `gemini-pro-orchestrator-neon`, and `xhigh` as a `thought_level`). The `google-antigravity` SDK was then current at `0.1.23`. On 2026-11-14 (agy 1.5.9) the Antigravity backend began refusing pi's default system prompt sent through the append hook with `RESOURCE_EXHAUSTED`; live `gemini-4-hydrogen` turns and pi-subagents runs succeed through the `auto` inline fallback (see `PI_AGY_SYSTEM_PROMPT`). Earlier live bridge checks passed on `agy 1.5.8`. Live turns succeeded on `gemini-3.8-flash`, `gemini-4-hydrogen` (including `xhigh`), and `gemini-pro-orchestrator-g1-pro`. A real pi surface check with the configured extensions also passed. Claude, GPT-OSS and the `gemini-4-neon` family have not been exercised in a live model turn.
8
8
 
9
9
  ## Requirements
10
10
 
@@ -97,7 +97,7 @@ Environment variables (all optional). Invalid values fall back to the default.
97
97
  | `PI_AGY_MAX_SESSIONS` | `2` | reusable sessions kept between turns |
98
98
  | `PI_AGY_IDLE_MIN` | `10` | stop the agy process after this long without activity and with no pooled session |
99
99
  | `PI_AGY_CANCEL_GRACE_MS` | `3000` | wait this long for a cancel before giving up on a turn |
100
- | `PI_AGY_MAX_REPLAY_KB` | `8192` | refuse to replay a conversation larger than this |
100
+ | `PI_AGY_MAX_REPLAY_KB` | `8192` | refuse total replay larger than this; oversized replay is delivered in sequential 128 KiB turns within one agy session |
101
101
  | `PI_AGY_CONTROL_TIMEOUT_SEC` | `60` | timeout for handshake and session calls |
102
102
  | `PI_AGY_SYSTEM_PROMPT` | `auto` | how pi's system prompt reaches agy: `append` (the `session/new` append hook), `inline` (top of the first prompt), or `auto` (append; if Antigravity refuses a fresh appended session with `RESOURCE_EXHAUSTED` before any output, retry that turn inline once and keep using inline). In `auto` the refusal is saved in `<home>/state.json` for 24 hours (or until agy's version changes), so other pi processes, including subagents, start inline without a refused attempt. agy 1.5.14 retries the refusal silently for about two minutes, so in `auto` a fresh appended session that shows no model output (text or thinking) within PI_AGY_REFUSAL_PROBE_SEC is treated as refused too |
103
103
  | `PI_AGY_REFUSAL_PROBE_SEC` | `30` | `auto` only: seconds a fresh session with the appended system prompt may stay silent before it is retried inline (measured first output on agy 1.5.14: 0.4-3.4 s); `0` disables the probe |
@@ -115,7 +115,7 @@ Only under `PI_AGY_HOME`: the staged carrier agent (`stage/`), agy's private con
115
115
 
116
116
  | Extension | Interaction |
117
117
  | --- | --- |
118
- | **pi-context** | Shake, boundary compaction and rollover rewrite history without `session_compact`. This package registers in pi-context's rewrite registry and drops the affected pooled session, so the next turn replays the rewritten history. `/fresh` (pi-ai `cleanupSessionResources`) does the same. Usage follows agy's measured semantics: `input` is uncached input, cache reads are separate, reasoning is part of output; zero cache reads are reported as zero. |
118
+ | **pi-context** | Boundary compaction and rollover notify this package through pi-context's rewrite registry and drop the affected pooled session. Shake currently does not emit that notification, but the hash-chain backstop detects the rewritten history and forces a fresh agy session anyway, so stale content is never reused. The next turn replays only the current context. `/fresh` (pi-ai `cleanupSessionResources`) does the same. Usage follows agy's measured semantics: `input` is uncached input, cache reads are separate, reasoning is part of output; zero cache reads are reported as zero. |
119
119
  | **pi-fallback-chains** | Errors use phrases its classifier already knows (`agy stalled for 120s with no output`, `agy spawn failed:`, `agy exited with status N`, `quota` with agy's reset hint, `not logged in`, `context_length_exceeded`). Chains are keyed by model, so mirror your existing `antigravity/*` chains for `agy/*` when you switch (example below). |
120
120
  | **pi-subagents, pi-advisor, pi-fusion, pi-btw** | All share one agy process; each pi session has its own agy session, so concurrent callers never see each other's text. A cancelled or crashed turn does not affect the others. |
121
121
  | **pi-model-picker, pi-statusline** | Models carry names, context windows, a thinking map and zero list price. `check` answers from the file system and a small hint, so it never delays pi's start-up. |
@@ -144,6 +144,7 @@ Example chain, mirrored from an `antigravity/*` chain:
144
144
  | `agy quota exceeded: Antigravity answered RESOURCE_EXHAUSTED ...` | the backend refused the request (429). agy would retry five times (~75 s); the bridge stops at the first notice. Since 2026-11-14 the backend refuses pi's default system prompt when it comes through the append hook (all models), while the same text inline is served; `auto` handles this | nothing in `auto` mode; otherwise use another model. The message says whether the prompt was appended or inline |
145
145
  | `agy stalled for 120s with no output` | the model produced nothing for the silence limit (with agy 1.5.14 and `PI_AGY_SYSTEM_PROMPT=append`: the backend's silent refusal of the appended prompt; use `auto`) | retry; raise `PI_AGY_SILENCE_SEC` for very long silent thinking. To see why, set `PI_AGY_TRACE=1` (the trace names agy's last update); for an extra account agy's own log of the failed run is `<home>/accounts/<id>/acp.prev.log` after the next start |
146
146
  | `agy request timed out after 300s` | agy sent no ACP update within pi's request timeout (`timeoutMs`; 300 s here), which defaults to pi's `httpIdleTimeoutMs`. Active turns refresh this deadline; with the default 120 s silence guard, that guard normally fires first | retry; pi's `/settings` HTTP timeout controls this idle limit (or set `retry.provider.timeoutMs`). The same `PI_AGY_TRACE=1` line shows what agy last sent |
147
+ | the model says `pi://conversation.md` was truncated before it could see the request | agy truncates oversized converted prompt content; this build delivers history, instructions and latest input as sequential bounded turns within one agy session instead | reload the extension and retry the current session (a fresh session alone would replay the same content). If pi's token estimate plus safety/output reserve exceeds the model window, the bridge returns `context_length_exceeded` before any model call so pi compacts automatically; total replay above `PI_AGY_MAX_REPLAY_KB` still needs a higher safe cap |
147
148
  | `agy exited with status N` | the agy process died | retry (a new process starts); `/agy-bridge doctor` shows agy's last stderr |
148
149
  | `agy is unavailable: pi-agy-bridge is shut down` during or just after reload/session replacement | 0.1.2 or older permanently latched the outgoing pool while a background caller (often pi-advisor) was retrying | upgrade to 0.1.3 or newer. An old advisor error can remain visible until a later review succeeds; that sticky status is normal |
149
150
  | `pi-agy-bridge is unavailable: agy ... below the minimum` | agy too old | `agy update` |
@@ -156,6 +157,7 @@ Example chain, mirrored from an `antigravity/*` chain:
156
157
  - A tool-call block the model writes inside a Markdown code fence is still treated as a call (a text protocol cannot tell an example from a request); your approval settings in pi remain the safeguard. Tool output is shown to the model inside a code fence it cannot close and marked as data, not instructions.
157
158
  - agy does not report context windows, so every model defaults to 1M tokens (set deliberately; a window agy reports through `usage_update.size` replaces it). If a model's real limit is lower, agy answers `context_length_exceeded`, pi compacts and retries, and that one request is the cost.
158
159
  - A session is kept across tool calls: after pi runs a tool, the next request continues the same agy session and sends only the tool result (a session waiting for a tool is kept for `PI_AGY_TOOL_TTL_MIN`, default 30 minutes). If the session was dropped meanwhile (TTL, `/fresh`, a pi-context rewrite, a changed system prompt or tool set), history is replayed into a new session (about one extra second).
160
+ - agy truncates oversized converted prompt content (the recorded failure retained roughly 192 KiB). Oversized fresh-session history, inline instructions and latest input are therefore split into complete blocks of at most 128 KiB of UTF-8, without splitting a Unicode codepoint, then delivered as sequential replay turns within one agy session before the actual request. Their usage is aggregated, and the completed session is reused by exact linear continuations. Independently, pi's token estimate plus a 15% safety margin and output reserve is checked against `model.contextWindow`: an overflow fails before any model call so pi compacts and retries instead of letting agy truncate a >1M-token session. Usage from the previous assistant is trusted only within the same provider/api; switching providers recomputes tokens from the full pi transcript instead of importing agy's compacted usage. The separate total replay cap remains `PI_AGY_MAX_REPLAY_KB`. Verified on real agy with a late-history fact and zero truncation markers.
159
161
  - agy's prompt cache applies only to a continuing session and only above roughly 16k prompt tokens, so short conversations show no cache reads; real coding sessions cross that quickly.
160
162
  - The first request of a pi session starts the agy process (about one second). A running `agy acp` uses roughly 170 MB (measured idle on Windows, plus a `conhost` child) and stops after `PI_AGY_IDLE_MIN` minutes without activity.
161
163
 
package/UPGRADING.md CHANGED
@@ -70,7 +70,9 @@ npm run check # tsc --noEmit
70
70
  `session/new` catalog captured from agy 1.5.8, the catalog recorded in the
71
71
  1.5.12 baseline and the live 1.5.16 catalog (renamed orchestrators, Gemini 4 Carbon), including per-model `xhigh`, models with no selectable reasoning
72
72
  level, and that the session-wide `thought_level` option never leaks a level to a
73
- model whose own variants do not list it. `probe.test.ts` pins parsers, diff
73
+ model whose own variants do not list it. agy 1.5.17's live probe is identical to
74
+ the 1.5.16 catalog/contract and is recorded in `compat/baselines/agy-1.5.17.json`.
75
+ `probe.test.ts` pins parsers, diff
74
76
  classification, baseline selection and CLI exit codes through injected
75
77
  fixtures; these tests never spawn agy.
76
78
 
@@ -101,7 +103,7 @@ uv run --project compat/sdk-canary python compat/sdk-canary/canary.py --latest
101
103
 
102
104
  First run creates `compat/sdk-canary/.venv` (the pinned `google-antigravity`
103
105
  version is in `pyproject.toml`; `uv.lock` is committed and `.venv` is gitignored).
104
- As of 2026-11-24, PyPI latest, the `v0.1.24` tag of
106
+ As of 2026-11-25, PyPI latest, the `v0.1.24` tag of
105
107
  `google-antigravity/antigravity-sdk-python` and the recorded SDK baseline are all
106
108
  `0.1.24`. 0.1.24 removed `InputConfig.use_interactions_api` (breaking for the
107
109
  canary, not for the bridge: the bridge never imports the SDK) and added
@@ -0,0 +1,284 @@
1
+ {
2
+ "schema": 1,
3
+ "agyVersion": "1.5.17",
4
+ "collectedAt": "2026-11-25T14:21:11.419Z",
5
+ "helpFlags": [
6
+ "--add-dir",
7
+ "--agent",
8
+ "--continue",
9
+ "--conversation",
10
+ "--dangerously-skip-permissions",
11
+ "--disable-slash-commands",
12
+ "--effort",
13
+ "--input-format",
14
+ "--json-schema",
15
+ "--log-file",
16
+ "--mode",
17
+ "--model",
18
+ "--new-project",
19
+ "--output-format",
20
+ "--print",
21
+ "--print-timeout",
22
+ "--project",
23
+ "--prompt",
24
+ "--prompt-interactive",
25
+ "--remote-agent",
26
+ "--remote-control",
27
+ "--resume",
28
+ "--sandbox",
29
+ "--settings",
30
+ "-c",
31
+ "-i",
32
+ "-p",
33
+ "-r"
34
+ ],
35
+ "acpHelpFlags": [
36
+ "--add-dir",
37
+ "--agent",
38
+ "--app-data-dir",
39
+ "--app_data_dir",
40
+ "--cli_dir_name",
41
+ "--cli_log_file",
42
+ "--cloud_code_endpoint",
43
+ "--dangerously-skip-permissions",
44
+ "--disable-telemetry",
45
+ "--disable_telemetry",
46
+ "--gemini-dir",
47
+ "--gemini_dir",
48
+ "--help",
49
+ "--ide-mcp-port",
50
+ "--ide_mcp_port",
51
+ "--include-default-customizations",
52
+ "--is_google3_workspace",
53
+ "--is_google_internal",
54
+ "--log-file",
55
+ "--login",
56
+ "--override_user_agent_name",
57
+ "--process-per-session",
58
+ "--sandbox",
59
+ "--stdio",
60
+ "--use_stubby_auth",
61
+ "--worker",
62
+ "-h"
63
+ ],
64
+ "models": [
65
+ {
66
+ "id": "claude-opus-5-5-high",
67
+ "label": "Claude Opus 5.5 (High)"
68
+ },
69
+ {
70
+ "id": "claude-opus-5-5-low",
71
+ "label": "Claude Opus 5.5 (Low)"
72
+ },
73
+ {
74
+ "id": "claude-opus-5-5-medium",
75
+ "label": "Claude Opus 5.5 (Medium)"
76
+ },
77
+ {
78
+ "id": "claude-sonnet-5-5-high",
79
+ "label": "Claude Sonnet 5.5 (High)"
80
+ },
81
+ {
82
+ "id": "claude-sonnet-5-5-low",
83
+ "label": "Claude Sonnet 5.5 (Low)"
84
+ },
85
+ {
86
+ "id": "claude-sonnet-5-5-medium",
87
+ "label": "Claude Sonnet 5.5 (Medium)"
88
+ },
89
+ {
90
+ "id": "gemini-3.8-flash-high",
91
+ "label": "Gemini 3.8 Flash (High)"
92
+ },
93
+ {
94
+ "id": "gemini-3.8-flash-low",
95
+ "label": "Gemini 3.8 Flash (Low)"
96
+ },
97
+ {
98
+ "id": "gemini-3.8-flash-medium",
99
+ "label": "Gemini 3.8 Flash (Medium)"
100
+ },
101
+ {
102
+ "id": "gemini-4-argon-high",
103
+ "label": "Gemini 4 Argon (High)"
104
+ },
105
+ {
106
+ "id": "gemini-4-argon-low",
107
+ "label": "Gemini 4 Argon (Low)"
108
+ },
109
+ {
110
+ "id": "gemini-4-argon-medium",
111
+ "label": "Gemini 4 Argon (Medium)"
112
+ },
113
+ {
114
+ "id": "gemini-4-carbon-high",
115
+ "label": "Gemini 4 Carbon (High)"
116
+ },
117
+ {
118
+ "id": "gemini-4-carbon-low",
119
+ "label": "Gemini 4 Carbon (Low)"
120
+ },
121
+ {
122
+ "id": "gemini-4-carbon-medium",
123
+ "label": "Gemini 4 Carbon (Medium)"
124
+ },
125
+ {
126
+ "id": "gemini-4-hydrogen-high",
127
+ "label": "Gemini 4 Hydrogen (High)"
128
+ },
129
+ {
130
+ "id": "gemini-4-hydrogen-low",
131
+ "label": "Gemini 4 Hydrogen (Low)"
132
+ },
133
+ {
134
+ "id": "gemini-4-hydrogen-medium",
135
+ "label": "Gemini 4 Hydrogen (Medium)"
136
+ },
137
+ {
138
+ "id": "gemini-4-hydrogen-xhigh",
139
+ "label": "Gemini 4 Hydrogen (XHigh)"
140
+ },
141
+ {
142
+ "id": "gemini-4-neon-high",
143
+ "label": "Gemini 4 Neon (High)"
144
+ },
145
+ {
146
+ "id": "gemini-4-neon-low",
147
+ "label": "Gemini 4 Neon (Low)"
148
+ },
149
+ {
150
+ "id": "gemini-4-neon-medium",
151
+ "label": "Gemini 4 Neon (Medium)"
152
+ },
153
+ {
154
+ "id": "gemini-4-neon-xhigh",
155
+ "label": "Gemini 4 Neon (XHigh)"
156
+ },
157
+ {
158
+ "id": "gemini-pro-orchestrator",
159
+ "label": "Orchestrator (Carbon)"
160
+ },
161
+ {
162
+ "id": "gemini-pro-orchestrator-argon",
163
+ "label": "Orchestrator (Argon)"
164
+ },
165
+ {
166
+ "id": "gemini-pro-orchestrator-neon",
167
+ "label": "Orchestrator (Neon)"
168
+ },
169
+ {
170
+ "id": "gpt-oss-120b-medium",
171
+ "label": "GPT-OSS 120B (Medium)"
172
+ }
173
+ ],
174
+ "initialize": {
175
+ "protocolVersion": 1,
176
+ "agentName": "Antigravity ACP Server",
177
+ "agentVersion": "1.5.17",
178
+ "capabilities": {
179
+ "_meta.antigravity.systemPrompt.append": true,
180
+ "auth.logout": true,
181
+ "loadSession": true,
182
+ "load_session": true,
183
+ "promptCapabilities.audio": false,
184
+ "promptCapabilities.embeddedContext": true,
185
+ "promptCapabilities.image": true,
186
+ "sessionCapabilities.additionalDirectories": true,
187
+ "sessionCapabilities.close": true,
188
+ "sessionCapabilities.list": true,
189
+ "sessionCapabilities.load": true,
190
+ "sessionCapabilities.resume": true,
191
+ "session_capabilities.additionalDirectories": true,
192
+ "session_capabilities.close": true,
193
+ "session_capabilities.list": true,
194
+ "session_capabilities.load": true,
195
+ "session_capabilities.resume": true
196
+ },
197
+ "authMethodIds": [
198
+ "agent-platform",
199
+ "gemini-api-key",
200
+ "oauth-business",
201
+ "oauth-personal"
202
+ ]
203
+ },
204
+ "session": {
205
+ "configOptions": [
206
+ {
207
+ "id": "mode",
208
+ "type": "select",
209
+ "values": [
210
+ "accept-edits",
211
+ "auto",
212
+ "default",
213
+ "plan"
214
+ ]
215
+ },
216
+ {
217
+ "id": "model",
218
+ "type": "select",
219
+ "values": [
220
+ "claude-opus-5-5",
221
+ "claude-sonnet-5-5",
222
+ "gemini-3.8-flash",
223
+ "gemini-4-argon",
224
+ "gemini-4-carbon",
225
+ "gemini-4-hydrogen",
226
+ "gemini-4-neon",
227
+ "gemini-pro-orchestrator",
228
+ "gemini-pro-orchestrator-argon",
229
+ "gemini-pro-orchestrator-neon",
230
+ "gpt-oss-120b-medium"
231
+ ]
232
+ },
233
+ {
234
+ "id": "thought_level",
235
+ "type": "select",
236
+ "values": [
237
+ "high",
238
+ "low",
239
+ "medium",
240
+ "xhigh"
241
+ ]
242
+ }
243
+ ],
244
+ "modeIds": [
245
+ "accept-edits",
246
+ "auto",
247
+ "default",
248
+ "plan"
249
+ ],
250
+ "modelIds": [
251
+ "claude-opus-5-5-high",
252
+ "claude-opus-5-5-low",
253
+ "claude-opus-5-5-medium",
254
+ "claude-sonnet-5-5-high",
255
+ "claude-sonnet-5-5-low",
256
+ "claude-sonnet-5-5-medium",
257
+ "gemini-3.8-flash-high",
258
+ "gemini-3.8-flash-low",
259
+ "gemini-3.8-flash-medium",
260
+ "gemini-4-argon-high",
261
+ "gemini-4-argon-low",
262
+ "gemini-4-argon-medium",
263
+ "gemini-4-carbon-high",
264
+ "gemini-4-carbon-low",
265
+ "gemini-4-carbon-medium",
266
+ "gemini-4-hydrogen-high",
267
+ "gemini-4-hydrogen-low",
268
+ "gemini-4-hydrogen-medium",
269
+ "gemini-4-hydrogen-xhigh",
270
+ "gemini-4-neon-high",
271
+ "gemini-4-neon-low",
272
+ "gemini-4-neon-medium",
273
+ "gemini-4-neon-xhigh",
274
+ "gemini-pro-orchestrator",
275
+ "gemini-pro-orchestrator-argon",
276
+ "gemini-pro-orchestrator-neon",
277
+ "gpt-oss-120b-medium"
278
+ ],
279
+ "metaKeys": [
280
+ "antigravity"
281
+ ]
282
+ },
283
+ "fileTokenStorageTrigger": "SSH_CONNECTION"
284
+ }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "schema": 1,
3
3
  "agy": {
4
- "tested": ["1.5.3", "1.5.8", "1.5.9", "1.5.12", "1.5.14", "1.5.16"],
4
+ "tested": ["1.5.3", "1.5.8", "1.5.9", "1.5.12", "1.5.14", "1.5.16", "1.5.17"],
5
5
  "minimum": "1.5.1",
6
6
  "knownBad": []
7
7
  },
package/compat/probe.ts CHANGED
@@ -40,7 +40,7 @@ export const PROBE_PROTOCOL_VERSION = 1;
40
40
  export const PROBE_CLIENT_INFO = {
41
41
  name: "pi-agy-bridge-compat-probe",
42
42
  title: "pi-agy-bridge zero-cost compat probe",
43
- version: "0.3.1",
43
+ version: "0.3.2",
44
44
  } as const;
45
45
 
46
46
  /** One failed probe step. `step` names the command or exchange. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@timmyjl12/pi-agy-bridge",
3
- "version": "0.3.1",
3
+ "version": "0.3.2",
4
4
  "description": "pi provider for Google Antigravity (agy) models over the official ACP server, modelled on pi-claude-code: pi keeps the loop, history and tool execution",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -194,7 +194,7 @@ export class AcpProcess {
194
194
  const result = await this.#rpc.request("initialize", {
195
195
  protocolVersion: 1,
196
196
  clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false },
197
- clientInfo: { name: "pi-agy-bridge", title: "pi-agy-bridge", version: "0.3.1" },
197
+ clientInfo: { name: "pi-agy-bridge", title: "pi-agy-bridge", version: "0.3.2" },
198
198
  });
199
199
  return (result ?? {}) as AcpInitializeResult;
200
200
  }
package/src/config.ts CHANGED
@@ -50,7 +50,7 @@ export const DEFAULT_CONFIG: Readonly<AgyConfig> = Object.freeze({
50
50
  maxSessions: 2,
51
51
  silenceMs: 120_000,
52
52
  cancelGraceMs: 3_000,
53
- // Gemini windows reach ~4 MB of text. agy's own frame limit is unmeasured: verify with a large live turn.
53
+ // Total replay budget; oversized replay is split into bounded sequential turns in stream.ts.
54
54
  replayMaxBytes: 8 * 1024 * 1024,
55
55
  controlTimeoutMs: 60_000,
56
56
  systemPrompt: "auto",
@@ -1,10 +1,11 @@
1
1
  // Coordination with pi-context.
2
2
  //
3
- // pi-context rewrites history (shake, boundary compaction, rollover) without emitting `session_compact`, so a
4
- // provider that keeps its own mirror of the conversation would resume a stale one. pi-context therefore calls
5
- // every function stored in a process-wide Set at globalThis[Symbol.for("claude-bridge:markRebuildHooks")] with
6
- // (piSessionId, event). The Set is created by whoever registers first; pi-context only reads it and ignores a
7
- // missing or empty Set. See pi-context/src/runtime/bridge-rebuild.ts and evidence/pi-context-coordination.md.
3
+ // pi-context boundary compaction and rollover rewrite history without emitting `session_compact`, so a provider
4
+ // that keeps its own mirror must discard it and rebuild from pi's rewritten messages. Shake currently emits no
5
+ // notification; the hash-prefix check in SessionPool is the backstop there. pi-context calls every function stored
6
+ // in a process-wide Set at globalThis[Symbol.for("claude-bridge:markRebuildHooks")] with (piSessionId, event).
7
+ // The Set is created by whoever registers first; pi-context only reads it and ignores a missing or empty Set.
8
+ // See pi-context/src/runtime/bridge-rebuild.ts and evidence/pi-context-coordination.md.
8
9
 
9
10
  const REGISTRY_KEY = Symbol.for("claude-bridge:markRebuildHooks");
10
11
 
@@ -153,9 +153,9 @@ export class SessionPool {
153
153
 
154
154
  /** Register the invalidation hooks that keep pooled sessions honest. Returns an unregister function.
155
155
  * - pi-ai `registerSessionResourceCleanup`: `/fresh`, session end (id undefined = every session).
156
- * - pi-context's process-wide rewrite registry: shake, boundary compaction and rollover rewrite history
157
- * without `session_compact`, so a pooled mirror would be stale (see evidence/pi-context-coordination.md).
158
- * The prefix-hash check remains the correctness backstop when neither fires. */
156
+ * - pi-context's process-wide rewrite registry: boundary compaction and rollover rewrite history without
157
+ * `session_compact`. Shake currently emits no notification; the prefix-hash check remains the correctness
158
+ * backstop there and whenever cleanup/rewrite notification is missed. */
159
159
  attachHooks(): () => void {
160
160
  const offCleanup = registerSessionResourceCleanup((sessionId) => this.invalidate(sessionId ?? null));
161
161
  const offRewrite = registerHistoryRewriteHook((piSessionId) => this.invalidate(piSessionId));
@@ -582,6 +582,8 @@ export class SessionPool {
582
582
  invalidate(piSessionId: string | null | undefined): void {
583
583
  this.#invalidationSeq += 1;
584
584
  if (piSessionId) {
585
+ // Map.set() alone preserves the original insertion position. Delete first so repeat invalidation is most-recent.
586
+ this.#invalidatedAt.delete(piSessionId);
585
587
  this.#invalidatedAt.set(piSessionId, this.#invalidationSeq);
586
588
  if (this.#invalidatedAt.size > 256) this.#invalidatedAt.delete(this.#invalidatedAt.keys().next().value as string); // bounded: only in-flight acquisitions read it
587
589
  } else {
package/src/stream.ts CHANGED
@@ -17,6 +17,7 @@ import {
17
17
  type ToolCall,
18
18
  type TranscriptContext,
19
19
  } from "@earendil-works/pi-ai";
20
+ import { estimateContextTokens, estimateMessageTokens } from "@earendil-works/pi-ai/utils/estimate";
20
21
  import { PERMISSION_DENIED_UPDATE } from "./acp/connection.ts";
21
22
  import type { AcpContentBlock, AcpPromptResult, AcpUpdate, AcpUsage } from "./acp/types.ts";
22
23
  import {
@@ -38,6 +39,53 @@ import { renderToolProtocol, safeJson, ToolCallStreamParser, type ParsedToolCall
38
39
  import { hashChain, serializeHistory, serializeLatest, splitContext } from "./transcript.ts";
39
40
 
40
41
  const HISTORY_URI = "pi://conversation.md";
42
+ /** agy truncates converted prompt content at roughly 192 KiB. Keep a conservative margin for its wrappers. */
43
+ const PROMPT_CHUNK_BYTES = 128 * 1024;
44
+ const CONTEXT_SAFETY_RATIO = 0.15;
45
+ const MIN_OUTPUT_RESERVE = 32_768;
46
+
47
+ /** Give pi a context-overflow signal before agy can silently truncate or bill a request that cannot fit. Uses the
48
+ * same token estimate and safety-margin shape as pi's own request option handling, scaled to each model's window. */
49
+ function assertContextWindow(model: Model<any>, context: TranscriptContext, options: SimpleStreamOptions | undefined): void {
50
+ if (model.contextWindow <= 0) return;
51
+ const estimate = estimateContextTokens(context);
52
+ const usageMessage = estimate.lastUsageIndex === null ? undefined : context.messages[estimate.lastUsageIndex];
53
+ // A previous provider's usage can describe a compacted session mirror, not pi's full transcript. On handoff,
54
+ // recompute every message instead of importing that provider-specific view of context size.
55
+ const tokens =
56
+ usageMessage?.role === "assistant" && (usageMessage.provider !== model.provider || usageMessage.api !== model.api)
57
+ ? context.messages.reduce((sum, message) => sum + estimateMessageTokens(message), 0)
58
+ : estimate.tokens;
59
+ const safety = Math.max(4096, Math.ceil(tokens * CONTEXT_SAFETY_RATIO));
60
+ const outputReserve = Math.min(options?.maxTokens ?? model.maxTokens, MIN_OUTPUT_RESERVE);
61
+ if (tokens + safety + outputReserve <= model.contextWindow) return;
62
+ throw new AgyError(
63
+ "context",
64
+ `context_length_exceeded: pi estimates ${tokens} input tokens; with ${safety} safety and ${outputReserve} output reserve this exceeds the ${model.contextWindow}-token window of ${model.id}. pi will compact and retry`,
65
+ );
66
+ }
67
+
68
+ /** Split without losing a codepoint or exceeding agy's per-block byte budget. */
69
+ function chunkUtf8(text: string): string[] {
70
+ const chunks: string[] = [];
71
+ let start = 0;
72
+ let bytes = 0;
73
+ let offset = 0;
74
+ while (offset < text.length) {
75
+ const codepoint = text.codePointAt(offset)!;
76
+ const width = codepoint > 0xffff ? 2 : 1;
77
+ const size = codepoint <= 0x7f ? 1 : codepoint <= 0x7ff ? 2 : codepoint <= 0xffff ? 3 : 4;
78
+ if (bytes + size > PROMPT_CHUNK_BYTES && offset > start) {
79
+ chunks.push(text.slice(start, offset));
80
+ start = offset;
81
+ bytes = 0;
82
+ }
83
+ bytes += size;
84
+ offset += width;
85
+ }
86
+ if (start < text.length) chunks.push(text.slice(start));
87
+ return chunks;
88
+ }
41
89
 
42
90
  function emptyUsage(): AssistantMessage["usage"] {
43
91
  return {
@@ -217,6 +265,101 @@ function stopFromResult(reason: string | undefined, hasToolCall: boolean): { sto
217
265
  }
218
266
  }
219
267
 
268
+ function needsSequentialReplay(prompt: AcpContentBlock[]): boolean {
269
+ const content = prompt.filter((block) => block.type !== "image");
270
+ const bytes = content.reduce((sum, block) => sum + Buffer.byteLength(block.type === "text" ? block.text : block.resource.text), 0);
271
+ return content.length > 1 && bytes > PROMPT_CHUNK_BYTES;
272
+ }
273
+
274
+ function replayPlan(prompt: AcpContentBlock[]): { replay: AcpContentBlock[]; final: AcpContentBlock[] } {
275
+ const content = prompt.filter((block) => block.type !== "image");
276
+ const images = prompt.filter((block) => block.type === "image");
277
+ const last = content.at(-1);
278
+ if (!last) return { replay: [], final: prompt };
279
+ return { replay: content.slice(0, -1), final: [last, ...images] };
280
+ }
281
+
282
+ function mergeUsage(parts: Array<AcpUsage | undefined>): AcpUsage | undefined {
283
+ const total: AcpUsage = {};
284
+ let any = false;
285
+ for (const usage of parts) {
286
+ if (!usage) continue;
287
+ for (const field of ["inputTokens", "outputTokens", "cachedReadTokens", "cachedWriteTokens", "thoughtTokens", "totalTokens"] as const) {
288
+ const value = usage[field];
289
+ if (typeof value !== "number") continue;
290
+ total[field] = (total[field] ?? 0) + value;
291
+ any = true;
292
+ }
293
+ }
294
+ return any ? total : undefined;
295
+ }
296
+
297
+ /** Deliver one oversized replay part as its own bounded turn. The acknowledgement is deliberately not exposed to pi;
298
+ * the next part continues in the same agy session, and the actual user request is sent only after every part arrives. */
299
+ async function runReplayPart(
300
+ runtime: AgyRuntime,
301
+ model: Model<any>,
302
+ options: SimpleStreamOptions | undefined,
303
+ lease: Lease,
304
+ block: AcpContentBlock,
305
+ index: number,
306
+ total: number,
307
+ ): Promise<AcpUsage | undefined> {
308
+ const replayStream = createAssistantMessageEventStream();
309
+ const output: AssistantMessage = {
310
+ role: "assistant",
311
+ content: [],
312
+ api: model.api,
313
+ provider: model.provider,
314
+ model: model.id,
315
+ usage: emptyUsage(),
316
+ stopReason: "pending",
317
+ timestamp: Date.now(),
318
+ };
319
+ const translator = new Translator(replayStream, output);
320
+ const guidance = [
321
+ `You are receiving earlier conversation context in ${total} bounded replay parts; this is part ${index}.`,
322
+ "Treat the attached content as historical context only. Do not answer historical requests or call tools.",
323
+ "Reply with exactly ACK and nothing else. The current request will follow after the final part.",
324
+ ].join("\n");
325
+ const turn = await runTurn(runtime, model, options, lease, [{ type: "text", text: guidance }, block], translator);
326
+ translator.finish();
327
+ replayStream.end();
328
+ if (turn.cancelReason === "abort") throw new AgyError("other", "aborted");
329
+ if (turn.cancelReason === "stall") {
330
+ if (turn.wedged) await runtime.pool.killProcess(lease.process, "replay stalled and ignored cancel");
331
+ throw stalledError(runtime.config.silenceMs);
332
+ }
333
+ if (turn.cancelReason === "timeout") {
334
+ if (turn.wedged) await runtime.pool.killProcess(lease.process, "replay timed out and ignored cancel");
335
+ throw new AgyError("stalled", `agy request timed out after ${Math.round((options?.timeoutMs ?? 0) / 1000)}s`);
336
+ }
337
+ if (turn.cancelReason || !turn.result || turn.result.stopReason !== "end_turn") {
338
+ if (turn.wedged) await runtime.pool.killProcess(lease.process, "replay was not acknowledged and ignored cancel");
339
+ throw new AgyError(
340
+ "other",
341
+ `agy did not acknowledge conversation replay part ${index}/${total} (${turn.cancelReason ?? turn.result?.stopReason ?? "no result"})`,
342
+ );
343
+ }
344
+ return turn.result.usage;
345
+ }
346
+
347
+ async function runReplayIfNeeded(
348
+ runtime: AgyRuntime,
349
+ model: Model<any>,
350
+ options: SimpleStreamOptions | undefined,
351
+ lease: Lease,
352
+ prompt: AcpContentBlock[],
353
+ ): Promise<{ prompt: AcpContentBlock[]; usages: Array<AcpUsage | undefined> }> {
354
+ if (!needsSequentialReplay(prompt)) return { prompt, usages: [] };
355
+ const plan = replayPlan(prompt);
356
+ const usages: Array<AcpUsage | undefined> = [];
357
+ for (const [index, block] of plan.replay.entries()) {
358
+ usages.push(await runReplayPart(runtime, model, options, lease, block, index + 1, plan.replay.length));
359
+ }
360
+ return { prompt: plan.final, usages };
361
+ }
362
+
220
363
  export function makeStreamAgy(runtime: AgyRuntime) {
221
364
  return function streamAgy(model: Model<any>, sourceContext: TranscriptContext, options?: SimpleStreamOptions): AssistantMessageEventStream {
222
365
  const stream = createAssistantMessageEventStream();
@@ -256,6 +399,7 @@ async function run(
256
399
  try {
257
400
  stream.push({ type: "start", partial: output });
258
401
  options?.signal?.throwIfAborted();
402
+ assertContextWindow(model, context, options);
259
403
 
260
404
  const split = splitContext(context.messages);
261
405
  const thought = thoughtLevelFor(model, options?.reasoning);
@@ -280,6 +424,15 @@ async function run(
280
424
  options?.signal?.throwIfAborted();
281
425
 
282
426
  let prompt = buildPrompt(runtime, split, lease.reused, lease.systemInline ? systemText : undefined);
427
+ // A large sequential replay needs the instructions inside the replay, not behind agy's append-refusal path. Open
428
+ // the fresh session inline up front instead of spending a model turn just to discover that delivery will fail.
429
+ if (needsSequentialReplay(prompt) && !lease.reused && runtime.config.systemPrompt === "auto" && !lease.systemInline) {
430
+ await lease.finish({ reusable: false });
431
+ lease = undefined;
432
+ lease = await acquireOrAbort(runtime.pool, options?.signal, { ...request, systemInline: true });
433
+ options?.signal?.throwIfAborted();
434
+ prompt = buildPrompt(runtime, split, lease.reused, lease.systemInline ? systemText : undefined);
435
+ }
283
436
  const deadline = options?.timeoutMs && options.timeoutMs > 0 ? Date.now() + options.timeoutMs : undefined;
284
437
  // Stop at the first RESOURCE_EXHAUSTED only when the inline retry below can follow. Anywhere else agy's own retries
285
438
  // (~75 s) are the best chance of getting through a short throttle, e.g. in the middle of a subagent's tool loop.
@@ -288,6 +441,11 @@ async function run(
288
441
  // longer arrives in time. A fresh appended session that produced no model output (text or thinking) within the probe
289
442
  // window is treated as refused too. Measured first output on 1.5.14: 0.4-3.4 s across Claude, Gemini 4 xhigh and the
290
443
  // orchestrator; a false positive only costs one inline session, which is always served.
444
+ let promptChars = prompt.reduce((n, b) => n + (b.type === "text" ? b.text.length : b.type === "resource" ? b.resource.text.length : 0), 0);
445
+ const replayUsages: Array<AcpUsage | undefined> = [];
446
+ const initialReplay = await runReplayIfNeeded(runtime, model, options, lease, prompt);
447
+ prompt = initialReplay.prompt;
448
+ replayUsages.push(...initialReplay.usages);
291
449
  let turn = await runTurn(runtime, model, options, lease, prompt, translator, undefined, inlineFallback, runtime.config.refusalProbeMs);
292
450
 
293
451
  // The Antigravity backend refuses some system prompts sent through the append hook with RESOURCE_EXHAUSTED on
@@ -313,6 +471,10 @@ async function run(
313
471
  lease = await acquireOrAbort(runtime.pool, options?.signal, { ...request, systemInline: true });
314
472
  options?.signal?.throwIfAborted();
315
473
  prompt = buildPrompt(runtime, split, lease.reused, lease.systemInline ? systemText : undefined);
474
+ promptChars = prompt.reduce((n, b) => n + (b.type === "text" ? b.text.length : b.type === "resource" ? b.resource.text.length : 0), 0);
475
+ const fallbackReplay = await runReplayIfNeeded(runtime, model, options, lease, prompt);
476
+ prompt = fallbackReplay.prompt;
477
+ replayUsages.push(...fallbackReplay.usages);
316
478
  turn = await runTurn(runtime, model, options, lease, prompt, translator, remaining);
317
479
  if (turn.cancelReason !== "exhausted" && turn.result !== undefined && translator.producedOutput) {
318
480
  runtime.recordAppendRefusal();
@@ -321,10 +483,10 @@ async function run(
321
483
  }
322
484
  translator.finish();
323
485
 
324
- if (turn.result) mapUsage(model, turn.result.usage, output.usage);
486
+ if (turn.result) mapUsage(model, mergeUsage([...replayUsages, turn.result.usage]), output.usage);
325
487
  output.rawStopReason = turn.result?.stopReason;
326
488
  runtime.trace(
327
- `turn: model=${model.id} reused=${lease.reused} agy=${turn.result?.stopReason ?? "none"} in=${output.usage.input} cacheRead=${output.usage.cacheRead} out=${output.usage.output} promptChars=${prompt.reduce((n, b) => n + (b.type === "text" ? b.text.length : b.type === "resource" ? b.resource.text.length : 0), 0)}`,
489
+ `turn: model=${model.id} reused=${lease.reused} agy=${turn.result?.stopReason ?? "none"} in=${output.usage.input} cacheRead=${output.usage.cacheRead} out=${output.usage.output} replayParts=${replayUsages.length} promptChars=${promptChars}`,
328
490
  );
329
491
 
330
492
  if (turn.cancelReason === "abort") throw new AgyError("other", "aborted");
@@ -455,10 +617,15 @@ function buildPrompt(
455
617
  );
456
618
  }
457
619
  if (history && features.embeddedContext) {
458
- blocks.push({ type: "resource", resource: { uri: HISTORY_URI, mimeType: "text/markdown", text: history } });
620
+ const chunks = chunkUtf8(history);
621
+ for (const [index, text] of chunks.entries()) {
622
+ const uri = index === 0 ? HISTORY_URI : `${HISTORY_URI}?part=${index + 1}`;
623
+ blocks.push({ type: "resource", resource: { uri, mimeType: "text/markdown", text } });
624
+ }
459
625
  history = "";
460
626
  }
461
- blocks.push({ type: "text", text: history ? `${history}\n\n${latestText}` : latestText });
627
+ const text = history ? `${history}\n\n${latestText}` : latestText;
628
+ for (const chunk of chunkUtf8(text)) blocks.push({ type: "text", text: chunk });
462
629
  if (features.images) {
463
630
  for (const image of latest.images) blocks.push({ type: "image", data: image.data, mimeType: image.mimeType });
464
631
  }