@estebanforge/pi-antigravity-bridge 1.12.1 → 1.13.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 +8 -0
- package/extensions/index.ts +27 -2
- package/package.json +1 -1
- package/src/provider.ts +106 -21
- package/src/stream-events.ts +39 -0
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,14 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to this project will be documented in this file.
|
|
4
4
|
|
|
5
|
+
## [1.13.0] - 2026-11-19
|
|
6
|
+
|
|
7
|
+
### Fixed
|
|
8
|
+
|
|
9
|
+
- **Multi-step agy turns no longer trip a phantom pi-side compaction (issue #20).** pi-ai's `isContextOverflow` judges overflow by `usage.input + usage.cacheRead` alone (Case 2, `stopReason "stop"`), while the ACP driver keeps those two as cumulative billing sums over every inference of the prompt (issue #12's finding: only `total_tokens` was corrected). A long tool-loop turn therefore satisfied the overflow check on a healthy conversation and pi silently compacted. The provider now clamps the emitted usage (`clampOverflowUsage`): when the corrected occupancy (`totalTokens`) fits the context window but the billing sums do not, `input`/`cacheRead` are proportionally rescaled into the single-turn budget with the cache-hit ratio preserved; genuine overflows, normal turns, and the driver's raw billing fields are untouched. pi's usage ledger slightly understates input/cacheRead on clamped turns (on stream-json with no `total_tokens` the clamp shrinks cacheRead in the ledger so the window arithmetic stays consistent); cost stays exact at zero (subscription quota).
|
|
10
|
+
- **pi's ephemeral helper calls no longer touch the session store (issue #20).** Compaction/summarization calls arrive with `cacheRetention: "none"` and a synthetic `uuidv7` sessionId, and replay-style callers can arrive with `disableContinuation` plus the LIVE session id - both previously ran the full binding path: reading the live record, overwriting its watermark, binding the synthetic id, claiming dead/stranded tool results, and arming the background watcher. Both shapes now classify as ephemeral: a fresh agy conversation, zero store reads/writes/deletes, no late-result or stranded claiming, no background arming. Each ephemeral call starts its own never-reclaimed agy conversation; the cache warmer never starts for agy models today (no `promptCache`), so the `disableContinuation` half is defensive for future replay callers.
|
|
11
|
+
- **`session_compact` now rotates the agy conversation binding (issue #20).** A pi compaction previously left the stale binding, so the next turn resumed an old conversation that had never seen the summary. `rotateSessionOnCompaction` deletes the binding on `session_compact` (also cleared on `session_shutdown` and `/agy clear`) and arms a one-shot `pendingCompactionHandoff` latch that survives failed retries (even with the digest disabled) and is consumed by the next successful bind. A turn whose transcript ends in a toolResult or assistant message with no user prompt then seeds a fresh conversation with the compaction summary (`buildContextDigest` with `bound: false, includeLast: true` plus `COMPACTION_RESUME_PROMPT`) instead of failing with the unretryable "No user message to send to agy." error; non-compaction unbound tails keep the old hard error. Known limits, deliberate: the latch is memory-only (after a restart with the digest off, a user-prompt-tailed session starts fresh without the summary - the tail rescue still applies); rotation is unconditional on the active model, so a compaction fired on another provider also rotates the agy binding and the conversation rebuilds from the digest on return; and a `session_compact` landing while a bridge call is parked keeps the rotation - passes that would bind a PRE-ROTATION conversation (parked continuations and strand redeliveries into the old conversation id) decline to rebind and leave the handoff for the next pass.
|
|
12
|
+
|
|
5
13
|
## [1.12.1] - 2026-11-19
|
|
6
14
|
|
|
7
15
|
### Fixed
|
package/extensions/index.ts
CHANGED
|
@@ -46,6 +46,7 @@ import {
|
|
|
46
46
|
defaultEscalateAfterMs,
|
|
47
47
|
formatEscalatedAck,
|
|
48
48
|
formatPollAnswer,
|
|
49
|
+
rotateSessionOnCompaction,
|
|
49
50
|
sessionKey,
|
|
50
51
|
type NativeDisplayEvent,
|
|
51
52
|
} from "../src/provider.js";
|
|
@@ -603,10 +604,30 @@ export default async function (pi: ExtensionAPI): Promise<void> {
|
|
|
603
604
|
fileLog.log("background-watch-sweep-error", { error: err instanceof Error ? err.message : String(err) }, "warn");
|
|
604
605
|
}
|
|
605
606
|
});
|
|
607
|
+
// Session keys whose bound agy conversation was rotated on session_compact
|
|
608
|
+
// so the next turn starts a fresh backend conversation and ships the
|
|
609
|
+
// compaction summary once (even when config.digest is disabled).
|
|
610
|
+
const pendingCompactionHandoff = new Set<string>();
|
|
606
611
|
pi.on("session_shutdown", () => {
|
|
607
612
|
backgroundWatchDisposed = true;
|
|
608
613
|
for (const handle of backgroundWatchers.values()) handle.stop();
|
|
609
614
|
backgroundWatchers.clear();
|
|
615
|
+
pendingCompactionHandoff.clear();
|
|
616
|
+
});
|
|
617
|
+
pi.on("session_compact", (_event, ctx) => {
|
|
618
|
+
try {
|
|
619
|
+
// Shape-cast as in model_select below: tolerate pi builds whose dts
|
|
620
|
+
// omits getSessionId.
|
|
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
|
+
const rotated = rotateSessionOnCompaction(store, key, pendingCompactionHandoff);
|
|
625
|
+
if (rotated) {
|
|
626
|
+
fileLog.log("session-compact-rotate", { key, previousConversation: rotated }, "info");
|
|
627
|
+
}
|
|
628
|
+
} catch (err) {
|
|
629
|
+
fileLog.log("session-compact-rotate-error", { error: err instanceof Error ? err.message : String(err) }, "warn");
|
|
630
|
+
}
|
|
610
631
|
});
|
|
611
632
|
// Model-switch handoff toast: entering an unbound antigravity model
|
|
612
633
|
// mid-session opens a fresh agy conversation on the next turn; the
|
|
@@ -618,8 +639,8 @@ export default async function (pi: ExtensionAPI): Promise<void> {
|
|
|
618
639
|
digestEnabled: loadConfig().digest,
|
|
619
640
|
source: event.source,
|
|
620
641
|
bound: (() => {
|
|
621
|
-
//
|
|
622
|
-
//
|
|
642
|
+
// Shape-cast as in the session_compact handler above: tolerate pi
|
|
643
|
+
// builds whose dts omits getSessionId.
|
|
623
644
|
const sm = ctx.sessionManager as { getSessionId?: () => string };
|
|
624
645
|
const sid = sm.getSessionId?.();
|
|
625
646
|
const key = sessionKey(sid ? { sessionId: sid } : undefined, ctx.cwd, engine);
|
|
@@ -645,6 +666,7 @@ export default async function (pi: ExtensionAPI): Promise<void> {
|
|
|
645
666
|
onNativeEvent,
|
|
646
667
|
onNativeBackground: (info) => armConversationWatcher(info.conversationId, info.turnStartMs),
|
|
647
668
|
roster,
|
|
669
|
+
pendingCompactionHandoff,
|
|
648
670
|
engine,
|
|
649
671
|
log: fileLog.log.bind(fileLog),
|
|
650
672
|
});
|
|
@@ -681,6 +703,7 @@ export default async function (pi: ExtensionAPI): Promise<void> {
|
|
|
681
703
|
hiddenBridgeTools,
|
|
682
704
|
fileLog,
|
|
683
705
|
roster,
|
|
706
|
+
pendingCompactionHandoff,
|
|
684
707
|
checkAgySetup,
|
|
685
708
|
});
|
|
686
709
|
|
|
@@ -1216,6 +1239,7 @@ interface AgyCommandCtx {
|
|
|
1216
1239
|
fileLog: DailyLogger;
|
|
1217
1240
|
/** Live subagent roster (folded in the provider); /agy subagents. */
|
|
1218
1241
|
roster: SubagentRoster;
|
|
1242
|
+
pendingCompactionHandoff: Set<string>;
|
|
1219
1243
|
checkAgySetup: (ctx: { ui: ExtensionUIContext; mode: string }, engine: Engine, explicit?: boolean) => Promise<void>;
|
|
1220
1244
|
}
|
|
1221
1245
|
|
|
@@ -1290,6 +1314,7 @@ function registerAgyCommand(pi: ExtensionAPI, ctx: AgyCommandCtx): void {
|
|
|
1290
1314
|
// Direct subcommands work everywhere (headless + TUI).
|
|
1291
1315
|
if (sub === "clear") {
|
|
1292
1316
|
ctx.store.clear();
|
|
1317
|
+
ctx.pendingCompactionHandoff.clear();
|
|
1293
1318
|
ui?.notify("Cleared all antigravity session bindings.", "info");
|
|
1294
1319
|
return;
|
|
1295
1320
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@estebanforge/pi-antigravity-bridge",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.13.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/provider.ts
CHANGED
|
@@ -36,7 +36,7 @@ import type { Api } from "@earendil-works/pi-ai";
|
|
|
36
36
|
import type { DriverActivity, TurnDriver, TurnHandle } from "./driver-types.js";
|
|
37
37
|
import { looksBackgroundNativeCall } from "./background-watch.js";
|
|
38
38
|
import { SubagentRoster } from "./subagent-roster.js";
|
|
39
|
-
import { toPiUsage } from "./stream-events.js";
|
|
39
|
+
import { clampOverflowUsage, 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";
|
|
@@ -151,6 +151,12 @@ const COMPACTION_MARKER = "compacted into the following summary";
|
|
|
151
151
|
export const RESUME_PROMPT =
|
|
152
152
|
"[The previous attempt of this turn failed and was discarded. Check your conversation history for the last step you completed, then continue the task from there. Do not repeat completed actions.]";
|
|
153
153
|
|
|
154
|
+
/** Synthetic prompt for resuming into a fresh agy conversation right after pi
|
|
155
|
+
* compacts mid-tool-loop (transcript ends in a toolResult or assistant
|
|
156
|
+
* message after the bound conversation was rotated on session_compact). */
|
|
157
|
+
export const COMPACTION_RESUME_PROMPT =
|
|
158
|
+
"[The conversation was compacted into a summary and moved to a fresh Antigravity session. Continue the task from the compaction summary and any recent context above without repeating completed actions.]";
|
|
159
|
+
|
|
154
160
|
export const DIGEST_PREAMBLE =
|
|
155
161
|
"[The following is context from the broader pi session that this Antigravity turn was not directly spawned for: compaction summaries and turns handled by other providers or pi's own tools. Your own prior turns are already in your conversation history. Use this for continuity only.]";
|
|
156
162
|
|
|
@@ -244,6 +250,11 @@ export interface DigestOptions {
|
|
|
244
250
|
* the front, so every compaction lands at the same index; content
|
|
245
251
|
* identity ships a NEW summary exactly once. */
|
|
246
252
|
seenSummaryId?: string;
|
|
253
|
+
/** Include the trailing message in the delta window instead of reserving
|
|
254
|
+
* it as the current user prompt. Used when resuming into a fresh
|
|
255
|
+
* post-compaction conversation whose transcript ends in a toolResult or
|
|
256
|
+
* assistant message. Default false. */
|
|
257
|
+
includeLast?: boolean;
|
|
247
258
|
}
|
|
248
259
|
|
|
249
260
|
/** Soft cap on the digest body when no tighter budget applies. */
|
|
@@ -356,7 +367,7 @@ export function buildContextDigest(
|
|
|
356
367
|
} else if (watermark > messages.length) {
|
|
357
368
|
start = 0;
|
|
358
369
|
}
|
|
359
|
-
const end = Math.max(0, messages.length - 1);
|
|
370
|
+
const end = opts.includeLast ? messages.length : Math.max(0, messages.length - 1);
|
|
360
371
|
for (let i = start; i < end; i++) {
|
|
361
372
|
const m = messages[i];
|
|
362
373
|
if (m.role === "assistant") {
|
|
@@ -445,6 +456,25 @@ export function sessionKey(
|
|
|
445
456
|
return base + (engine === "acp" ? "@acp" : "");
|
|
446
457
|
}
|
|
447
458
|
|
|
459
|
+
/** Rotate the bound agy conversation after pi compacts the session.
|
|
460
|
+
* Deleting the binding forces the next turn onto a fresh agy conversation so
|
|
461
|
+
* server-side context is freed alongside pi's transcript; recording the key
|
|
462
|
+
* in `pendingCompactionHandoff` guarantees a one-shot compaction handoff even
|
|
463
|
+
* when `config.digest` is disabled. Returns the rotated conversation id, or
|
|
464
|
+
* null when the session had no binding. */
|
|
465
|
+
export function rotateSessionOnCompaction(
|
|
466
|
+
store: SessionStore,
|
|
467
|
+
key: string,
|
|
468
|
+
pendingCompactionHandoff?: Set<string>,
|
|
469
|
+
): string | null {
|
|
470
|
+
const existing = store.get(key);
|
|
471
|
+
if (!existing) return null;
|
|
472
|
+
store.delete(key);
|
|
473
|
+
stagedAgentByConversation.delete(existing.conversationId);
|
|
474
|
+
pendingCompactionHandoff?.add(key);
|
|
475
|
+
return existing.conversationId;
|
|
476
|
+
}
|
|
477
|
+
|
|
448
478
|
/** Track which content block is currently open so we close-on-switch.
|
|
449
479
|
* At most one of textIdx / thinkingIdx is non-null at a time. */
|
|
450
480
|
export interface BlockState {
|
|
@@ -497,6 +527,9 @@ export interface StreamSimpleDeps {
|
|
|
497
527
|
onNativeBackground?: (info: { conversationId: string; turnStartMs: number }) => void;
|
|
498
528
|
/** Subagent roster (both engines); folded from every activity. */
|
|
499
529
|
roster?: SubagentRoster;
|
|
530
|
+
/** Session keys rotated on `session_compact` awaiting a one-shot
|
|
531
|
+
* compaction handoff into a fresh agy conversation. */
|
|
532
|
+
pendingCompactionHandoff?: Set<string>;
|
|
500
533
|
/** Daily file log sink (src/daily-log.ts). Records pre-dispatch turn
|
|
501
534
|
* errors that never create a driver turn (and so never reach onTurnEnd). */
|
|
502
535
|
log?: (event: string, data?: unknown, level?: "debug" | "info" | "warn" | "error") => void;
|
|
@@ -1197,6 +1230,9 @@ export interface DriverDeps {
|
|
|
1197
1230
|
onNativeBackground?: (info: { conversationId: string; turnStartMs: number }) => void;
|
|
1198
1231
|
/** Subagent roster fold target (both engines; best-effort telemetry). */
|
|
1199
1232
|
roster?: SubagentRoster;
|
|
1233
|
+
/** Session keys rotated on `session_compact` awaiting a one-shot
|
|
1234
|
+
* compaction handoff into a fresh agy conversation. */
|
|
1235
|
+
pendingCompactionHandoff?: Set<string>;
|
|
1200
1236
|
/** Active engine (config), for engine-scoped session keys. */
|
|
1201
1237
|
engine: "stream-json" | "acp";
|
|
1202
1238
|
/** Daily file log sink for pre-dispatch errors (see StreamSimpleDeps). */
|
|
@@ -1431,7 +1467,16 @@ async function runTurnDriver(
|
|
|
1431
1467
|
|
|
1432
1468
|
const cwd = (options as { cwd?: string } | undefined)?.cwd ?? process.cwd();
|
|
1433
1469
|
const key = sessionKey(options, cwd, deps.engine);
|
|
1434
|
-
|
|
1470
|
+
// Ephemeral helper calls (pi compaction / branch summarization set
|
|
1471
|
+
// cacheRetention: "none"; cache warming / replay callers set
|
|
1472
|
+
// disableContinuation: true) must run in a fresh, isolated agy
|
|
1473
|
+
// conversation: never reuse or mutate the live session's SessionStore
|
|
1474
|
+
// binding, never claim dead/stranded tool results, and never arm
|
|
1475
|
+
// background watchers for throwaway turns.
|
|
1476
|
+
const ephemeral = options?.cacheRetention === "none" || options?.disableContinuation === true;
|
|
1477
|
+
const existing = ephemeral ? null : store.get(key);
|
|
1478
|
+
const compactionHandoff =
|
|
1479
|
+
!ephemeral && !existing?.conversationId && Boolean(deps.pendingCompactionHandoff?.has(key));
|
|
1435
1480
|
const messageCount = context.messages.length;
|
|
1436
1481
|
const config = loadConfig();
|
|
1437
1482
|
// Settle bookkeeping shared by both store.set paths: the boundary
|
|
@@ -1472,7 +1517,7 @@ async function runTurnDriver(
|
|
|
1472
1517
|
// nor start a new prompt. Leave the tombstone for the next fresh pass
|
|
1473
1518
|
// instead of consuming it blind.
|
|
1474
1519
|
const late: LateToolResult[] = [];
|
|
1475
|
-
if (!isContinuation) {
|
|
1520
|
+
if (!ephemeral && !isContinuation) {
|
|
1476
1521
|
for (const r of collectToolResults(context.messages, deps.roundTrips.deadIds)) {
|
|
1477
1522
|
const dead = deps.roundTrips.consumeDead(r.toolCallId);
|
|
1478
1523
|
if (dead)
|
|
@@ -1487,7 +1532,7 @@ async function runTurnDriver(
|
|
|
1487
1532
|
if (late.length > 0) {
|
|
1488
1533
|
deps.log?.("late-result", { tools: late.map((l) => l.name), freshConversation: !existing?.conversationId }, "info");
|
|
1489
1534
|
}
|
|
1490
|
-
} else if (deps.roundTrips.deadIds.length > 0) {
|
|
1535
|
+
} else if (!ephemeral && deps.roundTrips.deadIds.length > 0) {
|
|
1491
1536
|
deps.log?.("late-result-deferred", { count: deps.roundTrips.deadIds.length }, "info");
|
|
1492
1537
|
}
|
|
1493
1538
|
|
|
@@ -1512,6 +1557,14 @@ async function runTurnDriver(
|
|
|
1512
1557
|
images: view.images,
|
|
1513
1558
|
};
|
|
1514
1559
|
});
|
|
1560
|
+
// A rotation that lands mid-turn must win over any bind of a PRE-ROTATION
|
|
1561
|
+
// conversation: continuations and strand redeliveries both target the old
|
|
1562
|
+
// conversation id, so binding their outcomes would restore the
|
|
1563
|
+
// rotated-away binding and swallow the handoff. Evaluated at bind time:
|
|
1564
|
+
// the latch may arm after turn start.
|
|
1565
|
+
const rotationGuardArmed = (): boolean =>
|
|
1566
|
+
(isContinuation || redeliveryConversation !== undefined) &&
|
|
1567
|
+
deps.pendingCompactionHandoff?.has(key) === true;
|
|
1515
1568
|
/** Stream-json has no image channel in the turn input: stage the blocks
|
|
1516
1569
|
* to temp files and let the note point the model at the bridge read
|
|
1517
1570
|
* tool, whose result images the CLI delivers (probe 2026-09-07). ACP
|
|
@@ -1544,7 +1597,7 @@ async function runTurnDriver(
|
|
|
1544
1597
|
} else {
|
|
1545
1598
|
// Dead turn: claim NOW (single-use). A live turn claims after outcome
|
|
1546
1599
|
// instead — claiming here would eat the post-outcome recovery.
|
|
1547
|
-
late.push(...collectStranded());
|
|
1600
|
+
if (!ephemeral) late.push(...collectStranded());
|
|
1548
1601
|
if (isContinuation && late.length === 0) {
|
|
1549
1602
|
if (escalatedNames.length === 0) {
|
|
1550
1603
|
deps.log?.("turn-error", { reason: "tool-result-no-active-turn" }, "warn");
|
|
@@ -1582,14 +1635,29 @@ async function runTurnDriver(
|
|
|
1582
1635
|
// transcript (lastRole undefined) and a user tail both keep their
|
|
1583
1636
|
// existing behavior.
|
|
1584
1637
|
const lastRole = context.messages[context.messages.length - 1]?.role;
|
|
1638
|
+
const hasCompactionSummary = findLastCompactionIdx(context.messages) >= 0;
|
|
1585
1639
|
const resume =
|
|
1586
1640
|
!userPrompt &&
|
|
1587
1641
|
images.length === 0 &&
|
|
1588
1642
|
late.length === 0 &&
|
|
1589
1643
|
Boolean(existing?.conversationId) &&
|
|
1590
1644
|
(lastRole === "toolResult" || lastRole === "assistant");
|
|
1591
|
-
|
|
1645
|
+
// Post-compaction mid-tool-loop resume: session_compact rotated the old
|
|
1646
|
+
// agy conversation (so existing is null), and pi's compacted transcript
|
|
1647
|
+
// ends in a toolResult or assistant message. Seed a fresh agy
|
|
1648
|
+
// conversation with the compaction summary + trailing messages instead
|
|
1649
|
+
// of failing with the unretryable "No user message" error.
|
|
1650
|
+
const compactionResume =
|
|
1651
|
+
!ephemeral &&
|
|
1652
|
+
!userPrompt &&
|
|
1653
|
+
images.length === 0 &&
|
|
1654
|
+
late.length === 0 &&
|
|
1655
|
+
!existing?.conversationId &&
|
|
1656
|
+
(compactionHandoff || hasCompactionSummary) &&
|
|
1657
|
+
(lastRole === "toolResult" || lastRole === "assistant");
|
|
1658
|
+
const prompt = resume ? RESUME_PROMPT : compactionResume ? COMPACTION_RESUME_PROMPT : userPrompt;
|
|
1592
1659
|
if (resume) deps.log?.("resume-turn", { conversation: existing?.conversationId }, "error");
|
|
1660
|
+
if (compactionResume) deps.log?.("compaction-resume-turn", { key, handoff: compactionHandoff }, "info");
|
|
1593
1661
|
// An image-only message (no text) is valid on the ACP engine; only fail
|
|
1594
1662
|
// when there is nothing at all to send (no text, no images, no late
|
|
1595
1663
|
// tool results to deliver).
|
|
@@ -1615,15 +1683,20 @@ async function runTurnDriver(
|
|
|
1615
1683
|
// Late and resume turns re-open the conversation with a synthetic
|
|
1616
1684
|
// prompt; the digest would re-send context agy already holds (against a
|
|
1617
1685
|
// stale watermark: a failed pass never advances it), so skip it.
|
|
1686
|
+
// Post-compaction handoff / compactionResume always ships the digest
|
|
1687
|
+
// once even if config.digest is false, because the old agy conversation
|
|
1688
|
+
// was rotated and the fresh conversation has no prior history.
|
|
1618
1689
|
const engine = deps.engine ?? config.engine;
|
|
1619
1690
|
const promptBytes = Buffer.byteLength(prompt ?? "", "utf8");
|
|
1620
1691
|
const maxChars = digestMaxCharsForEngine(engine, promptBytes);
|
|
1692
|
+
const wantDigest = config.digest || compactionHandoff || compactionResume;
|
|
1621
1693
|
const digest =
|
|
1622
|
-
|
|
1694
|
+
wantDigest && maxChars !== null && late.length === 0 && !resume
|
|
1623
1695
|
? buildContextDigest(context.messages, watermark, {
|
|
1624
1696
|
bound: Boolean(existing?.conversationId),
|
|
1625
1697
|
seenSummaryId: existing?.digestSummaryId,
|
|
1626
1698
|
maxChars,
|
|
1699
|
+
includeLast: compactionResume,
|
|
1627
1700
|
})
|
|
1628
1701
|
: "";
|
|
1629
1702
|
// Byte-level fail closed (issue #2): the char budget over-reserves for
|
|
@@ -1770,7 +1843,7 @@ async function runTurnDriver(
|
|
|
1770
1843
|
// recreated a conversation, so the snapshot id is the real one, and
|
|
1771
1844
|
// the staged agent must move with the binding or a stream-json resume
|
|
1772
1845
|
// re-runs without its carrier-agent profile.
|
|
1773
|
-
if (!existing) {
|
|
1846
|
+
if (!ephemeral && !existing && !rotationGuardArmed()) {
|
|
1774
1847
|
const parkedConv = deps.driver.snapshot().conversationId;
|
|
1775
1848
|
if (parkedConv) {
|
|
1776
1849
|
store.set(key, {
|
|
@@ -1780,6 +1853,7 @@ async function runTurnDriver(
|
|
|
1780
1853
|
digestBoundary: settleBoundary,
|
|
1781
1854
|
digestSummaryId: settleSummaryId,
|
|
1782
1855
|
});
|
|
1856
|
+
deps.pendingCompactionHandoff?.delete(key);
|
|
1783
1857
|
if (stagedAgentName) stagedAgentByConversation.set(parkedConv, stagedAgentName);
|
|
1784
1858
|
}
|
|
1785
1859
|
}
|
|
@@ -1807,7 +1881,7 @@ async function runTurnDriver(
|
|
|
1807
1881
|
outcome.modelOutputSeen === false &&
|
|
1808
1882
|
Boolean(existing?.conversationId);
|
|
1809
1883
|
if (silentDrop || poisonedResume) {
|
|
1810
|
-
if (existing?.conversationId || outcome.conversationId) {
|
|
1884
|
+
if (!ephemeral && (existing?.conversationId || outcome.conversationId)) {
|
|
1811
1885
|
store.delete(key);
|
|
1812
1886
|
if (outcome.conversationId) stagedAgentByConversation.delete(outcome.conversationId);
|
|
1813
1887
|
}
|
|
@@ -1852,7 +1926,7 @@ async function runTurnDriver(
|
|
|
1852
1926
|
// fix: sweep and deliver as a late run in the same conversation. Single
|
|
1853
1927
|
// shot: claims are single-use, so a re-delivered strand cannot reappear
|
|
1854
1928
|
// here; a late run that parks hands recovery to the next pi pass.
|
|
1855
|
-
if (isContinuation && outcome.status === "OK" && !outcome.aborted) {
|
|
1929
|
+
if (!ephemeral && isContinuation && outcome.status === "OK" && !outcome.aborted) {
|
|
1856
1930
|
const more = collectStranded();
|
|
1857
1931
|
if (more.length > 0) {
|
|
1858
1932
|
const conv = redeliveryConversation ?? outcome.conversationId ?? existing?.conversationId ?? null;
|
|
@@ -1886,7 +1960,7 @@ async function runTurnDriver(
|
|
|
1886
1960
|
}
|
|
1887
1961
|
}
|
|
1888
1962
|
}
|
|
1889
|
-
if (outcome.conversationId) {
|
|
1963
|
+
if (!ephemeral && outcome.conversationId) {
|
|
1890
1964
|
// A different id than the stored one means the driver recreated the
|
|
1891
1965
|
// conversation under us (ACP session-load fallback, stream-json CLI
|
|
1892
1966
|
// dropping a stale --conversation). The recreated conversation has seen
|
|
@@ -1899,14 +1973,19 @@ async function runTurnDriver(
|
|
|
1899
1973
|
store.delete(key);
|
|
1900
1974
|
stagedAgentByConversation.delete(existing.conversationId);
|
|
1901
1975
|
} else if (outcome.status === "OK" && !outcome.aborted) {
|
|
1902
|
-
|
|
1903
|
-
|
|
1904
|
-
|
|
1905
|
-
|
|
1906
|
-
|
|
1907
|
-
|
|
1908
|
-
|
|
1909
|
-
|
|
1976
|
+
if (rotationGuardArmed()) {
|
|
1977
|
+
deps.log?.("rotation-binding-deferred", { conversation: outcome.conversationId, key }, "info");
|
|
1978
|
+
} else {
|
|
1979
|
+
store.set(key, {
|
|
1980
|
+
conversationId: outcome.conversationId,
|
|
1981
|
+
lastStepIdx: -1,
|
|
1982
|
+
lastMessageCount: messageCount,
|
|
1983
|
+
digestBoundary: settleBoundary,
|
|
1984
|
+
digestSummaryId: settleSummaryId,
|
|
1985
|
+
});
|
|
1986
|
+
deps.pendingCompactionHandoff?.delete(key);
|
|
1987
|
+
if (stagedAgentName) stagedAgentByConversation.set(outcome.conversationId, stagedAgentName);
|
|
1988
|
+
}
|
|
1910
1989
|
}
|
|
1911
1990
|
// A failed or aborted turn on the SAME conversation keeps the pre-turn
|
|
1912
1991
|
// record: whether the prompt actually landed in agy's DB is not
|
|
@@ -1928,10 +2007,15 @@ async function runTurnDriver(
|
|
|
1928
2007
|
if (blocks.textIdx === null && blocks.thinkingIdx === null) {
|
|
1929
2008
|
ensureTextOpen(stream, blocks);
|
|
1930
2009
|
}
|
|
1931
|
-
if (nativeBackgroundSeen && outcome.conversationId) {
|
|
2010
|
+
if (!ephemeral && nativeBackgroundSeen && outcome.conversationId) {
|
|
1932
2011
|
deps.onNativeBackground?.({ conversationId: outcome.conversationId, turnStartMs });
|
|
1933
2012
|
deps.log?.("native-background-arm", { conversation: outcome.conversationId, turnStartMs }, "info");
|
|
1934
2013
|
}
|
|
2014
|
+
// Multi-inference billing sums in usage.input + usage.cacheRead can exceed
|
|
2015
|
+
// model.contextWindow even when live occupancy (totalTokens) is well under
|
|
2016
|
+
// the window. Clamp before emitting stop so pi-ai's isContextOverflow()
|
|
2017
|
+
// Case 2 does not trigger a phantom overflow compaction on a healthy turn.
|
|
2018
|
+
clampOverflowUsage(blocks.partial.usage, model.contextWindow);
|
|
1935
2019
|
finalize(stream, blocks, "stop");
|
|
1936
2020
|
}
|
|
1937
2021
|
|
|
@@ -2020,6 +2104,7 @@ export function createStreamSimple(
|
|
|
2020
2104
|
onNativeEvent: deps.onNativeEvent,
|
|
2021
2105
|
onNativeBackground: deps.onNativeBackground,
|
|
2022
2106
|
roster: deps.roster,
|
|
2107
|
+
pendingCompactionHandoff: deps.pendingCompactionHandoff,
|
|
2023
2108
|
// Record the engine of the driver that will ACTUALLY run: if the
|
|
2024
2109
|
// ACP driver is absent, the config switch falls back to stream,
|
|
2025
2110
|
// and keying the session as @acp would store a stream
|
package/src/stream-events.ts
CHANGED
|
@@ -120,3 +120,42 @@ export function toPiUsage(
|
|
|
120
120
|
piUsage.cacheRead = u.cache_read_tokens ?? piUsage.cacheRead;
|
|
121
121
|
piUsage.totalTokens = u.total_tokens ?? piUsage.input + piUsage.output;
|
|
122
122
|
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Prevent pi-ai's silent-overflow detector (`isContextOverflow` Case 2) from
|
|
126
|
+
* false-triggering on multi-inference billing sums.
|
|
127
|
+
*
|
|
128
|
+
* In multi-step turns (several tool inferences inside one prompt), agy sums
|
|
129
|
+
* `input_tokens` and `cache_read_tokens` across every inference. `AcpDriver`
|
|
130
|
+
* keeps those billing fields while replacing `total_tokens` with single-turn
|
|
131
|
+
* context occupancy (issue #12). However, pi-ai's `isContextOverflow` ignores
|
|
132
|
+
* `totalTokens` and checks `usage.input + usage.cacheRead > contextWindow` on
|
|
133
|
+
* `stopReason === "stop"`, which triggers emergency overflow compaction at a
|
|
134
|
+
* fraction of the real context window.
|
|
135
|
+
*
|
|
136
|
+
* When live occupancy (`totalTokens`) fits inside `contextWindow` but
|
|
137
|
+
* `input + cacheRead` exceeds it, scale `input` and `cacheRead` proportionally
|
|
138
|
+
* to fit within the single-turn input budget (preserving the cache-hit ratio).
|
|
139
|
+
* Normal turns (`input + cacheRead <= contextWindow`) and genuine silent
|
|
140
|
+
* overflows (`totalTokens > contextWindow`) are left untouched.
|
|
141
|
+
*/
|
|
142
|
+
export function clampOverflowUsage(
|
|
143
|
+
usage: { input: number; output: number; cacheRead: number; totalTokens: number },
|
|
144
|
+
contextWindow: number | undefined,
|
|
145
|
+
): void {
|
|
146
|
+
if (contextWindow === undefined || !Number.isFinite(contextWindow) || contextWindow <= 0) return;
|
|
147
|
+
if (!Number.isFinite(usage.totalTokens) || usage.totalTokens <= 0) return;
|
|
148
|
+
if (usage.totalTokens > contextWindow) return;
|
|
149
|
+
if (!Number.isFinite(usage.input) || !Number.isFinite(usage.cacheRead)) return;
|
|
150
|
+
if (usage.input < 0 || usage.cacheRead < 0) return;
|
|
151
|
+
const rawInput = usage.input + usage.cacheRead;
|
|
152
|
+
if (rawInput <= contextWindow) return;
|
|
153
|
+
|
|
154
|
+
const target =
|
|
155
|
+
Number.isFinite(usage.output) && usage.output >= 0 && usage.output < usage.totalTokens
|
|
156
|
+
? usage.totalTokens - usage.output
|
|
157
|
+
: usage.totalTokens;
|
|
158
|
+
const scaledInput = Math.min(target, Math.max(0, Math.round((usage.input / rawInput) * target)));
|
|
159
|
+
usage.input = scaledInput;
|
|
160
|
+
usage.cacheRead = target - scaledInput;
|
|
161
|
+
}
|