@estebanforge/pi-antigravity-bridge 1.10.8 → 1.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +16 -0
- package/README.md +2 -2
- package/extensions/index.ts +31 -3
- package/package.json +1 -1
- package/src/config.ts +12 -12
- package/src/handoff-toast.ts +21 -0
- package/src/provider.ts +190 -34
- package/src/quota-notice.ts +40 -0
- package/src/sessions.ts +16 -0
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,22 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to this project will be documented in this file.
|
|
4
4
|
|
|
5
|
+
## [1.11.0] - 2026-11-18
|
|
6
|
+
|
|
7
|
+
### Added
|
|
8
|
+
|
|
9
|
+
- **Model-switch handoff toast.** Selecting an Antigravity bridge model with no bound agy conversation (the mid-session switch from another provider) now toasts "handoff context will ship to the new agy conversation", so the fresh-conversation handoff is visible instead of silent. Suppressed on session restore, for bound conversations (they continue as-is), when the digest is off (nothing would ship), and on an empty session (nothing to hand off). UI only; binding is checked with the provider's own `sessionKey` derivation and a failure to compute it stays silent rather than lying.
|
|
10
|
+
|
|
11
|
+
### Fixed
|
|
12
|
+
|
|
13
|
+
- **Context now hands off to a fresh Antigravity conversation opened mid-session.** Switching pi models onto an Antigravity bridge model (or an engine switch, or issue #1 conversation recreation) opened a fresh agy conversation that received only the latest user prompt - Gemini answered "ok, ready for the task" as if starting from scratch, because the G1 context digest was gated on a config flag that defaulted to off. The digest is now on by default and self-gating: it ships only when the delta window is non-empty and every piece ships exactly once, so pure antigravity sessions keep byte-stable prompts and an intact server-side prompt cache. The builder learns two modes: bound (default, own-provider turns skipped as before) and fresh (own turns and their tool results included, for a conversation whose server-side history is empty). Compaction-aware watermark reset: a compaction shrinks the transcript below the stored `lastMessageCount`, which used to empty the delta window and silently drop every post-compaction turn; the window now restarts after the compaction with the summary shipped once, keyed by summary CONTENT (`digestSummaryId` on the session record - pi puts every post-compaction summary at the transcript front, so index identity would swallow the second compaction). A boundary fingerprint (`digestBoundary`, role+timestamp of the watermark message) resets the delta to the full digest when the transcript mutated under the stored count (/tree, /fork, per-call context-hook rewrites) instead of shipping a silently wrong window; that reset - and a delivered compaction - may re-ship recent user messages agy already holds, bounded by the digest cap, in exchange for never dropping context. Records written before this release keep their stored watermark (no duplicate dump on upgrade) and gain the new fields on their first turn. On stream-json the digest is budgeted under the ~25KB single-prompt silent-drop cap (issue #2) in BYTES, both for the user's prompt and the digest itself, including multibyte content; an oversized compaction summary is clamped (head kept, `[truncated]` marker), and an exhausted budget ships nothing rather than a turn agy would silently drop. `digest: false` / `AGY_DIGEST=0` / `/agy digest off` keeps the old opt-out behavior.
|
|
14
|
+
|
|
15
|
+
## [1.10.9] - 2026-11-17
|
|
16
|
+
|
|
17
|
+
### Fixed
|
|
18
|
+
|
|
19
|
+
- **Quota exhaustion settles as a retryable provider error instead of assistant text (issue #16).** When an Antigravity account's quota is spent, agy streams the quota notice ("⚠ Individual quota reached ... Resets in 153h38m14s") as plain agent text and ends the turn with `end_turn`, so the turn settled as a successful reply (`stopReason: "stop"`) and provider failover (pi-router, or any consumer keyed on pi's error classification) never fired. A text-only turn whose settled response matches the notice shape (anchored at the start, ≤400 chars, optional reset interval parsed out) now finalizes with `stopReason: "error"` and a retryable-classified message (`agy rate limit (ResourceExhausted): Antigravity quota exhausted; resets in ...`). The wording is load-bearing: pi-ai's `isRetryableAssistantError` gates failover and classifies "quota exceeded"/"billing" wording as fail-fast (no router handoff), so the message carries the retryable markers and never echoes the raw notice, keeping upstream copy drift from poisoning the classification. Turns that ran tools or produced thinking keep the normal reply, and the session binding is untouched (the conversation is healthy). Without a router, pi's built-in retry re-runs the same exhausted account within its retry budget - bounded, but expect repeat attempts until the reset lapses. Detection is content-based pending a structured upstream signal (none documented in ACP-PROTOCOL-REFERENCE.md; a live probe on an exhausted account would settle it).
|
|
20
|
+
|
|
5
21
|
## [1.10.8] - 2026-11-16
|
|
6
22
|
|
|
7
23
|
### Added
|
package/README.md
CHANGED
|
@@ -118,7 +118,7 @@ If `agy models` fails at load (binary missing, auth not done, network stall), a
|
|
|
118
118
|
| `askTool` | `on` (register the AskAntigravity delegation tool), `off` (no delegation tool; provider and models only) | `on` |
|
|
119
119
|
| `webTools` | `off` (no web tools), `on` (register `agy_web_search` + `agy_read_url` as Pi tools, usable by ANY provider's model). Each call spawns a one-shot search-only `agy` agent (plan mode, bridge MCP inheritance off), gates the answer on an observed native `search_web`/`read_url_content` step, and spends Antigravity quota. Off by default: Antigravity sessions already have native web tools on both engines; these serve other providers | `off` |
|
|
120
120
|
| `bridgeTools` | `none` (bridge off), `all` (every non-builtin tool, incl. other `Ask*` delegations), `mcp` (pi-mcp-adapter tools + skills bridge only) | `all` |
|
|
121
|
-
| `digest` |
|
|
121
|
+
| `digest` | Self-gating delta of pi-side context (compaction summaries, other-provider turns, handoffs after a mid-session switch) shipped to agy only when the delta is non-empty, each piece once. Pure antigravity sessions get byte-stable prompts and an intact prompt cache. `off` = agy prompts contain only your message; a conversation opened mid-session starts without prior pi-side context | `on` |
|
|
122
122
|
| `systemPrompt` | `on` (send pi's system prompt - operating instructions plus the global agent-dir `AGENTS.md` and ancestor `AGENTS.md`/`CLAUDE.md` - to the first prompt of each new agy conversation, plus a tool-priority note: Pi Bridge tools win over agy's native interactive ones, which never reach the user. Delivery: stream-json stages it as an agy agent file via `--agent`, off the prompt line - the CLI silently drops single prompts past a ~25KB cap and the dropped turn kills the conversation; the carrier declares the productive toolset explicitly (omitting `tools:` reads as a read-only set upstream, issue #13) plus `subagent: false` + `agents: []` so the native subagent tools stay masked (ACP carries no agent file, so its natives remain and the tool-priority note steers the model to pi delegation). ACP prepends it to the first prompt) or `off` (agy-native behavior) | `on` |
|
|
123
123
|
| `turnTimeoutMin` | Overall cap on ONE agy turn, minutes, both engines. Parked time (pi-tool round-trips, escalated calls, human-gated approvals) does not count against it on either engine: the cap pauses with remaining-budget semantics and resumes on unpark. When it fires, the bridge kills the agy process mid-task ("ACP turn exceeded the 10m deadline" / "agy exceeded the 10m turn timeout") - it is a bridge cap, not a Google server limit. Default is TTY-aware: `0` (no cap) on an interactive pi - you are the backstop with Esc; `20` headless, where nobody can abort and one runaway turn blocks the serialized turn queue. Opt into a gate with 1-1440 (free type via `config.json` or `/agy timeout <1-1440|off>`, or the `/agy` picker's preset list); `0` disables explicitly; anything else falls back to the TTY-aware default. The 5m inactivity stall guard always still bounds a hung server | `0` TTY / `20` headless |
|
|
124
124
|
| `inactivityTimeoutMin` | Silence cap, minutes, both engines: no stream-json stdout / no ACP session/update for this long fails the turn as a stall. `0` disables the guard. Parks (bridge calls, escalated calls, ACP permission dialogs) pause it; agy-native long steps such as builds do not. A false kill costs the whole turn, and on stream-json a stall kill with no result frame clears the conversation binding. Keep `5`; use `2`-`3` only when native steps are known to be short; do not use `1` | `5` |
|
|
@@ -143,7 +143,7 @@ The `activate_skill` catalog mirrors pi's directory-based skill discovery: the t
|
|
|
143
143
|
/agy ask on|off register the AskAntigravity delegation tool (default on; off keeps only the provider and models, even with pi-ask-antigravity installed)
|
|
144
144
|
/agy model flash|pro|gemini fallback model for the AskAntigravity tool; callers may override per call
|
|
145
145
|
/agy thinking low|medium|high fallback thinking tier for the AskAntigravity tool; callers may override per call
|
|
146
|
-
/agy digest on|off
|
|
146
|
+
/agy digest on|off ship pi-side context to agy when the delta is non-empty (default on; see table above)
|
|
147
147
|
/agy system-prompt on|off send pi's system prompt + AGENTS.md + the Pi Bridge tool-priority note to new agy conversations (default on)
|
|
148
148
|
/agy bridge all|mcp|none which pi tools the MCP bridge exposes to agy (default all; none = bridge off; a running server picks up the new catalog immediately, a stopped one on the next start)
|
|
149
149
|
/agy tools [hide|show <name>|reset] session-only bridge-catalog hides (multi-word names OK; reset restores the full set; bare lists exposed + hidden; never touches saved config)
|
package/extensions/index.ts
CHANGED
|
@@ -46,8 +46,10 @@ import {
|
|
|
46
46
|
defaultEscalateAfterMs,
|
|
47
47
|
formatEscalatedAck,
|
|
48
48
|
formatPollAnswer,
|
|
49
|
+
sessionKey,
|
|
49
50
|
type NativeDisplayEvent,
|
|
50
51
|
} from "../src/provider.js";
|
|
52
|
+
import { handoffToast } from "../src/handoff-toast.js";
|
|
51
53
|
import { PollRunFolder, type PollRunData } from "../src/poll-fold.js";
|
|
52
54
|
import {
|
|
53
55
|
createShadowTool,
|
|
@@ -604,6 +606,32 @@ export default async function (pi: ExtensionAPI): Promise<void> {
|
|
|
604
606
|
for (const handle of backgroundWatchers.values()) handle.stop();
|
|
605
607
|
backgroundWatchers.clear();
|
|
606
608
|
});
|
|
609
|
+
// Model-switch handoff toast: entering an unbound antigravity model
|
|
610
|
+
// mid-session opens a fresh agy conversation on the next turn; the
|
|
611
|
+
// digest re-delivers pi-side context into it. UI only.
|
|
612
|
+
pi.on("model_select", (event, ctx) => {
|
|
613
|
+
try {
|
|
614
|
+
const msg = handoffToast({
|
|
615
|
+
api: event.model?.api,
|
|
616
|
+
digestEnabled: loadConfig().digest,
|
|
617
|
+
source: event.source,
|
|
618
|
+
bound: (() => {
|
|
619
|
+
// getSessionId is missing from the published ReadonlySessionManager
|
|
620
|
+
// type (dts minification), so shape-cast instead of trusting it.
|
|
621
|
+
const sm = ctx.sessionManager as { getSessionId?: () => string };
|
|
622
|
+
const sid = sm.getSessionId?.();
|
|
623
|
+
const key = sessionKey(sid ? { sessionId: sid } : undefined, ctx.cwd, engine);
|
|
624
|
+
return store.get(key) !== null;
|
|
625
|
+
})(),
|
|
626
|
+
hasContext: ctx.sessionManager
|
|
627
|
+
.getEntries()
|
|
628
|
+
.some((e) => (e as { type?: string }).type === "message"),
|
|
629
|
+
});
|
|
630
|
+
if (msg && ctx.hasUI) ctx.ui.notify(msg, "info");
|
|
631
|
+
} catch (err) {
|
|
632
|
+
fileLog.log("handoff-toast-error", { error: err instanceof Error ? err.message : String(err) }, "warn");
|
|
633
|
+
}
|
|
634
|
+
});
|
|
607
635
|
const streamSimple = createStreamSimple({
|
|
608
636
|
entries,
|
|
609
637
|
store,
|
|
@@ -1738,8 +1766,8 @@ function registerAgyCommand(pi: ExtensionAPI, ctx: AgyCommandCtx): void {
|
|
|
1738
1766
|
const next = saveConfig({ digest: val === "on" });
|
|
1739
1767
|
ui?.notify(
|
|
1740
1768
|
next.digest
|
|
1741
|
-
? "digest on. pi-side context (
|
|
1742
|
-
: "digest off. agy prompts contain only your message;
|
|
1769
|
+
? "digest on. pi-side context ships when the delta is non-empty (fresh-conversation handoff, other-provider turns, pi-side tool runs, compaction summaries), each piece once. Pure antigravity sessions keep byte-stable prompts."
|
|
1770
|
+
: "digest off. agy prompts contain only your message; a conversation opened mid-session starts without prior pi-side context.",
|
|
1743
1771
|
"info",
|
|
1744
1772
|
);
|
|
1745
1773
|
} else {
|
|
@@ -1879,7 +1907,7 @@ async function openAgyPicker(ui: ExtensionUIContext, ctx: AgyCommandCtx): Promis
|
|
|
1879
1907
|
id: "digest",
|
|
1880
1908
|
label: "Context digest",
|
|
1881
1909
|
description:
|
|
1882
|
-
"
|
|
1910
|
+
"Ship pi-side context (handoffs, other-provider turns, compactions) to agy when the delta is non-empty. Pure antigravity sessions keep byte-stable prompts.",
|
|
1883
1911
|
currentValue: config.digest ? "on" : "off",
|
|
1884
1912
|
values: ["on", "off"],
|
|
1885
1913
|
},
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@estebanforge/pi-antigravity-bridge",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.11.0",
|
|
4
4
|
"description": "Gemini provider for Pi on the Antigravity ACP server (official Google ACP) or the stream-json agy CLI. Use antigravity/* models in Pi. Full /model picker support. Models runs Pi's tools. ToS safe to use.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"pi-package",
|
package/src/config.ts
CHANGED
|
@@ -156,18 +156,18 @@ export interface AgyConfig {
|
|
|
156
156
|
* the file. Takes effect on the next bridge call. */
|
|
157
157
|
escalateLongTools?: string[];
|
|
158
158
|
/** Inject a delta digest of pi-side context (compaction summaries, turns
|
|
159
|
-
* handled by other providers or pi's own tools) into
|
|
159
|
+
* handled by other providers or pi's own tools) into agy prompts.
|
|
160
160
|
*
|
|
161
|
-
* Default
|
|
162
|
-
*
|
|
163
|
-
*
|
|
164
|
-
*
|
|
161
|
+
* Default ON. The digest is self-gating: it ships only when the delta
|
|
162
|
+
* window is non-empty (a fresh agy conversation from a mid-session model
|
|
163
|
+
* switch or engine switch, another provider's turns, pi-side tool runs,
|
|
164
|
+
* or a compaction summary), and each piece ships once. Pure antigravity
|
|
165
|
+
* sessions get an empty delta, byte-stable prompts, and an intact
|
|
166
|
+
* server-side prompt cache.
|
|
165
167
|
*
|
|
166
|
-
*
|
|
167
|
-
*
|
|
168
|
-
*
|
|
169
|
-
* sessions gain nothing: agy already keeps its own history, and bridge
|
|
170
|
-
* round-trips deliver tool results through the bridge, not the digest. */
|
|
168
|
+
* Turn off for agy-native behavior: prompts then contain only your
|
|
169
|
+
* message, and a conversation opened mid-session starts without prior
|
|
170
|
+
* pi-side context. */
|
|
171
171
|
digest: boolean;
|
|
172
172
|
/** Prepend pi's composed system prompt (pi tool guidance + the global
|
|
173
173
|
* agent-dir AGENTS.md and ancestor AGENTS.md/CLAUDE.md) to the FIRST
|
|
@@ -216,7 +216,7 @@ const DEFAULTS: AgyConfig = {
|
|
|
216
216
|
askTool: true,
|
|
217
217
|
webTools: false,
|
|
218
218
|
bridgeTools: "all",
|
|
219
|
-
digest:
|
|
219
|
+
digest: true,
|
|
220
220
|
systemPrompt: true,
|
|
221
221
|
turnTimeoutMin: 0, // placeholder: the real default is resolved per loadConfig call (defaultTurnTimeoutMin)
|
|
222
222
|
inactivityTimeoutMin: 5,
|
|
@@ -375,7 +375,7 @@ export function loadConfig(configPath: string = CONFIG_PATH): AgyConfig {
|
|
|
375
375
|
|
|
376
376
|
const digest = process.env.AGY_DIGEST !== undefined
|
|
377
377
|
? ["1", "true", "on"].includes(process.env.AGY_DIGEST.toLowerCase())
|
|
378
|
-
: file.digest ??
|
|
378
|
+
: file.digest ?? true;
|
|
379
379
|
|
|
380
380
|
const envSys = process.env.AGY_SYSTEM_PROMPT;
|
|
381
381
|
const systemPrompt = envSys !== undefined
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/** Model-switch handoff toast (UI only): the message shown when the user
|
|
2
|
+
* lands on an antigravity bridge model that has no bound agy conversation,
|
|
3
|
+
* telling them pi-side context will re-deliver into the fresh conversation.
|
|
4
|
+
* Returns null when the toast must stay silent. */
|
|
5
|
+
|
|
6
|
+
const BRIDGE_API = "agy-bridge";
|
|
7
|
+
|
|
8
|
+
export function handoffToast(input: {
|
|
9
|
+
api: string | undefined;
|
|
10
|
+
digestEnabled: boolean;
|
|
11
|
+
bound: boolean;
|
|
12
|
+
hasContext: boolean;
|
|
13
|
+
source: "set" | "cycle" | "restore";
|
|
14
|
+
}): string | null {
|
|
15
|
+
if (input.source === "restore") return null;
|
|
16
|
+
if (input.api !== BRIDGE_API) return null;
|
|
17
|
+
if (!input.digestEnabled) return null;
|
|
18
|
+
if (input.bound) return null;
|
|
19
|
+
if (!input.hasContext) return null;
|
|
20
|
+
return "handoff context will ship to the new agy conversation";
|
|
21
|
+
}
|
package/src/provider.ts
CHANGED
|
@@ -40,6 +40,7 @@ import { toPiUsage } from "./stream-events.js";
|
|
|
40
40
|
import { mapAgyToolToNative } from "./native-tools.js";
|
|
41
41
|
import { toAgyEffort, type AgyModelEntry } from "./models.js";
|
|
42
42
|
import { SessionStore } from "./sessions.js";
|
|
43
|
+
import { detectQuotaNotice, quotaErrorMessage } from "./quota-notice.js";
|
|
43
44
|
import { loadConfig } from "./config.js";
|
|
44
45
|
import { GATE_MARKER, mapNativeToShadow, stripMarkerFields } from "./approval-gate.js";
|
|
45
46
|
import type { ApprovalDecision, ApprovalPayload, ApprovalParkApi } from "./mcp-server.js";
|
|
@@ -231,15 +232,91 @@ export interface DigestOptions {
|
|
|
231
232
|
ownProvider?: string;
|
|
232
233
|
/** Soft cap on the digest body (0 = unbounded). Default 8000. */
|
|
233
234
|
maxChars?: number;
|
|
235
|
+
/** Conversation binding state. bound=true (default): own-provider turns
|
|
236
|
+
* are already in agy's resumed DB and are skipped. bound=false: the agy
|
|
237
|
+
* conversation holds NOTHING (fresh conversation from a mid-session
|
|
238
|
+
* model switch, an engine switch, or recreation recovery), so
|
|
239
|
+
* own-provider turns and their tool results ship too. */
|
|
240
|
+
bound?: boolean;
|
|
241
|
+
/** Compaction summary identity already delivered in a previous digest
|
|
242
|
+
* (compactionFingerprint of the stripped summary text). Index identity
|
|
243
|
+
* is wrong: pi rebuilds post-compaction transcripts with the summary at
|
|
244
|
+
* the front, so every compaction lands at the same index; content
|
|
245
|
+
* identity ships a NEW summary exactly once. */
|
|
246
|
+
seenSummaryId?: string;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/** Soft cap on the digest body when no tighter budget applies. */
|
|
250
|
+
const DIGEST_MAX_CHARS = 8000;
|
|
251
|
+
|
|
252
|
+
/** stream-json single-prompt silent-drop cap (issue #2, probed 2026-09-30):
|
|
253
|
+
* the CLI drops any prompt past ~25KB with SUCCESS and an empty response,
|
|
254
|
+
* and the dropped turn leaves the conversation permanently unresponsive. */
|
|
255
|
+
const STREAM_JSON_PROMPT_CAP = 25_000;
|
|
256
|
+
/** Headroom under the cap for the staged-image note and prompt framing. */
|
|
257
|
+
const STREAM_JSON_PROMPT_MARGIN = 4_096;
|
|
258
|
+
|
|
259
|
+
/** Per-engine digest cap. ACP ships the digest as an embeddedContext
|
|
260
|
+
resource block: no prompt cap applies, so the default cap stands. On
|
|
261
|
+
stream-json the digest rides inline in the prompt, so it must fit under
|
|
262
|
+
the silent-drop budget alongside the user's own prompt bytes. Returns
|
|
263
|
+
null when the budget is already exhausted (ship nothing rather than a
|
|
264
|
+
digest that would push the turn over the drop cap). */
|
|
265
|
+
export function digestMaxCharsForEngine(engine: string, promptLength: number): number | null {
|
|
266
|
+
if (engine === "acp") return DIGEST_MAX_CHARS;
|
|
267
|
+
const budget = STREAM_JSON_PROMPT_CAP - promptLength - STREAM_JSON_PROMPT_MARGIN;
|
|
268
|
+
return budget > 0 ? Math.min(DIGEST_MAX_CHARS, budget) : null;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/** role:timestamp fingerprint of the message a watermark points at (the
|
|
272
|
+
digest boundary). A transcript mutated under the stored count (/tree,
|
|
273
|
+
/fork, per-call context-hook rewrites) changes the boundary message, so a
|
|
274
|
+
stored fingerprint that no longer match es invalidates the delta window
|
|
275
|
+
and the digest falls back to the full delta (the Codex WebSocket
|
|
276
|
+
continuation baseline-check pattern: verify before you trust a counter). */
|
|
277
|
+
export function boundaryFingerprint(m: Message | undefined): string | undefined {
|
|
278
|
+
return m ? `${m.role}:${m.timestamp}` : undefined;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/** Index of the most recent compaction summary in the transcript, -1 if none. */
|
|
282
|
+
export function findLastCompactionIdx(messages: Message[]): number {
|
|
283
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
284
|
+
const m = messages[i];
|
|
285
|
+
if (m.role !== "user") continue;
|
|
286
|
+
if (blocksToText(m.content).includes(COMPACTION_MARKER)) return i;
|
|
287
|
+
}
|
|
288
|
+
return -1;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/** Content identity of a compaction summary message (length + FNV-1a of the
|
|
292
|
+
stripped text). pi puts every post-compaction summary at the transcript
|
|
293
|
+
front, so index identity would swallow the second compaction; this id
|
|
294
|
+
ships a new summary exactly once. */
|
|
295
|
+
export function compactionFingerprint(m: Message): string {
|
|
296
|
+
const text = stripCompactionWrapping(blocksToText(m.content));
|
|
297
|
+
let hash = 0x811c9dc5;
|
|
298
|
+
for (let i = 0; i < text.length; i++) {
|
|
299
|
+
hash ^= text.charCodeAt(i);
|
|
300
|
+
hash = Math.imul(hash, 0x01000193);
|
|
301
|
+
}
|
|
302
|
+
return `${text.length}:${(hash >>> 0).toString(16)}`;
|
|
234
303
|
}
|
|
235
304
|
|
|
236
305
|
/** Build a delta digest of pi-side context agy was not spawned for: the most
|
|
237
|
-
* recent compaction summary plus turns since the watermark that
|
|
238
|
-
* produced by this provider. Pure: no I/O.
|
|
306
|
+
* recent undelivered compaction summary plus turns since the watermark that
|
|
307
|
+
* were not produced by this provider (in bound mode). Pure: no I/O.
|
|
308
|
+
* Exported for unit testing.
|
|
309
|
+
*
|
|
310
|
+
* Delta, not replay: in bound mode skip our own assistant turns
|
|
311
|
+
* (provider === ownProvider) - they are already in agy's resumed DB. In
|
|
312
|
+
* fresh mode (bound: false) the conversation holds nothing, so own turns
|
|
313
|
+
* ship too.
|
|
239
314
|
*
|
|
240
|
-
*
|
|
241
|
-
*
|
|
242
|
-
*
|
|
315
|
+
* Compaction-aware reset: a compaction can shrink the transcript below the
|
|
316
|
+
* stored watermark, which would empty the delta window and silently drop
|
|
317
|
+
* every post-compaction turn. The window instead restarts after the
|
|
318
|
+
* compaction, and the summary itself ships exactly once (tracked by
|
|
319
|
+
* seenSummaryId, content-keyed) to keep steady-state prompts byte-stable.
|
|
243
320
|
*
|
|
244
321
|
* Fidelity note: other-provider assistant turns contribute only their text
|
|
245
322
|
* blocks; tool-call and thinking blocks are dropped. The intent (which tool)
|
|
@@ -250,41 +327,46 @@ export function buildContextDigest(
|
|
|
250
327
|
opts: DigestOptions = {},
|
|
251
328
|
): string {
|
|
252
329
|
const own = opts.ownProvider ?? "antigravity";
|
|
253
|
-
const maxChars = opts.maxChars ??
|
|
330
|
+
const maxChars = opts.maxChars ?? DIGEST_MAX_CHARS;
|
|
254
331
|
if (messages.length === 0) return "";
|
|
255
332
|
|
|
256
|
-
let summaryPart: string | null = null;
|
|
257
333
|
const deltaParts: string[] = [];
|
|
258
334
|
|
|
259
|
-
// 1.
|
|
260
|
-
//
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
lastCompactionIdx = i;
|
|
268
|
-
summaryPart = `[pi compaction summary]\n${stripCompactionWrapping(t)}`;
|
|
269
|
-
break;
|
|
335
|
+
// 1. Compaction summary (never in agy's DB, so always high-value), but
|
|
336
|
+
// only when THIS summary has not shipped in a previous digest.
|
|
337
|
+
const compactionIdx = findLastCompactionIdx(messages);
|
|
338
|
+
let summaryPart: string | null = null;
|
|
339
|
+
if (compactionIdx >= 0) {
|
|
340
|
+
const summaryMessage = messages[compactionIdx];
|
|
341
|
+
if (compactionFingerprint(summaryMessage) !== opts.seenSummaryId) {
|
|
342
|
+
summaryPart = `[pi compaction summary]\n${stripCompactionWrapping(blocksToText(summaryMessage.content))}`;
|
|
270
343
|
}
|
|
271
344
|
}
|
|
272
345
|
|
|
273
|
-
// 2. Delta
|
|
274
|
-
//
|
|
346
|
+
// 2. Delta window. Two stale-watermark shapes both clamp to after the
|
|
347
|
+
// compaction: a watermark below it (pre-compaction history is dropped
|
|
348
|
+
// or summarized) and a watermark above the transcript (the compaction
|
|
349
|
+
// shrank the list under the stored count; without the clamp the window
|
|
350
|
+
// would be empty and every post-compaction turn silently dropped).
|
|
351
|
+
// Without a compaction, a watermark above the transcript (branch/prune
|
|
352
|
+
// without a marker) falls back to the full delta.
|
|
275
353
|
let start = Math.max(0, Math.floor(watermark));
|
|
276
|
-
if (
|
|
354
|
+
if (compactionIdx >= 0) {
|
|
355
|
+
if (start < compactionIdx + 1 || watermark > messages.length) start = compactionIdx + 1;
|
|
356
|
+
} else if (watermark > messages.length) {
|
|
357
|
+
start = 0;
|
|
358
|
+
}
|
|
277
359
|
const end = Math.max(0, messages.length - 1);
|
|
278
360
|
for (let i = start; i < end; i++) {
|
|
279
361
|
const m = messages[i];
|
|
280
362
|
if (m.role === "assistant") {
|
|
281
|
-
if (m.provider === own) continue; // our own turn: already in agy's DB
|
|
363
|
+
if (opts.bound !== false && m.provider === own) continue; // our own turn: already in agy's DB
|
|
282
364
|
const t = blocksToText(m.content).trim();
|
|
283
365
|
if (!t) continue;
|
|
284
366
|
deltaParts.push(`[assistant turn from ${m.provider}]\n${t}`);
|
|
285
367
|
} else if (m.role === "user") {
|
|
286
368
|
const t = blocksToText(m.content);
|
|
287
|
-
if (t.includes(COMPACTION_MARKER)) continue; //
|
|
369
|
+
if (t.includes(COMPACTION_MARKER)) continue; // delivered as the summary part
|
|
288
370
|
if (!t.trim()) continue;
|
|
289
371
|
deltaParts.push(`[earlier user message]\n${t}`);
|
|
290
372
|
} else if (m.role === "toolResult") {
|
|
@@ -295,13 +377,18 @@ export function buildContextDigest(
|
|
|
295
377
|
}
|
|
296
378
|
}
|
|
297
379
|
|
|
298
|
-
// Assemble. The compaction summary is
|
|
299
|
-
//
|
|
300
|
-
//
|
|
301
|
-
//
|
|
302
|
-
//
|
|
380
|
+
// Assemble. The compaction summary is clamped to the budget (head kept:
|
|
381
|
+
// a summary reads top-down, and an oversized one must not push a
|
|
382
|
+
// stream-json turn over the silent-drop cap). The DELTA is truncated from
|
|
383
|
+
// the newest end backward when over budget: recent context matters more
|
|
384
|
+
// for continuity than older detail, so drop the oldest delta first. If
|
|
385
|
+
// even the newest single item exceeds the budget, keep its tail slice.
|
|
303
386
|
const SEP = "\n\n";
|
|
304
387
|
const MARKER = "[truncated]";
|
|
388
|
+
if (summaryPart && maxChars > 0 && summaryPart.length > maxChars) {
|
|
389
|
+
const room = Math.max(0, maxChars - MARKER.length - 1);
|
|
390
|
+
summaryPart = `${summaryPart.slice(0, room)}\n${MARKER}`;
|
|
391
|
+
}
|
|
305
392
|
let delta = deltaParts.join(SEP);
|
|
306
393
|
if (maxChars > 0) {
|
|
307
394
|
const budget = Math.max(0, maxChars - (summaryPart ? summaryPart.length + SEP.length : 0));
|
|
@@ -345,7 +432,7 @@ function newAssistant(model: Model<Api>): AssistantMessage {
|
|
|
345
432
|
|
|
346
433
|
/** Session key: prefer pi's sessionId (stable per conversation), fall back to
|
|
347
434
|
* cwd so a single pi process still resumes correctly when sessionId is absent. */
|
|
348
|
-
function sessionKey(
|
|
435
|
+
export function sessionKey(
|
|
349
436
|
options: SimpleStreamOptions | undefined,
|
|
350
437
|
cwd: string,
|
|
351
438
|
engine: "stream-json" | "acp",
|
|
@@ -1347,6 +1434,13 @@ async function runTurnDriver(
|
|
|
1347
1434
|
const existing = store.get(key);
|
|
1348
1435
|
const messageCount = context.messages.length;
|
|
1349
1436
|
const config = loadConfig();
|
|
1437
|
+
// Settle bookkeeping shared by both store.set paths: the boundary
|
|
1438
|
+
// fingerprint validates next turn's delta window, and the compaction
|
|
1439
|
+
// index suppresses summary re-injection once this turn delivered it.
|
|
1440
|
+
const settleBoundary = boundaryFingerprint(context.messages[messageCount - 1]);
|
|
1441
|
+
// Summary id carried forward from the record; the gate below overwrites it
|
|
1442
|
+
// only when a digest actually ships, so skipped turns never lose it.
|
|
1443
|
+
let settleSummaryId = existing?.digestSummaryId;
|
|
1350
1444
|
|
|
1351
1445
|
// Continuation: resolve parked round-trips from pi's toolResult messages,
|
|
1352
1446
|
// then re-attach to the still-running agy turn. No new user event is sent:
|
|
@@ -1504,11 +1598,50 @@ async function runTurnDriver(
|
|
|
1504
1598
|
finalize(stream, blocks, "error", "No user message to send to agy.");
|
|
1505
1599
|
return;
|
|
1506
1600
|
}
|
|
1507
|
-
const
|
|
1601
|
+
const rawWatermark = existing?.lastMessageCount ?? 0;
|
|
1602
|
+
// Boundary fingerprint check (see boundaryFingerprint): a transcript
|
|
1603
|
+
// mutated under the stored count (/tree, /fork, context-hook rewrites)
|
|
1604
|
+
// resets the delta to the full digest instead of a silently wrong one.
|
|
1605
|
+
// Records written before the fingerprint existed (digestBoundary unset)
|
|
1606
|
+
// trust the count: the old code advanced it the same way, so reseting
|
|
1607
|
+
// would dump a one-time full delta of history agy already holds.
|
|
1608
|
+
const storedBoundary = existing?.digestBoundary;
|
|
1609
|
+
const watermark =
|
|
1610
|
+
rawWatermark > 0 &&
|
|
1611
|
+
(storedBoundary === undefined ||
|
|
1612
|
+
storedBoundary === boundaryFingerprint(context.messages[rawWatermark - 1]))
|
|
1613
|
+
? rawWatermark
|
|
1614
|
+
: 0;
|
|
1508
1615
|
// Late and resume turns re-open the conversation with a synthetic
|
|
1509
1616
|
// prompt; the digest would re-send context agy already holds (against a
|
|
1510
1617
|
// stale watermark: a failed pass never advances it), so skip it.
|
|
1511
|
-
const
|
|
1618
|
+
const engine = deps.engine ?? config.engine;
|
|
1619
|
+
const promptBytes = Buffer.byteLength(prompt ?? "", "utf8");
|
|
1620
|
+
const maxChars = digestMaxCharsForEngine(engine, promptBytes);
|
|
1621
|
+
const digest =
|
|
1622
|
+
config.digest && maxChars !== null && late.length === 0 && !resume
|
|
1623
|
+
? buildContextDigest(context.messages, watermark, {
|
|
1624
|
+
bound: Boolean(existing?.conversationId),
|
|
1625
|
+
seenSummaryId: existing?.digestSummaryId,
|
|
1626
|
+
maxChars,
|
|
1627
|
+
})
|
|
1628
|
+
: "";
|
|
1629
|
+
// Byte-level fail closed (issue #2): the char budget over-reserves for
|
|
1630
|
+
// ASCII but a multibyte digest can still exceed the remaining byte
|
|
1631
|
+
// room. ACP carries no prompt cap, so the check is stream-json only.
|
|
1632
|
+
const digestFinal =
|
|
1633
|
+
digest &&
|
|
1634
|
+
engine !== "acp" &&
|
|
1635
|
+
promptBytes + STREAM_JSON_PROMPT_MARGIN + Buffer.byteLength(digest, "utf8") > STREAM_JSON_PROMPT_CAP
|
|
1636
|
+
? ""
|
|
1637
|
+
: digest;
|
|
1638
|
+
// The delivered summary id persists only when a digest actually shipped:
|
|
1639
|
+
// late/resume/budget-skipped turns carry the previous id forward so the
|
|
1640
|
+
// summary is not lost to a turn that never delivered it.
|
|
1641
|
+
if (digestFinal) {
|
|
1642
|
+
const deliveredIdx = findLastCompactionIdx(context.messages);
|
|
1643
|
+
settleSummaryId = deliveredIdx >= 0 ? compactionFingerprint(context.messages[deliveredIdx]) : undefined;
|
|
1644
|
+
}
|
|
1512
1645
|
// G1 delivery per engine. stream-json: digest rides inline in the prompt
|
|
1513
1646
|
// (the CLI has no context channel). ACP: the server advertises
|
|
1514
1647
|
// `embeddedContext`, so the digest ships as a native resource block
|
|
@@ -1517,7 +1650,7 @@ async function runTurnDriver(
|
|
|
1517
1650
|
// surface, and the model needs the use-for-continuity-only instruction.
|
|
1518
1651
|
// The uri is suffixed per turn so a deduping server cannot serve stale
|
|
1519
1652
|
// content on turn 2+.
|
|
1520
|
-
const embeddedDigest = deps.engine === "acp" &&
|
|
1653
|
+
const embeddedDigest = deps.engine === "acp" && digestFinal ? digestFinal : undefined;
|
|
1521
1654
|
// G10, fresh conversations only (bound conversations ride agy's own
|
|
1522
1655
|
// history; re-sending would bloat every prompt and bust the cache).
|
|
1523
1656
|
// stream-json delivery is a staged agent file, NOT prompt text: agy's
|
|
@@ -1563,7 +1696,7 @@ async function runTurnDriver(
|
|
|
1563
1696
|
const fullPrompt =
|
|
1564
1697
|
(late.length > 0
|
|
1565
1698
|
? buildLateResultPrompt(late, prompt || undefined)
|
|
1566
|
-
: buildFullPrompt(sysPrompt, embeddedDigest ? "" :
|
|
1699
|
+
: buildFullPrompt(sysPrompt, embeddedDigest ? "" : digestFinal, prompt ?? "")) +
|
|
1567
1700
|
stageImageNote(runImages);
|
|
1568
1701
|
try {
|
|
1569
1702
|
handle = await deps.driver.run({
|
|
@@ -1605,6 +1738,8 @@ async function runTurnDriver(
|
|
|
1605
1738
|
// the cumulative task dir never re-reports older turns' logs.
|
|
1606
1739
|
const turnStartMs = Date.now();
|
|
1607
1740
|
let nativeBackgroundSeen = false;
|
|
1741
|
+
// Issue #16 guard: quota reclassification applies to text-only turns only.
|
|
1742
|
+
let sawToolOrThought = false;
|
|
1608
1743
|
const feats: ActivityFeatures = {
|
|
1609
1744
|
replay: deps.replay,
|
|
1610
1745
|
nativeActive: deps.nativeActive,
|
|
@@ -1622,6 +1757,7 @@ async function runTurnDriver(
|
|
|
1622
1757
|
for (;;) {
|
|
1623
1758
|
const activity = await h.next();
|
|
1624
1759
|
if (!activity) break;
|
|
1760
|
+
if (activity.type !== "text" && activity.type !== "usage") sawToolOrThought = true;
|
|
1625
1761
|
if (consumeActivity(stream, blocks, activity, diffCtx, cwd, feats) === "parked") return "parked";
|
|
1626
1762
|
}
|
|
1627
1763
|
};
|
|
@@ -1637,7 +1773,13 @@ async function runTurnDriver(
|
|
|
1637
1773
|
if (!existing) {
|
|
1638
1774
|
const parkedConv = deps.driver.snapshot().conversationId;
|
|
1639
1775
|
if (parkedConv) {
|
|
1640
|
-
store.set(key, {
|
|
1776
|
+
store.set(key, {
|
|
1777
|
+
conversationId: parkedConv,
|
|
1778
|
+
lastStepIdx: -1,
|
|
1779
|
+
lastMessageCount: messageCount,
|
|
1780
|
+
digestBoundary: settleBoundary,
|
|
1781
|
+
digestSummaryId: settleSummaryId,
|
|
1782
|
+
});
|
|
1641
1783
|
if (stagedAgentName) stagedAgentByConversation.set(parkedConv, stagedAgentName);
|
|
1642
1784
|
}
|
|
1643
1785
|
}
|
|
@@ -1693,6 +1835,18 @@ async function runTurnDriver(
|
|
|
1693
1835
|
);
|
|
1694
1836
|
return;
|
|
1695
1837
|
}
|
|
1838
|
+
// Issue #16: agy streams the account quota notice as agent text and ends
|
|
1839
|
+
// the turn OK; settle it as a retryable error so provider failover fires.
|
|
1840
|
+
// Text-only turns only, and the binding is untouched below: the
|
|
1841
|
+
// conversation itself is healthy, unlike the silentDrop signature above.
|
|
1842
|
+
if (outcome.status === "OK" && !outcome.aborted && !sawToolOrThought) {
|
|
1843
|
+
const quota = detectQuotaNotice(outcome.response);
|
|
1844
|
+
if (quota) {
|
|
1845
|
+
deps.log?.("turn-error", { reason: "quota-exhausted", resetsIn: quota.resetsIn ?? null }, "error");
|
|
1846
|
+
finalize(stream, blocks, "error", quotaErrorMessage(quota));
|
|
1847
|
+
return;
|
|
1848
|
+
}
|
|
1849
|
+
}
|
|
1696
1850
|
// Gap closer: the result landed while the turn was still live (reentry
|
|
1697
1851
|
// above), the turn ended, and the model never polled. Same strand, same
|
|
1698
1852
|
// fix: sweep and deliver as a late run in the same conversation. Single
|
|
@@ -1749,6 +1903,8 @@ async function runTurnDriver(
|
|
|
1749
1903
|
conversationId: outcome.conversationId,
|
|
1750
1904
|
lastStepIdx: -1,
|
|
1751
1905
|
lastMessageCount: messageCount,
|
|
1906
|
+
digestBoundary: settleBoundary,
|
|
1907
|
+
digestSummaryId: settleSummaryId,
|
|
1752
1908
|
});
|
|
1753
1909
|
if (stagedAgentName) stagedAgentByConversation.set(outcome.conversationId, stagedAgentName);
|
|
1754
1910
|
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
// Quota-exhaustion notice detection (issue #16). agy streams the account's
|
|
2
|
+
// quota notice as plain agent text and ends the turn with end_turn, so the
|
|
3
|
+
// provider reclassifies the settled response into a pi error instead of a
|
|
4
|
+
// successful reply.
|
|
5
|
+
//
|
|
6
|
+
// The pi-side errorMessage wording is load-bearing: pi-ai's
|
|
7
|
+
// isRetryableAssistantError gates provider failover and classifies
|
|
8
|
+
// "quota exceeded" / "billing" wording as fail-fast (no router handoff), so
|
|
9
|
+
// the message must carry a retryable marker ("rate limit") while staying
|
|
10
|
+
// clear of every non-retryable pattern. The raw upstream notice is never
|
|
11
|
+
// echoed, so upstream copy drift cannot poison the classification.
|
|
12
|
+
|
|
13
|
+
/** Reset interval parsed from the notice, e.g. "153h38m14s". */
|
|
14
|
+
export interface QuotaNotice {
|
|
15
|
+
resetsIn?: string;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// Anchored at the start and length-capped so only a notice-shaped
|
|
19
|
+
// (near-)whole response reclassifies; a long answer that merely discusses
|
|
20
|
+
// quota must never match.
|
|
21
|
+
const NOTICE_PATTERN = /^\s*(?:⚠\s*)?(?:[a-z]+\s+)?quota\s+(?:reached|exhausted|exceeded|limit reached)/i;
|
|
22
|
+
const RESET_PATTERN = /resets?\s+in\s+((?:\d+h)?(?:\d+m)?(?:\d+s))/i;
|
|
23
|
+
const NOTICE_MAX_CHARS = 400;
|
|
24
|
+
|
|
25
|
+
/** Classify a settled driver response as a quota-exhaustion notice.
|
|
26
|
+
* Conservative by design: false negatives keep a normal reply, false
|
|
27
|
+
* positives would turn real answers into errors. */
|
|
28
|
+
export function detectQuotaNotice(response: string): QuotaNotice | undefined {
|
|
29
|
+
const trimmed = response.trim();
|
|
30
|
+
if (trimmed.length === 0 || trimmed.length > NOTICE_MAX_CHARS) return undefined;
|
|
31
|
+
if (!NOTICE_PATTERN.test(trimmed)) return undefined;
|
|
32
|
+
const resetsIn = RESET_PATTERN.exec(trimmed)?.[1];
|
|
33
|
+
return resetsIn ? { resetsIn } : {};
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Retryable-classified pi errorMessage for a detected notice. */
|
|
37
|
+
export function quotaErrorMessage(notice: QuotaNotice): string {
|
|
38
|
+
const reset = notice.resetsIn ? `; resets in ${notice.resetsIn}` : "";
|
|
39
|
+
return `agy rate limit (ResourceExhausted): Antigravity quota exhausted${reset}`;
|
|
40
|
+
}
|
package/src/sessions.ts
CHANGED
|
@@ -29,6 +29,16 @@ export interface AgySession {
|
|
|
29
29
|
* fresh or pre-watermark session. Optional for backward compat with older
|
|
30
30
|
* persisted sessions that predate the watermark. */
|
|
31
31
|
lastMessageCount?: number;
|
|
32
|
+
/** role:timestamp fingerprint of messages[lastMessageCount - 1] at write
|
|
33
|
+
* time. The provider compares it against the live boundary message: a
|
|
34
|
+
* mismatch (branch, fork, context-hook rewrite) resets the digest window
|
|
35
|
+
* to the full delta. Optional: absent on records predating the
|
|
36
|
+
* fingerprint, which the provider treats as a mismatch. */
|
|
37
|
+
digestBoundary?: string;
|
|
38
|
+
/** Compaction index already delivered in a previous digest, so the
|
|
39
|
+
* builder neither re-injects that summary nor restarts its window on
|
|
40
|
+
* it. Optional/absent when no compaction existed at write time. */
|
|
41
|
+
digestSummaryId?: string;
|
|
32
42
|
}
|
|
33
43
|
|
|
34
44
|
type StoreMap = Record<string, AgySession>;
|
|
@@ -48,10 +58,14 @@ function narrowStoreMap(parsed: unknown): StoreMap {
|
|
|
48
58
|
if (typeof conversationId !== "string") continue;
|
|
49
59
|
const idx = (value as { lastStepIdx?: unknown }).lastStepIdx;
|
|
50
60
|
const mc = (value as { lastMessageCount?: unknown }).lastMessageCount;
|
|
61
|
+
const db = (value as { digestBoundary?: unknown }).digestBoundary;
|
|
62
|
+
const dci = (value as { digestSummaryId?: unknown }).digestSummaryId;
|
|
51
63
|
clean[key] = {
|
|
52
64
|
conversationId,
|
|
53
65
|
lastStepIdx: typeof idx === "number" && Number.isFinite(idx) ? idx : -1,
|
|
54
66
|
lastMessageCount: typeof mc === "number" && Number.isFinite(mc) ? mc : 0,
|
|
67
|
+
...(typeof db === "string" ? { digestBoundary: db } : {}),
|
|
68
|
+
...(typeof dci === "string" ? { digestSummaryId: dci } : {}),
|
|
55
69
|
};
|
|
56
70
|
}
|
|
57
71
|
return clean;
|
|
@@ -93,6 +107,8 @@ export class SessionStore {
|
|
|
93
107
|
conversationId: s.conversationId,
|
|
94
108
|
lastStepIdx: s.lastStepIdx ?? -1,
|
|
95
109
|
lastMessageCount: s.lastMessageCount ?? 0,
|
|
110
|
+
...(s.digestBoundary !== undefined ? { digestBoundary: s.digestBoundary } : {}),
|
|
111
|
+
...(s.digestSummaryId !== undefined ? { digestSummaryId: s.digestSummaryId } : {}),
|
|
96
112
|
};
|
|
97
113
|
}
|
|
98
114
|
|