@estebanforge/pi-antigravity-bridge 1.13.3 → 1.15.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 +27 -0
- package/README.md +2 -2
- package/extensions/index.ts +55 -18
- package/package.json +2 -2
- package/src/acp/driver.ts +59 -1
- package/src/acp/history-sync.ts +221 -0
- package/src/ask-tool.ts +3 -3
- package/src/bridge-catalog.ts +23 -3
- package/src/config.ts +41 -5
- package/src/driver-types.ts +34 -0
- package/src/history-projection.ts +188 -0
- package/src/history-sync.ts +299 -0
- package/src/models.ts +16 -11
- package/src/provider.ts +456 -59
- package/src/sessions.ts +12 -0
package/src/provider.ts
CHANGED
|
@@ -39,8 +39,10 @@ import { SubagentRoster } from "./subagent-roster.js";
|
|
|
39
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
|
+
import { AcpHistorySync, OutboundFrameBudgetError } from "./acp/history-sync.js";
|
|
42
43
|
import { SessionStore } from "./sessions.js";
|
|
43
44
|
import { detectQuotaNotice, quotaErrorMessage } from "./quota-notice.js";
|
|
45
|
+
import { redactText } from "./redact.js";
|
|
44
46
|
import { loadConfig } from "./config.js";
|
|
45
47
|
import { GATE_MARKER, mapNativeToShadow, stripMarkerFields } from "./approval-gate.js";
|
|
46
48
|
import type { ApprovalDecision, ApprovalPayload, ApprovalParkApi } from "./mcp-server.js";
|
|
@@ -241,19 +243,28 @@ export const SYSTEM_PROMPT_END = "[END SYSTEM PROMPT]";
|
|
|
241
243
|
* the user's machine must go through the bridge. Rides the systemPrompt
|
|
242
244
|
* gate: the note ships only when the system prompt ships. */
|
|
243
245
|
export const TOOL_PRIORITY_NOTE =
|
|
244
|
-
"[Tool priority: this conversation runs inside pi, not as a standalone agy session; the user only sees what surfaces in pi. Native interactive tools, for example ask_question, never reach the user. When a Pi Bridge tool covers the same purpose, always use the Pi Bridge tool; for user questions use ask_user_question. Your native file tools such as view_file only read brain artifacts and reject real filesystem paths; for any path on the user's machine use the Pi Bridge tools (read, ls, grep, find, edit,
|
|
246
|
+
"[Tool priority: this conversation runs inside pi, not as a standalone agy session; the user only sees what surfaces in pi. Native interactive tools, for example ask_question, never reach the user. When a Pi Bridge tool covers the same purpose, always use the Pi Bridge tool; for user questions use ask_user_question. Your native file tools such as view_file only read brain artifacts and reject real filesystem paths; for any path on the user's machine use the Pi Bridge tools (read, ls, grep, find, edit, write, bash). Image files are visible to you: the Pi Bridge read tool returns image files as visible images (png, jpg, webp, gif, bmp), so never claim you cannot view images. Extension Pi tools not declared directly are listed in bridge_tool_info; call bridge_tool_info to inspect their description and schema, then call bridge_call_tool to run them. When a bridge call answers STILL RUNNING, poll bridge_poll_result before doing other work: until you poll, the result (including any image) stays undelivered to you. Delegate subagent work the same way: when pi's tool list includes a delegation tool (for example subagent, Agent, agent_spawn, agent_wait, or subagent_run), always delegate through it and never through the native invoke_subagent, run_subagent, or manage_subagents; use native ones only if no pi delegation tool is listed, because native subagents run inside agy and are invisible to pi and anything watching it. Long-running bridge calls do not fail: after ~20 seconds the bridge answers STILL RUNNING with a callId; fetch the result with bridge_poll_result and poll until it lands. Your turn ends when your reply ends, and pi never waits for agy's own wake-ups: never let a native run_command go to the background (keep WaitMsBeforeAsync at 0 for foreground runs and native commands under two minutes, since longer foreground waits hit pi's idle cap and kill the turn; wrap long commands in timeout and run anything longer through the Pi Bridge bash tool, which keeps it inside your turn, and poll bridge_poll_result if it answers STILL RUNNING) and never use the native schedule tool or timers. A task left running when you reply outlives your turn: its wake-up cannot call Pi Bridge tools, and a delegated subagent session is already gone when it fires.]";
|
|
245
247
|
|
|
246
248
|
/** Assemble the full agy prompt: system prompt block, pi-side digest, user
|
|
247
249
|
* prompt. Empty parts are dropped. Pure; exported for unit testing.
|
|
248
250
|
* Pass systemPrompt only on a fresh conversation (see runTurnDriver). */
|
|
251
|
+
/** Appended after the tool-priority note when the bridge runs in codemode
|
|
252
|
+
* configuration: the engine's catalog has no direct file tools, so the
|
|
253
|
+
* note's "use the Pi Bridge tools" instruction must be redirected into
|
|
254
|
+
* scripts. */
|
|
255
|
+
export const CODEMODE_NOTE =
|
|
256
|
+
"This conversation runs in codemode configuration: the direct Pi file tools (read, ls, grep, find, edit, write, bash) are not in your tool list; call them from inside codemode scripts as tools.read, tools.ls, tools.grep, tools.find, tools.edit, tools.write, tools.bash. Long or multi-step file work belongs in one script, not many tool calls.";
|
|
257
|
+
|
|
249
258
|
export function buildFullPrompt(
|
|
250
259
|
systemPrompt: string | undefined,
|
|
251
260
|
digest: string,
|
|
252
261
|
prompt: string,
|
|
262
|
+
options?: { codemodeOnly?: boolean },
|
|
253
263
|
): string {
|
|
254
264
|
const parts: string[] = [];
|
|
255
265
|
if (systemPrompt) {
|
|
256
|
-
|
|
266
|
+
const note = options?.codemodeOnly ? `${TOOL_PRIORITY_NOTE}\n\n${CODEMODE_NOTE}` : TOOL_PRIORITY_NOTE;
|
|
267
|
+
parts.push(`${SYSTEM_PROMPT_PREAMBLE}\n\n${systemPrompt}\n\n${note}\n\n${SYSTEM_PROMPT_END}`);
|
|
257
268
|
}
|
|
258
269
|
if (digest) {
|
|
259
270
|
parts.push(`${DIGEST_PREAMBLE}\n\n${digest}`);
|
|
@@ -287,6 +298,39 @@ function stripCompactionWrapping(t: string): string {
|
|
|
287
298
|
return t.trim();
|
|
288
299
|
}
|
|
289
300
|
|
|
301
|
+
/** Per-part body caps so one oversized entry cannot starve the delta budget
|
|
302
|
+
* (issue #25: a single >8KB tool result used to erase every earlier turn).
|
|
303
|
+
* Head+tail keeps the result's opening and its final summary/error lines. */
|
|
304
|
+
const TOOL_RESULT_HEAD = 800;
|
|
305
|
+
const TOOL_RESULT_TAIL = 300;
|
|
306
|
+
|
|
307
|
+
function capToolResultBody(t: string): string {
|
|
308
|
+
if (!t) return "(no text output)";
|
|
309
|
+
const overflow = t.length - TOOL_RESULT_HEAD - TOOL_RESULT_TAIL;
|
|
310
|
+
if (overflow <= 0) return t;
|
|
311
|
+
return `${t.slice(0, TOOL_RESULT_HEAD)}\n[${overflow} chars elided]\n${t.slice(-TOOL_RESULT_TAIL)}`;
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
const TOOL_CALL_ARGS_CAP = 200;
|
|
315
|
+
|
|
316
|
+
function renderToolCalls(content: unknown): string {
|
|
317
|
+
if (!Array.isArray(content)) return "";
|
|
318
|
+
const lines: string[] = [];
|
|
319
|
+
for (const b of content) {
|
|
320
|
+
if (typeof b !== "object" || b === null || (b as { type?: string }).type !== "toolCall") continue;
|
|
321
|
+
const { name, arguments: args } = b as { name?: string; arguments?: unknown };
|
|
322
|
+
let argsText: string;
|
|
323
|
+
try {
|
|
324
|
+
argsText = JSON.stringify(args ?? {});
|
|
325
|
+
} catch {
|
|
326
|
+
argsText = "(unserializable args)";
|
|
327
|
+
}
|
|
328
|
+
if (argsText.length > TOOL_CALL_ARGS_CAP) argsText = `${argsText.slice(0, TOOL_CALL_ARGS_CAP)}…`;
|
|
329
|
+
lines.push(`[tool call: ${name ?? "?"}(${redactText(argsText)})]`);
|
|
330
|
+
}
|
|
331
|
+
return lines.join("\n");
|
|
332
|
+
}
|
|
333
|
+
|
|
290
334
|
export interface DigestOptions {
|
|
291
335
|
/** Provider id whose assistant turns are already in agy's own DB and so
|
|
292
336
|
* must be skipped to avoid double-counting. Default "antigravity". */
|
|
@@ -321,6 +365,13 @@ export interface DigestOptions {
|
|
|
321
365
|
/** Soft cap on the digest body when no tighter budget applies. */
|
|
322
366
|
const DIGEST_MAX_CHARS = 8000;
|
|
323
367
|
|
|
368
|
+
/** ACP digest cap: the embeddedContext transport carried a 120k-char probe
|
|
369
|
+
* block with exact needle recall at both block extremities
|
|
370
|
+
* (scripts/probe-acp-context.mjs, 2026-11-24), so 24k is transport-safe
|
|
371
|
+
* and shrinks the newest-first partial-render hole. stream-json keeps
|
|
372
|
+
* DIGEST_MAX_CHARS: its digest rides inline under the prompt byte cap. */
|
|
373
|
+
const ACP_DIGEST_MAX_CHARS = 24_000;
|
|
374
|
+
|
|
324
375
|
/** stream-json single-prompt silent-drop cap (issue #2, probed 2026-09-30):
|
|
325
376
|
* the CLI drops any prompt past ~25KB with SUCCESS and an empty response,
|
|
326
377
|
* and the dropped turn leaves the conversation permanently unresponsive. */
|
|
@@ -329,13 +380,13 @@ const STREAM_JSON_PROMPT_CAP = 25_000;
|
|
|
329
380
|
const STREAM_JSON_PROMPT_MARGIN = 4_096;
|
|
330
381
|
|
|
331
382
|
/** Per-engine digest cap. ACP ships the digest as an embeddedContext
|
|
332
|
-
resource block: no prompt cap applies, so the
|
|
333
|
-
stream-json the digest rides inline in the prompt, so it must fit under
|
|
383
|
+
resource block: no prompt cap applies, so the probe-raised cap stands.
|
|
384
|
+
On stream-json the digest rides inline in the prompt, so it must fit under
|
|
334
385
|
the silent-drop budget alongside the user's own prompt bytes. Returns
|
|
335
386
|
null when the budget is already exhausted (ship nothing rather than a
|
|
336
387
|
digest that would push the turn over the drop cap). */
|
|
337
388
|
export function digestMaxCharsForEngine(engine: string, promptLength: number): number | null {
|
|
338
|
-
if (engine === "acp") return
|
|
389
|
+
if (engine === "acp") return ACP_DIGEST_MAX_CHARS;
|
|
339
390
|
const budget = STREAM_JSON_PROMPT_CAP - promptLength - STREAM_JSON_PROMPT_MARGIN;
|
|
340
391
|
return budget > 0 ? Math.min(DIGEST_MAX_CHARS, budget) : null;
|
|
341
392
|
}
|
|
@@ -393,16 +444,36 @@ export function compactionFingerprint(m: Message): string {
|
|
|
393
444
|
* Fidelity note: other-provider assistant turns contribute only their text
|
|
394
445
|
* blocks; tool-call and thinking blocks are dropped. The intent (which tool)
|
|
395
446
|
* is lost, but their results still surface separately as toolResult messages. */
|
|
396
|
-
export
|
|
447
|
+
export interface DigestResult {
|
|
448
|
+
/** Digest body, "" when nothing rendered. */
|
|
449
|
+
text: string;
|
|
450
|
+
/** First index of the delta window (after clamp adjustments). */
|
|
451
|
+
windowStart: number;
|
|
452
|
+
/** Exclusive window end (run extraction boundary). */
|
|
453
|
+
windowEnd: number;
|
|
454
|
+
/** Oldest message index whose content is actually in the digest.
|
|
455
|
+
* == windowStart when the whole window rendered; == windowEnd when
|
|
456
|
+
* nothing fit; in between when the budget cut old turns (the pi-lens
|
|
457
|
+
* watermark invariant: the record may only claim delivery of what
|
|
458
|
+
* rendered). */
|
|
459
|
+
deliveredFrom: number;
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
export function buildContextDigestResult(
|
|
397
463
|
messages: Message[],
|
|
398
464
|
watermark: number,
|
|
399
465
|
opts: DigestOptions = {},
|
|
400
|
-
):
|
|
466
|
+
): DigestResult {
|
|
401
467
|
const own = opts.ownProvider ?? "antigravity";
|
|
402
468
|
const maxChars = opts.maxChars ?? DIGEST_MAX_CHARS;
|
|
403
|
-
if (messages.length === 0)
|
|
469
|
+
if (messages.length === 0) {
|
|
470
|
+
return { text: "", windowStart: 0, windowEnd: 0, deliveredFrom: 0 };
|
|
471
|
+
}
|
|
404
472
|
|
|
405
473
|
const deltaParts: string[] = [];
|
|
474
|
+
// Message index each delta part was rendered from: the budget cut has to
|
|
475
|
+
// report which messages actually shipped, not just how many parts.
|
|
476
|
+
const partIdx: number[] = [];
|
|
406
477
|
|
|
407
478
|
// 1. Compaction summary (never in agy's DB, so always high-value), but
|
|
408
479
|
// only when THIS summary has not shipped in a previous digest.
|
|
@@ -438,19 +509,22 @@ export function buildContextDigest(
|
|
|
438
509
|
const m = messages[i];
|
|
439
510
|
if (m.role === "assistant") {
|
|
440
511
|
if (opts.bound !== false && m.provider === own) continue; // our own turn: already in agy's DB
|
|
441
|
-
const t = blocksToText(m.content).trim();
|
|
512
|
+
const t = [blocksToText(m.content).trim(), renderToolCalls(m.content)].filter(Boolean).join("\n");
|
|
442
513
|
if (!t) continue;
|
|
443
514
|
deltaParts.push(`[assistant turn from ${m.provider}]\n${t}`);
|
|
515
|
+
partIdx.push(i);
|
|
444
516
|
} else if (m.role === "user") {
|
|
445
517
|
const t = blocksToText(m.content);
|
|
446
518
|
if (t.includes(COMPACTION_MARKER)) continue; // delivered as the summary part
|
|
447
519
|
if (!t.trim()) continue;
|
|
448
520
|
deltaParts.push(`[earlier user message]\n${t}`);
|
|
521
|
+
partIdx.push(i);
|
|
449
522
|
} else if (m.role === "toolResult") {
|
|
450
523
|
const t = blocksToText(m.content).trim();
|
|
451
524
|
deltaParts.push(
|
|
452
|
-
`[tool result: ${m.toolName}${m.isError ? " (error)" : ""}]\n${t
|
|
525
|
+
`[tool result: ${m.toolName}${m.isError ? " (error)" : ""}]\n${capToolResultBody(t)}`,
|
|
453
526
|
);
|
|
527
|
+
partIdx.push(i);
|
|
454
528
|
}
|
|
455
529
|
}
|
|
456
530
|
|
|
@@ -467,15 +541,18 @@ export function buildContextDigest(
|
|
|
467
541
|
summaryPart = `${summaryPart.slice(0, room)}\n${MARKER}`;
|
|
468
542
|
}
|
|
469
543
|
let delta = deltaParts.join(SEP);
|
|
544
|
+
let oldestKept = partIdx.length > 0 ? partIdx[0] : end;
|
|
470
545
|
if (maxChars > 0) {
|
|
471
546
|
const budget = Math.max(0, maxChars - (summaryPart ? summaryPart.length + SEP.length : 0));
|
|
472
547
|
if (delta.length > budget) {
|
|
473
548
|
const kept: string[] = [];
|
|
474
549
|
let used = 0;
|
|
550
|
+
oldestKept = end;
|
|
475
551
|
for (let i = deltaParts.length - 1; i >= 0; i--) {
|
|
476
552
|
const cost = deltaParts[i].length + (kept.length > 0 ? SEP.length : 0);
|
|
477
553
|
if (used + cost > budget) break;
|
|
478
554
|
kept.unshift(deltaParts[i]);
|
|
555
|
+
oldestKept = partIdx[i];
|
|
479
556
|
used += cost;
|
|
480
557
|
}
|
|
481
558
|
if (kept.length > 0) {
|
|
@@ -487,9 +564,18 @@ export function buildContextDigest(
|
|
|
487
564
|
}
|
|
488
565
|
}
|
|
489
566
|
|
|
490
|
-
|
|
567
|
+
const text = [summaryPart, delta]
|
|
491
568
|
.filter((s): s is string => typeof s === "string" && s.length > 0)
|
|
492
569
|
.join(SEP);
|
|
570
|
+
return { text, windowStart: start, windowEnd: end, deliveredFrom: text ? oldestKept : end };
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
export function buildContextDigest(
|
|
574
|
+
messages: Message[],
|
|
575
|
+
watermark: number,
|
|
576
|
+
opts: DigestOptions = {},
|
|
577
|
+
): string {
|
|
578
|
+
return buildContextDigestResult(messages, watermark, opts).text;
|
|
493
579
|
}
|
|
494
580
|
|
|
495
581
|
/** Build a fresh AssistantMessage shell for this turn. Mutated as blocks
|
|
@@ -596,6 +682,18 @@ export interface StreamSimpleDeps {
|
|
|
596
682
|
/** Session keys rotated on `session_compact` awaiting a one-shot
|
|
597
683
|
* compaction handoff into a fresh agy conversation. */
|
|
598
684
|
pendingCompactionHandoff?: Set<string>;
|
|
685
|
+
/** Live pi-side tool visibility (extension wiring). Lets prompt text
|
|
686
|
+
* adapt to the catalog the engine actually got; omitted in tests,
|
|
687
|
+
* which reads as "the configured mode is authoritative". */
|
|
688
|
+
hasActiveTool?: (name: string) => boolean;
|
|
689
|
+
/** Per-provider handoff runtime: the mode each session key's last
|
|
690
|
+
* dispatched turn used (continuations must settle under the same
|
|
691
|
+
* contract as the parked turn) and consecutive warm-session rebuild
|
|
692
|
+
* counts for the churn gate. Created by createStreamSimple. */
|
|
693
|
+
handoffRuntime?: {
|
|
694
|
+
mode: Map<string, "digest" | "sync">;
|
|
695
|
+
rebuildStreak: Map<string, number>;
|
|
696
|
+
};
|
|
599
697
|
/** Daily file log sink (src/daily-log.ts). Records pre-dispatch turn
|
|
600
698
|
* errors that never create a driver turn (and so never reach onTurnEnd). */
|
|
601
699
|
log?: (event: string, data?: unknown, level?: "debug" | "info" | "warn" | "error") => void;
|
|
@@ -1301,6 +1399,13 @@ export interface DriverDeps {
|
|
|
1301
1399
|
pendingCompactionHandoff?: Set<string>;
|
|
1302
1400
|
/** Active engine (config), for engine-scoped session keys. */
|
|
1303
1401
|
engine: "stream-json" | "acp";
|
|
1402
|
+
/** Live pi-side tool visibility (see StreamSimpleDeps). */
|
|
1403
|
+
hasActiveTool?: (name: string) => boolean;
|
|
1404
|
+
/** Per-provider handoff runtime (see StreamSimpleDeps). */
|
|
1405
|
+
handoffRuntime?: {
|
|
1406
|
+
mode: Map<string, "digest" | "sync">;
|
|
1407
|
+
rebuildStreak: Map<string, number>;
|
|
1408
|
+
};
|
|
1304
1409
|
/** Daily file log sink for pre-dispatch errors (see StreamSimpleDeps). */
|
|
1305
1410
|
log?: (event: string, data?: unknown, level?: "debug" | "info" | "warn" | "error") => void;
|
|
1306
1411
|
}
|
|
@@ -1552,6 +1657,11 @@ async function runTurnDriver(
|
|
|
1552
1657
|
// Summary id carried forward from the record; the gate below overwrites it
|
|
1553
1658
|
// only when a digest actually ships, so skipped turns never lose it.
|
|
1554
1659
|
let settleSummaryId = existing?.digestSummaryId;
|
|
1660
|
+
// Settle writes (both store.set paths) use these: they default to normal
|
|
1661
|
+
// advance semantics and the digest build overrides them when a wanted
|
|
1662
|
+
// digest failed to ship (see the delivery invariant at the build site).
|
|
1663
|
+
let nextCount = messageCount;
|
|
1664
|
+
let nextBoundary: string | undefined = settleBoundary;
|
|
1555
1665
|
|
|
1556
1666
|
// Continuation: resolve parked round-trips from pi's toolResult messages,
|
|
1557
1667
|
// then re-attach to the still-running agy turn. No new user event is sent:
|
|
@@ -1653,6 +1763,30 @@ async function runTurnDriver(
|
|
|
1653
1763
|
const effort = entry?.efforts?.length ? toAgyEffort(options?.reasoning, entry.efforts) : undefined;
|
|
1654
1764
|
|
|
1655
1765
|
let handle: TurnHandle | undefined;
|
|
1766
|
+
// True when THIS pass dispatched a fresh driver.run on the digest flow
|
|
1767
|
+
// (the sync dispatch and live re-attaches leave it false): it keys the
|
|
1768
|
+
// settle contract below so a digest redelivery over a sync-latched
|
|
1769
|
+
// session settles digest-shaped.
|
|
1770
|
+
let digestDispatched = false;
|
|
1771
|
+
// The codemode note ships only when the engine's catalog actually has
|
|
1772
|
+
// the tool: pi registers codemode inactive by default, and the note
|
|
1773
|
+
// would otherwise point at scripts the engine cannot call. No probe
|
|
1774
|
+
// dep (tests) reads as "the configured mode is authoritative".
|
|
1775
|
+
let codemodeNote = false;
|
|
1776
|
+
if (config.bridgeTools === "codemode") {
|
|
1777
|
+
// A stale pi handle throws on getActiveTools after /reload or a
|
|
1778
|
+
// session replacement; fall back to the configured value rather
|
|
1779
|
+
// than killing the turn from the prompt-builder path.
|
|
1780
|
+
try {
|
|
1781
|
+
codemodeNote = deps.hasActiveTool?.("codemode") ?? true;
|
|
1782
|
+
} catch {
|
|
1783
|
+
codemodeNote = true;
|
|
1784
|
+
}
|
|
1785
|
+
}
|
|
1786
|
+
// The sync orchestrator for THIS pass when the sync gate dispatched; the
|
|
1787
|
+
// settle (and the park persist) sit outside the fresh-pass block, so the
|
|
1788
|
+
// binding is function-level (the round-1 settle scope trap).
|
|
1789
|
+
let syncTurn: AcpHistorySync | undefined;
|
|
1656
1790
|
// Name of the carrier agent staged for THIS turn's fresh conversation, if
|
|
1657
1791
|
// any. Recorded into stagedAgentByConversation once the outcome binds the
|
|
1658
1792
|
// conversation id, so later gate-closed turns pass the same agent.
|
|
@@ -1784,22 +1918,124 @@ async function runTurnDriver(
|
|
|
1784
1918
|
}
|
|
1785
1919
|
}
|
|
1786
1920
|
}
|
|
1921
|
+
// --- sync handoff mode (opt-in via AGY_HANDOFF=sync, ACP-only) ---
|
|
1922
|
+
// The checkpoint/plan owns continuity instead of the digest: history
|
|
1923
|
+
// ships as a framed resource block, the record persists the zeroed
|
|
1924
|
+
// contract, and the settle bypasses the digest store writes. Legacy
|
|
1925
|
+
// paths (late/strand redelivery, retry-dropped resume, post-compaction
|
|
1926
|
+
// resume) and the churn latch stay on the digest flow.
|
|
1927
|
+
const handoffRuntime = deps.handoffRuntime;
|
|
1928
|
+
const syncTurnRequested = config.handoff === "sync" && engine === "acp";
|
|
1929
|
+
if (
|
|
1930
|
+
syncTurnRequested &&
|
|
1931
|
+
!ephemeral &&
|
|
1932
|
+
!isContinuation &&
|
|
1933
|
+
late.length === 0 &&
|
|
1934
|
+
!resume &&
|
|
1935
|
+
!compactionResume &&
|
|
1936
|
+
!redeliveryConversation &&
|
|
1937
|
+
!existing?.sync?.digestFallback
|
|
1938
|
+
) {
|
|
1939
|
+
const turn = new AcpHistorySync(context.messages, existing, { isBacklogShape: isBacklogUserShape });
|
|
1940
|
+
syncTurn = turn;
|
|
1941
|
+
deps.log?.(
|
|
1942
|
+
"sync-plan",
|
|
1943
|
+
{ key, kind: turn.plan.kind, reason: turn.plan.reason, fresh: turn.freshConversation, history: turn.plan.history.length },
|
|
1944
|
+
"info",
|
|
1945
|
+
);
|
|
1946
|
+
if (existing && turn.plan.kind === "rebuild" && turn.plan.reason === "changed-prefix") {
|
|
1947
|
+
// Count ONLY transcript churn (the checkpoint exists but the
|
|
1948
|
+
// prefix moved: per-turn context-hook rewrites). Failure-induced
|
|
1949
|
+
// rebuilds (invalidReason, unsettled submissions, first-enable
|
|
1950
|
+
// missing checkpoints) are transient and must never pin the
|
|
1951
|
+
// session to digest.
|
|
1952
|
+
const streak = (handoffRuntime?.rebuildStreak.get(key) ?? 0) + 1;
|
|
1953
|
+
handoffRuntime?.rebuildStreak.set(key, streak);
|
|
1954
|
+
if (streak >= 3 && !existing.sync?.digestFallback) {
|
|
1955
|
+
turn.markDigestFallback();
|
|
1956
|
+
deps.log?.("sync-churn-fallback", { key, streak }, "warn");
|
|
1957
|
+
}
|
|
1958
|
+
} else if (turn.plan.kind !== "rebuild") {
|
|
1959
|
+
handoffRuntime?.rebuildStreak.delete(key);
|
|
1960
|
+
}
|
|
1961
|
+
const gateOpen = Boolean(config.systemPrompt) && turn.freshConversation;
|
|
1962
|
+
const sys = gateOpen ? getCurrentSystemPrompt(context.messages) || undefined : undefined;
|
|
1963
|
+
const syncImages = [...images, ...late.flatMap((l) => l.images ?? [])];
|
|
1964
|
+
try {
|
|
1965
|
+
// inputFor hard-fails past the outbound frame budget and the
|
|
1966
|
+
// coordinator calls throw on invariants: both must fail the turn
|
|
1967
|
+
// visibly, not surface as an unhandled rejection.
|
|
1968
|
+
const input = turn.inputFor({
|
|
1969
|
+
prompt: buildFullPrompt(sys, "", userPrompt ?? "", { codemodeOnly: codemodeNote }) + stageImageNote(syncImages),
|
|
1970
|
+
images: syncImages,
|
|
1971
|
+
});
|
|
1972
|
+
turn.bound(key);
|
|
1973
|
+
turn.dispatching();
|
|
1974
|
+
handle = await deps.driver.run({
|
|
1975
|
+
cwd,
|
|
1976
|
+
model: agyModel,
|
|
1977
|
+
effort,
|
|
1978
|
+
mode: config.mode,
|
|
1979
|
+
skipPermissions: config.skipPermissions,
|
|
1980
|
+
timeoutMin: config.turnTimeoutMin,
|
|
1981
|
+
inactivityMin: config.inactivityTimeoutMin,
|
|
1982
|
+
conversationId: turn.boundConversationId,
|
|
1983
|
+
prompt: input.prompt,
|
|
1984
|
+
images: input.images,
|
|
1985
|
+
agent: config.agent,
|
|
1986
|
+
contextBlock: input.contextBlock,
|
|
1987
|
+
onSessionBound: ({ sessionId }) => {
|
|
1988
|
+
turn.adoptBinding(sessionId);
|
|
1989
|
+
if (!rotationGuardArmed()) {
|
|
1990
|
+
const rec = turn.record();
|
|
1991
|
+
if (rec.conversationId) store.set(key, { ...rec, conversationId: rec.conversationId });
|
|
1992
|
+
}
|
|
1993
|
+
},
|
|
1994
|
+
onSessionLoadFailed: () => {
|
|
1995
|
+
// session/load died: re-plan as a rebuild and ship the whole
|
|
1996
|
+
// history to a fresh conversation; the gate re-opens there.
|
|
1997
|
+
const fresh = turn.loadFailed({
|
|
1998
|
+
prompt:
|
|
1999
|
+
buildFullPrompt(config.systemPrompt ? getCurrentSystemPrompt(context.messages) || undefined : undefined, "", userPrompt ?? "", { codemodeOnly: codemodeNote }) +
|
|
2000
|
+
stageImageNote(syncImages),
|
|
2001
|
+
images: syncImages,
|
|
2002
|
+
});
|
|
2003
|
+
// Re-arm the settle: loadFailed invalidated and re-planned
|
|
2004
|
+
// (phase syncing), and the swap prompt below is the turn's
|
|
2005
|
+
// real dispatch — without this the settle finds a
|
|
2006
|
+
// non-settleable coordinator and forces a second rebuild.
|
|
2007
|
+
turn.bound(key);
|
|
2008
|
+
turn.dispatching();
|
|
2009
|
+
return { prompt: fresh.prompt, contextBlock: fresh.contextBlock, images: fresh.images };
|
|
2010
|
+
},
|
|
2011
|
+
signal: options?.signal,
|
|
2012
|
+
});
|
|
2013
|
+
handoffRuntime?.mode.set(key, "sync");
|
|
2014
|
+
} catch (err) {
|
|
2015
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
2016
|
+
deps.log?.("turn-error", { reason: "dispatch-failed", error: msg }, "error");
|
|
2017
|
+
finalize(stream, blocks, "error", err instanceof OutboundFrameBudgetError ? msg : `agy failed to start: ${msg}`);
|
|
2018
|
+
return;
|
|
2019
|
+
}
|
|
2020
|
+
}
|
|
1787
2021
|
const promptBytes = Buffer.byteLength(deliveredPrompt, "utf8");
|
|
1788
2022
|
// A truncated run ships alone: the digest budget is spent, and a
|
|
1789
2023
|
// marker-only digest beside a sliced prompt is noise that also breaks
|
|
1790
2024
|
// agy's server-side prompt cache.
|
|
1791
2025
|
const wantDigest = (config.digest || compactionHandoff || compactionResume) && !runTruncated;
|
|
1792
2026
|
const maxChars = digestMaxCharsForEngine(engine, promptBytes);
|
|
1793
|
-
const
|
|
2027
|
+
const digestRes =
|
|
2028
|
+
!syncTurn &&
|
|
1794
2029
|
wantDigest && maxChars !== null && late.length === 0 && !resume
|
|
1795
|
-
?
|
|
2030
|
+
? buildContextDigestResult(context.messages, watermark, {
|
|
1796
2031
|
bound: Boolean(existing?.conversationId),
|
|
1797
2032
|
seenSummaryId: existing?.digestSummaryId,
|
|
1798
2033
|
maxChars,
|
|
1799
2034
|
end: run.runStart,
|
|
1800
2035
|
includeLast: compactionResume,
|
|
1801
2036
|
})
|
|
1802
|
-
:
|
|
2037
|
+
: undefined;
|
|
2038
|
+
const digest = digestRes?.text ?? "";
|
|
1803
2039
|
// Byte-level fail closed (issue #2): the char budget over-reserves for
|
|
1804
2040
|
// ASCII but a multibyte digest can still exceed the remaining byte
|
|
1805
2041
|
// room. ACP carries no prompt cap, so the check is stream-json only.
|
|
@@ -1809,6 +2045,36 @@ async function runTurnDriver(
|
|
|
1809
2045
|
promptBytes + STREAM_JSON_PROMPT_MARGIN + Buffer.byteLength(digest, "utf8") > STREAM_JSON_PROMPT_CAP
|
|
1810
2046
|
? ""
|
|
1811
2047
|
: digest;
|
|
2048
|
+
// Watermark delivery invariant (issue #25 follow-up): the record may
|
|
2049
|
+
// only claim what reached agy. When a built digest failed the byte
|
|
2050
|
+
// check, nothing shipped, so the settle write HOLDS the pre-turn
|
|
2051
|
+
// watermark - the whole window re-offers next turn, duplicating
|
|
2052
|
+
// nothing because nothing arrived. (maxChars null is defensive: a
|
|
2053
|
+
// spent budget co-occurs with runTruncated, which skips the digest
|
|
2054
|
+
// deliberately.) Partial renders (budget cut the oldest turns) still
|
|
2055
|
+
// advance: the hole can never re-fit under the newest-first budget,
|
|
2056
|
+
// and re-offering it every turn would re-embed cap-sized duplicate
|
|
2057
|
+
// blocks into agy's DB; the hole is logged instead.
|
|
2058
|
+
const digestDropped = wantDigest && (maxChars === null || (digest !== "" && !digestFinal));
|
|
2059
|
+
if (digestDropped) {
|
|
2060
|
+
nextCount = existing?.lastMessageCount ?? watermark;
|
|
2061
|
+
nextBoundary = existing?.digestBoundary;
|
|
2062
|
+
}
|
|
2063
|
+
if (!syncTurn)
|
|
2064
|
+
deps.log?.(
|
|
2065
|
+
"digest",
|
|
2066
|
+
{
|
|
2067
|
+
engine,
|
|
2068
|
+
bound: Boolean(existing?.conversationId),
|
|
2069
|
+
maxChars,
|
|
2070
|
+
bytes: digestFinal ? Buffer.byteLength(digestFinal, "utf8") : 0,
|
|
2071
|
+
windowStart: digestRes?.windowStart,
|
|
2072
|
+
windowEnd: digestRes?.windowEnd,
|
|
2073
|
+
deliveredFrom: digestRes?.deliveredFrom,
|
|
2074
|
+
shipped: Boolean(digestFinal),
|
|
2075
|
+
},
|
|
2076
|
+
digestDropped ? "warn" : "info",
|
|
2077
|
+
);
|
|
1812
2078
|
// The delivered summary id persists only when a digest actually shipped:
|
|
1813
2079
|
// late/resume/budget-skipped turns carry the previous id forward so the
|
|
1814
2080
|
// summary is not lost to a turn that never delivered it.
|
|
@@ -1840,7 +2106,11 @@ async function runTurnDriver(
|
|
|
1840
2106
|
if (deps.engine !== "acp") {
|
|
1841
2107
|
if (rawSysPrompt && !config.agent) {
|
|
1842
2108
|
const stagedName = stageSyspromptAgent(
|
|
1843
|
-
[
|
|
2109
|
+
[
|
|
2110
|
+
SYSTEM_PROMPT_PREAMBLE,
|
|
2111
|
+
rawSysPrompt,
|
|
2112
|
+
codemodeNote ? `${TOOL_PRIORITY_NOTE}\n\n${CODEMODE_NOTE}` : TOOL_PRIORITY_NOTE,
|
|
2113
|
+
].join("\n\n"),
|
|
1844
2114
|
);
|
|
1845
2115
|
if (stagedName) {
|
|
1846
2116
|
agent = stagedName;
|
|
@@ -1867,44 +2137,90 @@ async function runTurnDriver(
|
|
|
1867
2137
|
// prompt is text-only); user-message images ride them on ACP natively
|
|
1868
2138
|
// and staged files on stream-json.
|
|
1869
2139
|
const runImages = [...images, ...late.flatMap((l) => l.images ?? [])];
|
|
2140
|
+
// Issue #25: an ACP session/load failure silently creates a fresh agy
|
|
2141
|
+
// conversation mid-turn, and the bound-mode prompt (G10 gate closed by
|
|
2142
|
+
// the binding, bound:true digest skipping own turns) would ship blind.
|
|
2143
|
+
// This variant is built as-if-fresh; the driver swaps it in only when
|
|
2144
|
+
// the load actually fails. stream-json cannot detect that drop, so it
|
|
2145
|
+
// is ACP-only.
|
|
2146
|
+
const requestConversation = redeliveryConversation ?? existing?.conversationId ?? null;
|
|
2147
|
+
const acpFallback =
|
|
2148
|
+
!syncTurn && deps.engine === "acp" && requestConversation && !resume && late.length === 0
|
|
2149
|
+
? (() => {
|
|
2150
|
+
const fbSys = config.systemPrompt
|
|
2151
|
+
? getCurrentSystemPrompt(context.messages) || undefined
|
|
2152
|
+
: undefined;
|
|
2153
|
+
const freshDigest = wantDigest
|
|
2154
|
+
? buildContextDigestResult(context.messages, 0, {
|
|
2155
|
+
bound: false,
|
|
2156
|
+
maxChars: ACP_DIGEST_MAX_CHARS,
|
|
2157
|
+
end: run.runStart,
|
|
2158
|
+
includeLast: compactionResume,
|
|
2159
|
+
})
|
|
2160
|
+
: null;
|
|
2161
|
+
// Both features off: the variant would equal the plain prompt.
|
|
2162
|
+
if (!fbSys && !freshDigest?.text) return undefined;
|
|
2163
|
+
return {
|
|
2164
|
+
prompt: buildFullPrompt(fbSys, "", deliveredPrompt, { codemodeOnly: codemodeNote }) + stageImageNote(runImages),
|
|
2165
|
+
contextBlock: freshDigest?.text
|
|
2166
|
+
? {
|
|
2167
|
+
uri: `urn:pi-bridge:context-digest/fresh/${messageCount}`,
|
|
2168
|
+
text: `${DIGEST_PREAMBLE}\n\n${freshDigest.text}`,
|
|
2169
|
+
}
|
|
2170
|
+
: undefined,
|
|
2171
|
+
};
|
|
2172
|
+
})()
|
|
2173
|
+
: undefined;
|
|
1870
2174
|
const fullPrompt =
|
|
1871
2175
|
(late.length > 0
|
|
1872
2176
|
? buildLateResultPrompt(late, deliveredPrompt || undefined)
|
|
1873
|
-
: buildFullPrompt(sysPrompt, embeddedDigest ? "" : digestFinal, deliveredPrompt)) +
|
|
2177
|
+
: buildFullPrompt(sysPrompt, embeddedDigest ? "" : digestFinal, deliveredPrompt, { codemodeOnly: codemodeNote })) +
|
|
1874
2178
|
stageImageNote(runImages);
|
|
1875
|
-
|
|
1876
|
-
|
|
1877
|
-
|
|
1878
|
-
|
|
1879
|
-
|
|
1880
|
-
|
|
1881
|
-
|
|
1882
|
-
|
|
1883
|
-
|
|
1884
|
-
|
|
1885
|
-
|
|
1886
|
-
|
|
1887
|
-
|
|
1888
|
-
|
|
1889
|
-
|
|
1890
|
-
|
|
1891
|
-
|
|
1892
|
-
|
|
1893
|
-
|
|
1894
|
-
|
|
1895
|
-
|
|
1896
|
-
|
|
1897
|
-
|
|
1898
|
-
|
|
1899
|
-
|
|
1900
|
-
|
|
1901
|
-
|
|
1902
|
-
|
|
1903
|
-
|
|
1904
|
-
|
|
2179
|
+
if (!syncTurn) {
|
|
2180
|
+
try {
|
|
2181
|
+
handle = await deps.driver.run({
|
|
2182
|
+
cwd,
|
|
2183
|
+
model: agyModel,
|
|
2184
|
+
effort,
|
|
2185
|
+
mode: config.mode,
|
|
2186
|
+
skipPermissions: config.skipPermissions,
|
|
2187
|
+
timeoutMin: config.turnTimeoutMin,
|
|
2188
|
+
inactivityMin: config.inactivityTimeoutMin,
|
|
2189
|
+
conversationId: redeliveryConversation ?? existing?.conversationId ?? null,
|
|
2190
|
+
prompt: fullPrompt,
|
|
2191
|
+
images: runImages.length > 0 ? runImages : undefined,
|
|
2192
|
+
agent,
|
|
2193
|
+
fallback: acpFallback,
|
|
2194
|
+
contextBlock: embeddedDigest
|
|
2195
|
+
? {
|
|
2196
|
+
uri: `urn:pi-bridge:context-digest/${messageCount}`,
|
|
2197
|
+
text: `${DIGEST_PREAMBLE}\n\n${embeddedDigest}`,
|
|
2198
|
+
}
|
|
2199
|
+
: undefined,
|
|
2200
|
+
signal: options?.signal,
|
|
2201
|
+
});
|
|
2202
|
+
if (!ephemeral) handoffRuntime?.mode.set(key, "digest");
|
|
2203
|
+
digestDispatched = true;
|
|
2204
|
+
} catch (err) {
|
|
2205
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
2206
|
+
// Release stranded claims: the delivery never started, so the next
|
|
2207
|
+
// pass must find them undelivered (tombstone-borne items have no
|
|
2208
|
+
// callId and stay consumed, as before).
|
|
2209
|
+
for (const l of late) if (l.callId) deps.roundTrips.unclaim(l.callId);
|
|
2210
|
+
deps.log?.("turn-error", { reason: "driver-start-failed", error: msg }, "error");
|
|
2211
|
+
finalize(stream, blocks, "error", `agy failed to start: ${msg}`);
|
|
2212
|
+
return;
|
|
2213
|
+
}
|
|
1905
2214
|
}
|
|
1906
2215
|
}
|
|
1907
2216
|
|
|
2217
|
+
if (!handle) {
|
|
2218
|
+
// Unreachable in practice: every non-finalized path above dispatched a
|
|
2219
|
+
// turn. Fail visibly instead of arguing with the type checker.
|
|
2220
|
+
finalize(stream, blocks, "error", "agy turn was not dispatched");
|
|
2221
|
+
return;
|
|
2222
|
+
}
|
|
2223
|
+
|
|
1908
2224
|
ensureStarted(stream, blocks);
|
|
1909
2225
|
const diffCtx = new TurnDiffContext(createExecGitOps());
|
|
1910
2226
|
// Background latch: one WaitMsBeforeAsync-shaped native call this turn is
|
|
@@ -1944,18 +2260,28 @@ async function runTurnDriver(
|
|
|
1944
2260
|
// recreated a conversation, so the snapshot id is the real one, and
|
|
1945
2261
|
// the staged agent must move with the binding or a stream-json resume
|
|
1946
2262
|
// re-runs without its carrier-agent profile.
|
|
1947
|
-
if (!ephemeral && !
|
|
2263
|
+
if (!ephemeral && !rotationGuardArmed() && (syncTurn || !existing)) {
|
|
1948
2264
|
const parkedConv = deps.driver.snapshot().conversationId;
|
|
1949
2265
|
if (parkedConv) {
|
|
1950
|
-
|
|
1951
|
-
|
|
1952
|
-
|
|
1953
|
-
|
|
1954
|
-
|
|
1955
|
-
|
|
1956
|
-
|
|
1957
|
-
|
|
1958
|
-
|
|
2266
|
+
if (syncTurn) {
|
|
2267
|
+
// Sync persists the zeroed contract with the adopted binding;
|
|
2268
|
+
// a rebuild that parked already carried the compaction summary
|
|
2269
|
+
// as history, so the latch has no second consumer.
|
|
2270
|
+
syncTurn.adoptBinding(parkedConv);
|
|
2271
|
+
const rec = syncTurn.record();
|
|
2272
|
+
if (rec.conversationId) store.set(key, { ...rec, conversationId: rec.conversationId });
|
|
2273
|
+
if (syncTurn.freshConversation) deps.pendingCompactionHandoff?.delete(key);
|
|
2274
|
+
} else {
|
|
2275
|
+
store.set(key, {
|
|
2276
|
+
conversationId: parkedConv,
|
|
2277
|
+
lastStepIdx: -1,
|
|
2278
|
+
lastMessageCount: nextCount,
|
|
2279
|
+
digestBoundary: nextBoundary,
|
|
2280
|
+
digestSummaryId: settleSummaryId,
|
|
2281
|
+
});
|
|
2282
|
+
deps.pendingCompactionHandoff?.delete(key);
|
|
2283
|
+
if (stagedAgentName) stagedAgentByConversation.set(parkedConv, stagedAgentName);
|
|
2284
|
+
}
|
|
1959
2285
|
}
|
|
1960
2286
|
}
|
|
1961
2287
|
return;
|
|
@@ -2061,7 +2387,65 @@ async function runTurnDriver(
|
|
|
2061
2387
|
}
|
|
2062
2388
|
}
|
|
2063
2389
|
}
|
|
2064
|
-
|
|
2390
|
+
// Sync settle: the orchestrator owns the record write (zeroed contract),
|
|
2391
|
+
// so the digest settle below is bypassed entirely. A continuation of a
|
|
2392
|
+
// parked sync turn reconstructs the coordinator from the record (the
|
|
2393
|
+
// live re-attach fires no hooks) and marks it dispatched so the two-step
|
|
2394
|
+
// settle can terminal. A digest redelivery over a sync-latched session
|
|
2395
|
+
// (dead handle, deadIds) settles digest-shaped instead.
|
|
2396
|
+
const syncContract =
|
|
2397
|
+
syncTurn !== undefined ||
|
|
2398
|
+
(isContinuation && !digestDispatched && !ephemeral && deps.handoffRuntime?.mode.get(key) === "sync");
|
|
2399
|
+
if (syncContract && !ephemeral) {
|
|
2400
|
+
try {
|
|
2401
|
+
const settleSync =
|
|
2402
|
+
syncTurn ??
|
|
2403
|
+
(() => {
|
|
2404
|
+
const recon = new AcpHistorySync(context.messages, existing, {
|
|
2405
|
+
continuation: isContinuation,
|
|
2406
|
+
isBacklogShape: isBacklogUserShape,
|
|
2407
|
+
});
|
|
2408
|
+
recon.bound(key);
|
|
2409
|
+
recon.dispatching();
|
|
2410
|
+
return recon;
|
|
2411
|
+
})();
|
|
2412
|
+
const result = settleSync.finish(
|
|
2413
|
+
{
|
|
2414
|
+
ok: outcome.status === "OK",
|
|
2415
|
+
conversationId: outcome.conversationId ?? null,
|
|
2416
|
+
aborted: outcome.aborted,
|
|
2417
|
+
promptAttempted: outcome.promptAttempted,
|
|
2418
|
+
promptTerminal: outcome.promptTerminal,
|
|
2419
|
+
},
|
|
2420
|
+
blocks.partial,
|
|
2421
|
+
context.messages,
|
|
2422
|
+
existing?.conversationId,
|
|
2423
|
+
);
|
|
2424
|
+
deps.log?.(
|
|
2425
|
+
"sync-settle",
|
|
2426
|
+
{
|
|
2427
|
+
key,
|
|
2428
|
+
settled: result.settled,
|
|
2429
|
+
...("reason" in result ? { reason: result.reason } : {}),
|
|
2430
|
+
conversation: outcome.conversationId,
|
|
2431
|
+
},
|
|
2432
|
+
"info",
|
|
2433
|
+
);
|
|
2434
|
+
const record = settleSync.record();
|
|
2435
|
+
if (record.conversationId && !rotationGuardArmed()) {
|
|
2436
|
+
store.set(key, { ...record, conversationId: record.conversationId });
|
|
2437
|
+
// A rebuild shipped the compaction summary as history; the one-shot
|
|
2438
|
+
// latch has no second consumer.
|
|
2439
|
+
if (settleSync.freshConversation) deps.pendingCompactionHandoff?.delete(key);
|
|
2440
|
+
}
|
|
2441
|
+
} catch (err) {
|
|
2442
|
+
// A settle invariant failure must not surface as an unhandled
|
|
2443
|
+
// rejection (the caller is void): dropping the record forces a
|
|
2444
|
+
// named rebuild next turn, the safe direction.
|
|
2445
|
+
deps.log?.("sync-settle-failed", { key, error: err instanceof Error ? err.message : String(err) }, "error");
|
|
2446
|
+
store.delete(key);
|
|
2447
|
+
}
|
|
2448
|
+
} else if (!ephemeral && outcome.conversationId) {
|
|
2065
2449
|
// A different id than the stored one means the driver recreated the
|
|
2066
2450
|
// conversation under us (ACP session-load fallback, stream-json CLI
|
|
2067
2451
|
// dropping a stale --conversation). The recreated conversation has seen
|
|
@@ -2080,9 +2464,13 @@ async function runTurnDriver(
|
|
|
2080
2464
|
store.set(key, {
|
|
2081
2465
|
conversationId: outcome.conversationId,
|
|
2082
2466
|
lastStepIdx: -1,
|
|
2083
|
-
lastMessageCount:
|
|
2084
|
-
digestBoundary:
|
|
2467
|
+
lastMessageCount: nextCount,
|
|
2468
|
+
digestBoundary: nextBoundary,
|
|
2085
2469
|
digestSummaryId: settleSummaryId,
|
|
2470
|
+
// The churn latch must survive digest turns (store.set
|
|
2471
|
+
// replaces the record), or the gate re-opens next turn and
|
|
2472
|
+
// the session alternates rebuild/digest forever.
|
|
2473
|
+
...(existing?.sync?.digestFallback ? { sync: existing.sync } : {}),
|
|
2086
2474
|
});
|
|
2087
2475
|
deps.pendingCompactionHandoff?.delete(key);
|
|
2088
2476
|
if (stagedAgentName) stagedAgentByConversation.set(outcome.conversationId, stagedAgentName);
|
|
@@ -2128,6 +2516,13 @@ export function createStreamSimple(
|
|
|
2128
2516
|
deps: StreamSimpleDeps,
|
|
2129
2517
|
): (model: Model<Api>, context: TranscriptContext, options?: SimpleStreamOptions) => AssistantMessageEventStream {
|
|
2130
2518
|
const { entries, store, roundTrips } = deps;
|
|
2519
|
+
// Per-provider handoff runtime: the park-time mode latch (continuations
|
|
2520
|
+
// must settle under the same contract as the parked turn) and the churn
|
|
2521
|
+
// gate's consecutive-rebuild counter, both keyed by session key.
|
|
2522
|
+
const handoffRuntime = {
|
|
2523
|
+
mode: new Map<string, "digest" | "sync">(),
|
|
2524
|
+
rebuildStreak: new Map<string, number>(),
|
|
2525
|
+
};
|
|
2131
2526
|
|
|
2132
2527
|
return function streamSimple(model, context, options) {
|
|
2133
2528
|
const stream = createAssistantMessageEventStream();
|
|
@@ -2206,6 +2601,8 @@ export function createStreamSimple(
|
|
|
2206
2601
|
onNativeBackground: deps.onNativeBackground,
|
|
2207
2602
|
roster: deps.roster,
|
|
2208
2603
|
pendingCompactionHandoff: deps.pendingCompactionHandoff,
|
|
2604
|
+
handoffRuntime,
|
|
2605
|
+
hasActiveTool: deps.hasActiveTool,
|
|
2209
2606
|
// Record the engine of the driver that will ACTUALLY run: if the
|
|
2210
2607
|
// ACP driver is absent, the config switch falls back to stream,
|
|
2211
2608
|
// and keying the session as @acp would store a stream
|