@timmyjl12/pi-agy-bridge 0.3.1 → 0.3.3
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 +17 -5
- package/README.md +8 -5
- package/UPGRADING.md +4 -2
- package/compat/baselines/agy-1.5.17.json +284 -0
- package/compat/matrix.json +1 -1
- package/compat/probe.ts +1 -1
- package/package.json +1 -1
- package/src/accounts.ts +13 -2
- package/src/acp/connection.ts +1 -1
- package/src/config.ts +1 -1
- package/src/errors.ts +2 -2
- package/src/pi-context-hook.ts +6 -5
- package/src/runtime.ts +4 -1
- package/src/session-pool.ts +5 -3
- package/src/stream.ts +227 -13
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,
|
|
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/
|
|
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,11 @@ 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
|
+
Internal replay acknowledgements and the single whitespace-recovery prompt are transport details, not pi transcript messages. They stay inside the same agy session; the next exact continuation sends only pi's new suffix, while a fresh replay uses pi's transcript as the source of truth. Parser-buffered text and truncated tool calls are flushed before empty-answer recovery is considered, so recovery cannot discard emitted work. These rules preserve the context delivered to the model; they do not guarantee correct model reasoning over that context.
|
|
71
|
+
|
|
72
|
+
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. Replay ACK turns do not interpret pi's tool protocol: a protocol-looking block is unexecuted text and cannot cancel context delivery, while the actual user request keeps normal tool parsing. 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
73
|
|
|
64
74
|
## Process model
|
|
65
75
|
|
|
@@ -69,7 +79,7 @@ One shared `agy acp` per extension runtime, started on first real use, serving e
|
|
|
69
79
|
|
|
70
80
|
`AccountManager` (`account-manager.ts`) owns one `AgyRuntime` per Antigravity account. The default runtime is the one described above (provider `agy`, api `agy-acp`, agy's keyring login) and is registered synchronously at load, exactly as before. Each enabled entry of `<home>/accounts.json` (plus `PI_AGY_ACCOUNTS`) gets its own runtime, pool and `agy acp` process, and its own pi provider `agy-<alias ?? id>` with its own api id `agy-acp-<alias ?? id>` (pi-ai's compat stream registry is keyed by api id, so ids must not be shared). Providers are (un)registered live through `pi.registerProvider` / `pi.unregisterProvider` when an account is added, renamed, enabled, disabled or removed.
|
|
71
81
|
|
|
72
|
-
An extra account's process differs from the default in three ways: `--gemini-dir <home>/accounts/<id>/gemini` (and its own work dir), `--log-file <home>/accounts/<id>/acp
|
|
82
|
+
An extra account's process differs from the default in three ways: `--gemini-dir <home>/accounts/<id>/gemini` (and its own work dir), `--log-file <home>/accounts/<id>/acp-<pid>.log` (moved to `acp-<pid>.prev.log` when that pi process restarts agy, so a failed run can still be read and concurrent pi processes never rotate each other's logs), and `SSH_CONNECTION` in its environment. agy keeps one login per OS user in the keyring; when it sees an SSH session it uses a token file inside the gemini dir instead (measured on 1.5.12 and 1.5.14, `.plan/agy-multi-account/evidence`). `agy acp --login` with the same three settings signs that folder in (`accounts.ts` `startLogin`).
|
|
73
83
|
|
|
74
84
|
The identity guard (`PoolOptions.verifyProcess`, `AgyRuntime` `#checkIdentity`) runs once per process right after its first `session/new`, because agy resolves the login lazily during that call. It reads agy's own log: the process is used only if agy reports file-based token storage and `authenticated successfully as <expected email>`. Otherwise the session is closed, the process stopped, and the request fails with `agy authentication required (not logged in) … account <id>` (non-retryable for pi-fallback-chains) or, when the storage trigger is missing, `pi-agy-bridge is unavailable: …` - so an extra provider never silently spends the default account's quota. Each account has its own `state.json` hint and trace tag; error messages of an extra account end with `(account <id>)`.
|
|
75
85
|
|
|
@@ -103,11 +113,13 @@ Measured on agy 1.5.3 (`evidence/cache-and-usage-semantics.md`, pinned by `tests
|
|
|
103
113
|
| no output for the silence limit | `agy stalled for Ns with no output` | retryable |
|
|
104
114
|
| pi's idle `timeoutMs` elapsed without an ACP update | `agy request timed out after Ns` | retryable |
|
|
105
115
|
| empty answer | `agy returned success but produced no model output:` | retryable |
|
|
106
|
-
| quota (agy sends it as a normal `end_turn` reply with
|
|
116
|
+
| quota (agy sends it as a normal `end_turn` reply, with absent/zero usage or after billable thinking; detected and failed) | `agy quota exhausted:` + agy's text (keeps `Resets in ...`) | retryable, provider cap |
|
|
107
117
|
| not logged in | `agy authentication required (not logged in)` | non-retryable |
|
|
108
118
|
| context too large | `context_length_exceeded:` | non-retryable |
|
|
109
119
|
| agy too old / wrong protocol | `pi-agy-bridge is unavailable:` | retryable |
|
|
110
120
|
|
|
121
|
+
A successful `end_turn` that spent output tokens or emitted reasoning but produced no visible answer gets one same-session retry for a normal answer or protocol tool call; usage from both attempts is aggregated. A second whitespace-only answer, or a truly empty zero-output reply, keeps the error above.
|
|
122
|
+
|
|
111
123
|
Own messages avoid bare three-digit numbers because the classifier reads them as HTTP statuses.
|
|
112
124
|
|
|
113
125
|
## Upgrade path
|
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.
|
|
7
|
+
> Status: 0.3.3. Leading quota warnings now trigger fallback even after billable thinking, concurrent pi processes use isolated per-account ACP logs, internal replay ACKs can no longer abort the real request as tool calls, and reasoning-only or whitespace-only answers get one bounded same-session recovery retry without losing buffered text or truncated tool calls. 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
|
|
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** |
|
|
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. |
|
|
@@ -140,10 +140,12 @@ Example chain, mirrored from an `antigravity/*` chain:
|
|
|
140
140
|
| `agy authentication required (not logged in)` | login expired | run `agy` and sign in |
|
|
141
141
|
| `agy authentication required (not logged in) for account <id>` | that extra account has no saved login, or agy is signed in as a different Google account than the one recorded | `/agy-bridge login <id>` (the new email becomes the expected one) |
|
|
142
142
|
| `pi-agy-bridge is unavailable: agy did not switch to per-account token storage for account <id>` | an agy update stopped honouring the trigger extra accounts use; they fail closed rather than use your default login | see `UPGRADING.md` §1 (the compat probe reports this as breaking) |
|
|
143
|
-
| `agy quota exhausted: ... Resets in ...` | the plan's quota for that model is used up (agy delivers this as a normal reply
|
|
143
|
+
| `agy quota exhausted: ... Resets in ...` | the plan's quota for that model is used up (agy delivers this as a normal reply, sometimes after billable thinking; the bridge turns a leading warning into an error whether usage is absent, zero or nonzero so fallback chains rotate immediately) | use another model/account; the reset time is in the message |
|
|
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
|
-
| `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
|
|
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-<pid>.prev.log` after that pi process's next start (per-process logs avoid concurrent-start rotation locks) |
|
|
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 |
|
|
148
|
+
| `agy returned success but produced no model output: stop reason end_turn` | agy ended without visible answer text or a tool call | retry; when agy emitted reasoning or spent output tokens, this build automatically asks once in the same session for the missing visible answer before reporting this error |
|
|
147
149
|
| `agy exited with status N` | the agy process died | retry (a new process starts); `/agy-bridge doctor` shows agy's last stderr |
|
|
148
150
|
| `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
151
|
| `pi-agy-bridge is unavailable: agy ... below the minimum` | agy too old | `agy update` |
|
|
@@ -156,6 +158,7 @@ Example chain, mirrored from an `antigravity/*` chain:
|
|
|
156
158
|
- 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
159
|
- 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
160
|
- 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).
|
|
161
|
+
- 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
162
|
- 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
163
|
- 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
164
|
|
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.
|
|
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-
|
|
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
|
+
}
|
package/compat/matrix.json
CHANGED
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.
|
|
43
|
+
version: "0.3.3",
|
|
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.
|
|
3
|
+
"version": "0.3.3",
|
|
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",
|
package/src/accounts.ts
CHANGED
|
@@ -95,8 +95,19 @@ export function accountPaths(home: string, id: string): AccountPaths {
|
|
|
95
95
|
};
|
|
96
96
|
}
|
|
97
97
|
|
|
98
|
-
/**
|
|
99
|
-
*
|
|
98
|
+
/** ACP logs are private to one pi process. Several pi agents can use the same account concurrently without rotating
|
|
99
|
+
* or deleting the log another process still has open. `owner` is a test seam; production uses pi's process id. */
|
|
100
|
+
export function accountProcessPaths(home: string, id: string, owner = process.pid): AccountPaths {
|
|
101
|
+
const paths = accountPaths(home, id);
|
|
102
|
+
return {
|
|
103
|
+
...paths,
|
|
104
|
+
logFile: path.join(paths.root, `acp-${owner}.log`),
|
|
105
|
+
prevLogFile: path.join(paths.root, `acp-${owner}.prev.log`),
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Before an extra-account process starts: move its last log to the matching previous-log path (replacing the older
|
|
110
|
+
* one) so the new process starts with an empty log for the identity guard, while the previous run stays readable. */
|
|
100
111
|
export async function rotateAccountLog(
|
|
101
112
|
paths: Pick<AccountPaths, "logFile" | "prevLogFile">,
|
|
102
113
|
io: { rename: typeof rename; rm: typeof rm } = { rename, rm },
|
package/src/acp/connection.ts
CHANGED
|
@@ -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.
|
|
197
|
+
clientInfo: { name: "pi-agy-bridge", title: "pi-agy-bridge", version: "0.3.3" },
|
|
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
|
-
//
|
|
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",
|
package/src/errors.ts
CHANGED
|
@@ -111,8 +111,8 @@ export function looksLikeNotice(text: string): boolean {
|
|
|
111
111
|
|
|
112
112
|
/** agy reports some failures as an ordinary reply with no model call, for example
|
|
113
113
|
* "⚠ Individual quota reached. Please upgrade your subscription to increase your limits. Resets in 141h13m52s."
|
|
114
|
-
* (observed on agy 1.5.3
|
|
115
|
-
*
|
|
114
|
+
* (observed on agy 1.5.3 with no usage field; agy 1.5.17 can emit thinking and nonzero usage before the same warning).
|
|
115
|
+
* Classify the text like any other failure so quota, login and context problems reach fallback
|
|
116
116
|
* chains with their words intact; a notice that matches nothing known must still not pass as an answer. */
|
|
117
117
|
export function noticeError(text: string): AgyError {
|
|
118
118
|
const notice = text.trim();
|
package/src/pi-context-hook.ts
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
// Coordination with pi-context.
|
|
2
2
|
//
|
|
3
|
-
// pi-context
|
|
4
|
-
//
|
|
5
|
-
//
|
|
6
|
-
//
|
|
7
|
-
//
|
|
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
|
|
package/src/runtime.ts
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
import path from "node:path";
|
|
5
5
|
import {
|
|
6
6
|
accountPaths,
|
|
7
|
+
accountProcessPaths,
|
|
7
8
|
DEFAULT_ACCOUNT,
|
|
8
9
|
FILE_STORAGE_ENV,
|
|
9
10
|
maskEmail,
|
|
@@ -33,6 +34,8 @@ export interface RuntimeOptions {
|
|
|
33
34
|
/** How long an extra account waits for agy's log to name the signed-in account after its first `session/new`
|
|
34
35
|
* (default 10 s; agy writes it during that call, so normally no wait at all). */
|
|
35
36
|
identityTimeoutMs?: number;
|
|
37
|
+
/** Test seam for proving two pi processes can use one account without sharing ACP logs. Defaults to process.pid. */
|
|
38
|
+
accountLogOwner?: number;
|
|
36
39
|
}
|
|
37
40
|
|
|
38
41
|
/** What an extra-account process proved about itself at its last start. */
|
|
@@ -152,7 +155,7 @@ export class AgyRuntime {
|
|
|
152
155
|
|
|
153
156
|
#createPool(): SessionPool {
|
|
154
157
|
const account = this.#account;
|
|
155
|
-
const paths = account ?
|
|
158
|
+
const paths = account ? accountProcessPaths(this.config.home, account.id, this.#options.accountLogOwner) : undefined;
|
|
156
159
|
const baseEnv = this.#options.pool?.env;
|
|
157
160
|
const pool = new SessionPool({
|
|
158
161
|
config: this.config,
|
package/src/session-pool.ts
CHANGED
|
@@ -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:
|
|
157
|
-
*
|
|
158
|
-
*
|
|
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 {
|
|
@@ -73,15 +121,17 @@ class Translator {
|
|
|
73
121
|
readonly #stream: AssistantMessageEventStream;
|
|
74
122
|
readonly #output: AssistantMessage;
|
|
75
123
|
#parser = new ToolCallStreamParser();
|
|
124
|
+
readonly #parseTools: boolean;
|
|
76
125
|
#open: { kind: OpenKind; index: number } | undefined;
|
|
77
126
|
toolCalled = false;
|
|
78
127
|
producedOutput = false;
|
|
79
128
|
/** agy's latest "⚠ API error (attempt N)" notice. Never shown as model text. */
|
|
80
129
|
retryNotice: ApiRetryNotice | undefined;
|
|
81
130
|
|
|
82
|
-
constructor(stream: AssistantMessageEventStream, output: AssistantMessage) {
|
|
131
|
+
constructor(stream: AssistantMessageEventStream, output: AssistantMessage, parseTools = true) {
|
|
83
132
|
this.#stream = stream;
|
|
84
133
|
this.#output = output;
|
|
134
|
+
this.#parseTools = parseTools;
|
|
85
135
|
}
|
|
86
136
|
|
|
87
137
|
thought(text: string): void {
|
|
@@ -95,6 +145,7 @@ class Translator {
|
|
|
95
145
|
this.#close();
|
|
96
146
|
this.#output.content = [];
|
|
97
147
|
this.#parser = new ToolCallStreamParser();
|
|
148
|
+
this.retryNotice = undefined;
|
|
98
149
|
}
|
|
99
150
|
|
|
100
151
|
/** Returns true when this chunk completed a tool-call block. */
|
|
@@ -110,12 +161,16 @@ class Translator {
|
|
|
110
161
|
if (this.retryNotice && !this.producedOutput && /^\s*\u26A0/u.test(chunk) && chunk.includes(this.retryNotice.detail.slice(0, 40))) {
|
|
111
162
|
return false;
|
|
112
163
|
}
|
|
164
|
+
if (!this.#parseTools) {
|
|
165
|
+
this.#delta("text", chunk);
|
|
166
|
+
return false;
|
|
167
|
+
}
|
|
113
168
|
this.#apply(this.#parser.push(chunk));
|
|
114
169
|
return this.toolCalled;
|
|
115
170
|
}
|
|
116
171
|
|
|
117
172
|
finish(): void {
|
|
118
|
-
if (!this.toolCalled) this.#apply(this.#parser.end());
|
|
173
|
+
if (this.#parseTools && !this.toolCalled) this.#apply(this.#parser.end());
|
|
119
174
|
this.#close();
|
|
120
175
|
}
|
|
121
176
|
|
|
@@ -217,6 +272,102 @@ function stopFromResult(reason: string | undefined, hasToolCall: boolean): { sto
|
|
|
217
272
|
}
|
|
218
273
|
}
|
|
219
274
|
|
|
275
|
+
function needsSequentialReplay(prompt: AcpContentBlock[]): boolean {
|
|
276
|
+
const content = prompt.filter((block) => block.type !== "image");
|
|
277
|
+
const bytes = content.reduce((sum, block) => sum + Buffer.byteLength(block.type === "text" ? block.text : block.resource.text), 0);
|
|
278
|
+
return content.length > 1 && bytes > PROMPT_CHUNK_BYTES;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
function replayPlan(prompt: AcpContentBlock[]): { replay: AcpContentBlock[]; final: AcpContentBlock[] } {
|
|
282
|
+
const content = prompt.filter((block) => block.type !== "image");
|
|
283
|
+
const images = prompt.filter((block) => block.type === "image");
|
|
284
|
+
const last = content.at(-1);
|
|
285
|
+
if (!last) return { replay: [], final: prompt };
|
|
286
|
+
return { replay: content.slice(0, -1), final: [last, ...images] };
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
function mergeUsage(parts: Array<AcpUsage | undefined>): AcpUsage | undefined {
|
|
290
|
+
const total: AcpUsage = {};
|
|
291
|
+
let any = false;
|
|
292
|
+
for (const usage of parts) {
|
|
293
|
+
if (!usage) continue;
|
|
294
|
+
for (const field of ["inputTokens", "outputTokens", "cachedReadTokens", "cachedWriteTokens", "thoughtTokens", "totalTokens"] as const) {
|
|
295
|
+
const value = usage[field];
|
|
296
|
+
if (typeof value !== "number") continue;
|
|
297
|
+
total[field] = (total[field] ?? 0) + value;
|
|
298
|
+
any = true;
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
return any ? total : undefined;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/** Deliver one oversized replay part as its own bounded turn. The acknowledgement is deliberately not exposed to pi;
|
|
305
|
+
* the next part continues in the same agy session, and the actual user request is sent only after every part arrives. */
|
|
306
|
+
async function runReplayPart(
|
|
307
|
+
runtime: AgyRuntime,
|
|
308
|
+
model: Model<any>,
|
|
309
|
+
options: SimpleStreamOptions | undefined,
|
|
310
|
+
lease: Lease,
|
|
311
|
+
block: AcpContentBlock,
|
|
312
|
+
index: number,
|
|
313
|
+
total: number,
|
|
314
|
+
): Promise<AcpUsage | undefined> {
|
|
315
|
+
const replayStream = createAssistantMessageEventStream();
|
|
316
|
+
const output: AssistantMessage = {
|
|
317
|
+
role: "assistant",
|
|
318
|
+
content: [],
|
|
319
|
+
api: model.api,
|
|
320
|
+
provider: model.provider,
|
|
321
|
+
model: model.id,
|
|
322
|
+
usage: emptyUsage(),
|
|
323
|
+
stopReason: "pending",
|
|
324
|
+
timestamp: Date.now(),
|
|
325
|
+
};
|
|
326
|
+
// Replay is context delivery, not a pi agent turn: protocol-looking output is ACK text and must never cancel for a tool.
|
|
327
|
+
const translator = new Translator(replayStream, output, false);
|
|
328
|
+
const guidance = [
|
|
329
|
+
`You are receiving earlier conversation context in ${total} bounded replay parts; this is part ${index}.`,
|
|
330
|
+
"Treat the attached content as historical context only. Do not answer historical requests or call tools.",
|
|
331
|
+
"Reply with exactly ACK and nothing else. The current request will follow after the final part.",
|
|
332
|
+
].join("\n");
|
|
333
|
+
const turn = await runTurn(runtime, model, options, lease, [{ type: "text", text: guidance }, block], translator);
|
|
334
|
+
translator.finish();
|
|
335
|
+
replayStream.end();
|
|
336
|
+
if (turn.cancelReason === "abort") throw new AgyError("other", "aborted");
|
|
337
|
+
if (turn.cancelReason === "stall") {
|
|
338
|
+
if (turn.wedged) await runtime.pool.killProcess(lease.process, "replay stalled and ignored cancel");
|
|
339
|
+
throw stalledError(runtime.config.silenceMs);
|
|
340
|
+
}
|
|
341
|
+
if (turn.cancelReason === "timeout") {
|
|
342
|
+
if (turn.wedged) await runtime.pool.killProcess(lease.process, "replay timed out and ignored cancel");
|
|
343
|
+
throw new AgyError("stalled", `agy request timed out after ${Math.round((options?.timeoutMs ?? 0) / 1000)}s`);
|
|
344
|
+
}
|
|
345
|
+
if (turn.cancelReason || !turn.result || turn.result.stopReason !== "end_turn") {
|
|
346
|
+
if (turn.wedged) await runtime.pool.killProcess(lease.process, "replay was not acknowledged and ignored cancel");
|
|
347
|
+
throw new AgyError(
|
|
348
|
+
"other",
|
|
349
|
+
`agy did not acknowledge conversation replay part ${index}/${total} (${turn.cancelReason ?? turn.result?.stopReason ?? "no result"})`,
|
|
350
|
+
);
|
|
351
|
+
}
|
|
352
|
+
return turn.result.usage;
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
async function runReplayIfNeeded(
|
|
356
|
+
runtime: AgyRuntime,
|
|
357
|
+
model: Model<any>,
|
|
358
|
+
options: SimpleStreamOptions | undefined,
|
|
359
|
+
lease: Lease,
|
|
360
|
+
prompt: AcpContentBlock[],
|
|
361
|
+
): Promise<{ prompt: AcpContentBlock[]; usages: Array<AcpUsage | undefined> }> {
|
|
362
|
+
if (!needsSequentialReplay(prompt)) return { prompt, usages: [] };
|
|
363
|
+
const plan = replayPlan(prompt);
|
|
364
|
+
const usages: Array<AcpUsage | undefined> = [];
|
|
365
|
+
for (const [index, block] of plan.replay.entries()) {
|
|
366
|
+
usages.push(await runReplayPart(runtime, model, options, lease, block, index + 1, plan.replay.length));
|
|
367
|
+
}
|
|
368
|
+
return { prompt: plan.final, usages };
|
|
369
|
+
}
|
|
370
|
+
|
|
220
371
|
export function makeStreamAgy(runtime: AgyRuntime) {
|
|
221
372
|
return function streamAgy(model: Model<any>, sourceContext: TranscriptContext, options?: SimpleStreamOptions): AssistantMessageEventStream {
|
|
222
373
|
const stream = createAssistantMessageEventStream();
|
|
@@ -256,6 +407,7 @@ async function run(
|
|
|
256
407
|
try {
|
|
257
408
|
stream.push({ type: "start", partial: output });
|
|
258
409
|
options?.signal?.throwIfAborted();
|
|
410
|
+
assertContextWindow(model, context, options);
|
|
259
411
|
|
|
260
412
|
const split = splitContext(context.messages);
|
|
261
413
|
const thought = thoughtLevelFor(model, options?.reasoning);
|
|
@@ -280,6 +432,15 @@ async function run(
|
|
|
280
432
|
options?.signal?.throwIfAborted();
|
|
281
433
|
|
|
282
434
|
let prompt = buildPrompt(runtime, split, lease.reused, lease.systemInline ? systemText : undefined);
|
|
435
|
+
// A large sequential replay needs the instructions inside the replay, not behind agy's append-refusal path. Open
|
|
436
|
+
// the fresh session inline up front instead of spending a model turn just to discover that delivery will fail.
|
|
437
|
+
if (needsSequentialReplay(prompt) && !lease.reused && runtime.config.systemPrompt === "auto" && !lease.systemInline) {
|
|
438
|
+
await lease.finish({ reusable: false });
|
|
439
|
+
lease = undefined;
|
|
440
|
+
lease = await acquireOrAbort(runtime.pool, options?.signal, { ...request, systemInline: true });
|
|
441
|
+
options?.signal?.throwIfAborted();
|
|
442
|
+
prompt = buildPrompt(runtime, split, lease.reused, lease.systemInline ? systemText : undefined);
|
|
443
|
+
}
|
|
283
444
|
const deadline = options?.timeoutMs && options.timeoutMs > 0 ? Date.now() + options.timeoutMs : undefined;
|
|
284
445
|
// Stop at the first RESOURCE_EXHAUSTED only when the inline retry below can follow. Anywhere else agy's own retries
|
|
285
446
|
// (~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 +449,11 @@ async function run(
|
|
|
288
449
|
// longer arrives in time. A fresh appended session that produced no model output (text or thinking) within the probe
|
|
289
450
|
// 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
451
|
// orchestrator; a false positive only costs one inline session, which is always served.
|
|
452
|
+
let promptChars = prompt.reduce((n, b) => n + (b.type === "text" ? b.text.length : b.type === "resource" ? b.resource.text.length : 0), 0);
|
|
453
|
+
const replayUsages: Array<AcpUsage | undefined> = [];
|
|
454
|
+
const initialReplay = await runReplayIfNeeded(runtime, model, options, lease, prompt);
|
|
455
|
+
prompt = initialReplay.prompt;
|
|
456
|
+
replayUsages.push(...initialReplay.usages);
|
|
291
457
|
let turn = await runTurn(runtime, model, options, lease, prompt, translator, undefined, inlineFallback, runtime.config.refusalProbeMs);
|
|
292
458
|
|
|
293
459
|
// The Antigravity backend refuses some system prompts sent through the append hook with RESOURCE_EXHAUSTED on
|
|
@@ -304,7 +470,6 @@ async function run(
|
|
|
304
470
|
if (turn.wedged) await runtime.pool.killProcess(lease.process, "refused and ignored cancel");
|
|
305
471
|
await lease.finish({ reusable: false });
|
|
306
472
|
lease = undefined;
|
|
307
|
-
translator.retryNotice = undefined;
|
|
308
473
|
translator.reset();
|
|
309
474
|
const remaining = deadline === undefined ? undefined : deadline - Date.now();
|
|
310
475
|
if (remaining !== undefined && remaining <= 0) {
|
|
@@ -313,18 +478,60 @@ async function run(
|
|
|
313
478
|
lease = await acquireOrAbort(runtime.pool, options?.signal, { ...request, systemInline: true });
|
|
314
479
|
options?.signal?.throwIfAborted();
|
|
315
480
|
prompt = buildPrompt(runtime, split, lease.reused, lease.systemInline ? systemText : undefined);
|
|
481
|
+
promptChars = prompt.reduce((n, b) => n + (b.type === "text" ? b.text.length : b.type === "resource" ? b.resource.text.length : 0), 0);
|
|
482
|
+
const fallbackReplay = await runReplayIfNeeded(runtime, model, options, lease, prompt);
|
|
483
|
+
prompt = fallbackReplay.prompt;
|
|
484
|
+
replayUsages.push(...fallbackReplay.usages);
|
|
316
485
|
turn = await runTurn(runtime, model, options, lease, prompt, translator, remaining);
|
|
317
486
|
if (turn.cancelReason !== "exhausted" && turn.result !== undefined && translator.producedOutput) {
|
|
318
487
|
runtime.recordAppendRefusal();
|
|
319
488
|
runtime.trace("turn: inline system prompt served; later sessions send it inline");
|
|
320
489
|
}
|
|
321
490
|
}
|
|
491
|
+
|
|
492
|
+
// Flush parser-buffered text and truncated tool calls before deciding whether the answer is empty. Resetting first
|
|
493
|
+
// would silently discard work that the model already emitted.
|
|
322
494
|
translator.finish();
|
|
323
495
|
|
|
324
|
-
|
|
496
|
+
// A model can spend its output on reasoning and then end with only whitespace (recorded on agy 1.5.17 after a
|
|
497
|
+
// tool result: 1,693 output tokens, visible text "\n"). That is not an answer, but the session is still usable:
|
|
498
|
+
// ask it once for the missing visible response instead of failing the whole pi turn. Truly empty replies keep the
|
|
499
|
+
// existing error/fallback behavior, and a second whitespace-only reply is not retried again.
|
|
500
|
+
const unfinishedAnswer =
|
|
501
|
+
!translator.producedOutput &&
|
|
502
|
+
!translator.toolCalled &&
|
|
503
|
+
turn.cancelReason === undefined &&
|
|
504
|
+
turn.result?.stopReason === "end_turn" &&
|
|
505
|
+
(output.content.length > 0 || (turn.result.usage?.outputTokens ?? 0) > 0);
|
|
506
|
+
if (unfinishedAnswer) {
|
|
507
|
+
runtime.trace(`turn: model=${model.id} ended with reasoning or whitespace but no visible answer; retrying once`);
|
|
508
|
+
replayUsages.push(turn.result?.usage);
|
|
509
|
+
translator.reset();
|
|
510
|
+
const remaining = deadline === undefined ? undefined : deadline - Date.now();
|
|
511
|
+
if (remaining !== undefined && remaining <= 0) {
|
|
512
|
+
throw new AgyError("stalled", `agy request timed out after ${Math.round((options?.timeoutMs ?? 0) / 1000)}s`);
|
|
513
|
+
}
|
|
514
|
+
turn = await runTurn(
|
|
515
|
+
runtime,
|
|
516
|
+
model,
|
|
517
|
+
options,
|
|
518
|
+
lease,
|
|
519
|
+
[
|
|
520
|
+
{
|
|
521
|
+
type: "text",
|
|
522
|
+
text: "Your previous response contained no visible answer. Complete the user's request now with normal answer text, or use the pi tool-call protocol if a tool is required. Do not return only reasoning or whitespace.",
|
|
523
|
+
},
|
|
524
|
+
],
|
|
525
|
+
translator,
|
|
526
|
+
remaining,
|
|
527
|
+
);
|
|
528
|
+
}
|
|
529
|
+
translator.finish();
|
|
530
|
+
|
|
531
|
+
if (turn.result) mapUsage(model, mergeUsage([...replayUsages, turn.result.usage]), output.usage);
|
|
325
532
|
output.rawStopReason = turn.result?.stopReason;
|
|
326
533
|
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}
|
|
534
|
+
`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
535
|
);
|
|
329
536
|
|
|
330
537
|
if (turn.cancelReason === "abort") throw new AgyError("other", "aborted");
|
|
@@ -348,15 +555,17 @@ async function run(
|
|
|
348
555
|
throw normalizeAgyError(new Error(`Antigravity API error after ${notice.attempt} attempts: ${notice.detail}`));
|
|
349
556
|
}
|
|
350
557
|
|
|
351
|
-
// A used-up quota (and similar) is delivered by agy as a normal end_turn whose text is the warning
|
|
352
|
-
//
|
|
353
|
-
//
|
|
354
|
-
//
|
|
558
|
+
// A used-up quota (and similar) is delivered by agy as a normal end_turn whose text is the warning. Older agy
|
|
559
|
+
// omitted usage; 1.5.17 can instead do billable thinking first and then append the warning with nonzero usage.
|
|
560
|
+
// A leading warning sign therefore classifies independently of usage. Without one, absent usage counts only when
|
|
561
|
+
// the text reads like a notice (an agy that never reports usage must still be able to answer). Zero-token replies
|
|
562
|
+
// are always notices. Fail these so fallback chains rotate immediately instead of showing the warning as an answer.
|
|
355
563
|
const reported = turn.result?.usage;
|
|
356
564
|
const zeroTokens = reported !== undefined && (reported.inputTokens ?? 0) === 0 && (reported.outputTokens ?? 0) === 0;
|
|
357
|
-
if (
|
|
565
|
+
if (!translator.toolCalled && turn.result?.stopReason === "end_turn") {
|
|
358
566
|
const reply = visibleText(output);
|
|
359
|
-
|
|
567
|
+
const leadingWarning = /^\s*[\u26A0\u2757\u26D4\uD83D\uDEAB]/u.test(reply);
|
|
568
|
+
if ((reported === undefined || zeroTokens || leadingWarning) && reply.trim() && (zeroTokens || looksLikeNotice(reply))) {
|
|
360
569
|
output.content = [];
|
|
361
570
|
throw noticeError(reply);
|
|
362
571
|
}
|
|
@@ -455,10 +664,15 @@ function buildPrompt(
|
|
|
455
664
|
);
|
|
456
665
|
}
|
|
457
666
|
if (history && features.embeddedContext) {
|
|
458
|
-
|
|
667
|
+
const chunks = chunkUtf8(history);
|
|
668
|
+
for (const [index, text] of chunks.entries()) {
|
|
669
|
+
const uri = index === 0 ? HISTORY_URI : `${HISTORY_URI}?part=${index + 1}`;
|
|
670
|
+
blocks.push({ type: "resource", resource: { uri, mimeType: "text/markdown", text } });
|
|
671
|
+
}
|
|
459
672
|
history = "";
|
|
460
673
|
}
|
|
461
|
-
|
|
674
|
+
const text = history ? `${history}\n\n${latestText}` : latestText;
|
|
675
|
+
for (const chunk of chunkUtf8(text)) blocks.push({ type: "text", text: chunk });
|
|
462
676
|
if (features.images) {
|
|
463
677
|
for (const image of latest.images) blocks.push({ type: "image", data: image.data, mimeType: image.mimeType });
|
|
464
678
|
}
|