@estebanforge/pi-antigravity-bridge 1.10.9 → 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 +10 -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 +174 -34
- package/src/sessions.ts +16 -0
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,16 @@
|
|
|
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
|
+
|
|
5
15
|
## [1.10.9] - 2026-11-17
|
|
6
16
|
|
|
7
17
|
### Fixed
|
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
|
@@ -232,15 +232,91 @@ export interface DigestOptions {
|
|
|
232
232
|
ownProvider?: string;
|
|
233
233
|
/** Soft cap on the digest body (0 = unbounded). Default 8000. */
|
|
234
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)}`;
|
|
235
303
|
}
|
|
236
304
|
|
|
237
305
|
/** Build a delta digest of pi-side context agy was not spawned for: the most
|
|
238
|
-
* recent compaction summary plus turns since the watermark that
|
|
239
|
-
* 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.
|
|
240
314
|
*
|
|
241
|
-
*
|
|
242
|
-
*
|
|
243
|
-
*
|
|
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.
|
|
244
320
|
*
|
|
245
321
|
* Fidelity note: other-provider assistant turns contribute only their text
|
|
246
322
|
* blocks; tool-call and thinking blocks are dropped. The intent (which tool)
|
|
@@ -251,41 +327,46 @@ export function buildContextDigest(
|
|
|
251
327
|
opts: DigestOptions = {},
|
|
252
328
|
): string {
|
|
253
329
|
const own = opts.ownProvider ?? "antigravity";
|
|
254
|
-
const maxChars = opts.maxChars ??
|
|
330
|
+
const maxChars = opts.maxChars ?? DIGEST_MAX_CHARS;
|
|
255
331
|
if (messages.length === 0) return "";
|
|
256
332
|
|
|
257
|
-
let summaryPart: string | null = null;
|
|
258
333
|
const deltaParts: string[] = [];
|
|
259
334
|
|
|
260
|
-
// 1.
|
|
261
|
-
//
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
lastCompactionIdx = i;
|
|
269
|
-
summaryPart = `[pi compaction summary]\n${stripCompactionWrapping(t)}`;
|
|
270
|
-
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))}`;
|
|
271
343
|
}
|
|
272
344
|
}
|
|
273
345
|
|
|
274
|
-
// 2. Delta
|
|
275
|
-
//
|
|
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.
|
|
276
353
|
let start = Math.max(0, Math.floor(watermark));
|
|
277
|
-
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
|
+
}
|
|
278
359
|
const end = Math.max(0, messages.length - 1);
|
|
279
360
|
for (let i = start; i < end; i++) {
|
|
280
361
|
const m = messages[i];
|
|
281
362
|
if (m.role === "assistant") {
|
|
282
|
-
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
|
|
283
364
|
const t = blocksToText(m.content).trim();
|
|
284
365
|
if (!t) continue;
|
|
285
366
|
deltaParts.push(`[assistant turn from ${m.provider}]\n${t}`);
|
|
286
367
|
} else if (m.role === "user") {
|
|
287
368
|
const t = blocksToText(m.content);
|
|
288
|
-
if (t.includes(COMPACTION_MARKER)) continue; //
|
|
369
|
+
if (t.includes(COMPACTION_MARKER)) continue; // delivered as the summary part
|
|
289
370
|
if (!t.trim()) continue;
|
|
290
371
|
deltaParts.push(`[earlier user message]\n${t}`);
|
|
291
372
|
} else if (m.role === "toolResult") {
|
|
@@ -296,13 +377,18 @@ export function buildContextDigest(
|
|
|
296
377
|
}
|
|
297
378
|
}
|
|
298
379
|
|
|
299
|
-
// Assemble. The compaction summary is
|
|
300
|
-
//
|
|
301
|
-
//
|
|
302
|
-
//
|
|
303
|
-
//
|
|
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.
|
|
304
386
|
const SEP = "\n\n";
|
|
305
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
|
+
}
|
|
306
392
|
let delta = deltaParts.join(SEP);
|
|
307
393
|
if (maxChars > 0) {
|
|
308
394
|
const budget = Math.max(0, maxChars - (summaryPart ? summaryPart.length + SEP.length : 0));
|
|
@@ -346,7 +432,7 @@ function newAssistant(model: Model<Api>): AssistantMessage {
|
|
|
346
432
|
|
|
347
433
|
/** Session key: prefer pi's sessionId (stable per conversation), fall back to
|
|
348
434
|
* cwd so a single pi process still resumes correctly when sessionId is absent. */
|
|
349
|
-
function sessionKey(
|
|
435
|
+
export function sessionKey(
|
|
350
436
|
options: SimpleStreamOptions | undefined,
|
|
351
437
|
cwd: string,
|
|
352
438
|
engine: "stream-json" | "acp",
|
|
@@ -1348,6 +1434,13 @@ async function runTurnDriver(
|
|
|
1348
1434
|
const existing = store.get(key);
|
|
1349
1435
|
const messageCount = context.messages.length;
|
|
1350
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;
|
|
1351
1444
|
|
|
1352
1445
|
// Continuation: resolve parked round-trips from pi's toolResult messages,
|
|
1353
1446
|
// then re-attach to the still-running agy turn. No new user event is sent:
|
|
@@ -1505,11 +1598,50 @@ async function runTurnDriver(
|
|
|
1505
1598
|
finalize(stream, blocks, "error", "No user message to send to agy.");
|
|
1506
1599
|
return;
|
|
1507
1600
|
}
|
|
1508
|
-
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;
|
|
1509
1615
|
// Late and resume turns re-open the conversation with a synthetic
|
|
1510
1616
|
// prompt; the digest would re-send context agy already holds (against a
|
|
1511
1617
|
// stale watermark: a failed pass never advances it), so skip it.
|
|
1512
|
-
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
|
+
}
|
|
1513
1645
|
// G1 delivery per engine. stream-json: digest rides inline in the prompt
|
|
1514
1646
|
// (the CLI has no context channel). ACP: the server advertises
|
|
1515
1647
|
// `embeddedContext`, so the digest ships as a native resource block
|
|
@@ -1518,7 +1650,7 @@ async function runTurnDriver(
|
|
|
1518
1650
|
// surface, and the model needs the use-for-continuity-only instruction.
|
|
1519
1651
|
// The uri is suffixed per turn so a deduping server cannot serve stale
|
|
1520
1652
|
// content on turn 2+.
|
|
1521
|
-
const embeddedDigest = deps.engine === "acp" &&
|
|
1653
|
+
const embeddedDigest = deps.engine === "acp" && digestFinal ? digestFinal : undefined;
|
|
1522
1654
|
// G10, fresh conversations only (bound conversations ride agy's own
|
|
1523
1655
|
// history; re-sending would bloat every prompt and bust the cache).
|
|
1524
1656
|
// stream-json delivery is a staged agent file, NOT prompt text: agy's
|
|
@@ -1564,7 +1696,7 @@ async function runTurnDriver(
|
|
|
1564
1696
|
const fullPrompt =
|
|
1565
1697
|
(late.length > 0
|
|
1566
1698
|
? buildLateResultPrompt(late, prompt || undefined)
|
|
1567
|
-
: buildFullPrompt(sysPrompt, embeddedDigest ? "" :
|
|
1699
|
+
: buildFullPrompt(sysPrompt, embeddedDigest ? "" : digestFinal, prompt ?? "")) +
|
|
1568
1700
|
stageImageNote(runImages);
|
|
1569
1701
|
try {
|
|
1570
1702
|
handle = await deps.driver.run({
|
|
@@ -1641,7 +1773,13 @@ async function runTurnDriver(
|
|
|
1641
1773
|
if (!existing) {
|
|
1642
1774
|
const parkedConv = deps.driver.snapshot().conversationId;
|
|
1643
1775
|
if (parkedConv) {
|
|
1644
|
-
store.set(key, {
|
|
1776
|
+
store.set(key, {
|
|
1777
|
+
conversationId: parkedConv,
|
|
1778
|
+
lastStepIdx: -1,
|
|
1779
|
+
lastMessageCount: messageCount,
|
|
1780
|
+
digestBoundary: settleBoundary,
|
|
1781
|
+
digestSummaryId: settleSummaryId,
|
|
1782
|
+
});
|
|
1645
1783
|
if (stagedAgentName) stagedAgentByConversation.set(parkedConv, stagedAgentName);
|
|
1646
1784
|
}
|
|
1647
1785
|
}
|
|
@@ -1765,6 +1903,8 @@ async function runTurnDriver(
|
|
|
1765
1903
|
conversationId: outcome.conversationId,
|
|
1766
1904
|
lastStepIdx: -1,
|
|
1767
1905
|
lastMessageCount: messageCount,
|
|
1906
|
+
digestBoundary: settleBoundary,
|
|
1907
|
+
digestSummaryId: settleSummaryId,
|
|
1768
1908
|
});
|
|
1769
1909
|
if (stagedAgentName) stagedAgentByConversation.set(outcome.conversationId, stagedAgentName);
|
|
1770
1910
|
}
|
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
|
|