@estebanforge/pi-antigravity-bridge 1.14.0 → 1.15.1
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 +18 -0
- package/README.md +2 -2
- package/extensions/index.ts +34 -17
- package/package.json +2 -2
- package/src/acp/driver.ts +52 -5
- package/src/acp/history-sync.ts +221 -0
- package/src/ask-tool.ts +1 -1
- package/src/bridge-catalog.ts +23 -3
- package/src/config.ts +20 -5
- package/src/driver-types.ts +26 -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 +487 -92
- package/src/sessions.ts +12 -0
package/src/provider.ts
CHANGED
|
@@ -39,6 +39,7 @@ 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";
|
|
44
45
|
import { redactText } from "./redact.js";
|
|
@@ -87,6 +88,15 @@ export function _resetObservationalMemoryWarnedForTesting(): void {
|
|
|
87
88
|
* each other's files. */
|
|
88
89
|
const stagedAgentByConversation = new Map<string, string>();
|
|
89
90
|
|
|
91
|
+
/** Per-session mid-park steering cursor: the context length the current turn
|
|
92
|
+
* was dispatched with, and the transcript index past the last steer actually
|
|
93
|
+
* delivered to agy. The moving first-pending-toolResult anchor alone misses
|
|
94
|
+
* a steer that landed during an EARLIER park of a park chain: the anchor
|
|
95
|
+
* moves to the newer park's toolResult, which sits after the steer, and the
|
|
96
|
+
* settle claims it undelivered. Absent (pi restart mid-turn) the provider
|
|
97
|
+
* falls back to the anchor rule. */
|
|
98
|
+
const steerCursors = new Map<string, { dispatchedAt: number; deliveredThrough: number }>();
|
|
99
|
+
|
|
90
100
|
/** Zero-usage helper. agy doesn't expose token counts; pi's cost math gets
|
|
91
101
|
* zeros (we're not billing through this provider). */
|
|
92
102
|
function zeroUsage(): Usage {
|
|
@@ -242,19 +252,28 @@ export const SYSTEM_PROMPT_END = "[END SYSTEM PROMPT]";
|
|
|
242
252
|
* the user's machine must go through the bridge. Rides the systemPrompt
|
|
243
253
|
* gate: the note ships only when the system prompt ships. */
|
|
244
254
|
export const TOOL_PRIORITY_NOTE =
|
|
245
|
-
"[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,
|
|
255
|
+
"[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.]";
|
|
246
256
|
|
|
247
257
|
/** Assemble the full agy prompt: system prompt block, pi-side digest, user
|
|
248
258
|
* prompt. Empty parts are dropped. Pure; exported for unit testing.
|
|
249
259
|
* Pass systemPrompt only on a fresh conversation (see runTurnDriver). */
|
|
260
|
+
/** Appended after the tool-priority note when the bridge runs in codemode
|
|
261
|
+
* configuration: the engine's catalog has no direct file tools, so the
|
|
262
|
+
* note's "use the Pi Bridge tools" instruction must be redirected into
|
|
263
|
+
* scripts. */
|
|
264
|
+
export const CODEMODE_NOTE =
|
|
265
|
+
"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.";
|
|
266
|
+
|
|
250
267
|
export function buildFullPrompt(
|
|
251
268
|
systemPrompt: string | undefined,
|
|
252
269
|
digest: string,
|
|
253
270
|
prompt: string,
|
|
271
|
+
options?: { codemodeOnly?: boolean },
|
|
254
272
|
): string {
|
|
255
273
|
const parts: string[] = [];
|
|
256
274
|
if (systemPrompt) {
|
|
257
|
-
|
|
275
|
+
const note = options?.codemodeOnly ? `${TOOL_PRIORITY_NOTE}\n\n${CODEMODE_NOTE}` : TOOL_PRIORITY_NOTE;
|
|
276
|
+
parts.push(`${SYSTEM_PROMPT_PREAMBLE}\n\n${systemPrompt}\n\n${note}\n\n${SYSTEM_PROMPT_END}`);
|
|
258
277
|
}
|
|
259
278
|
if (digest) {
|
|
260
279
|
parts.push(`${DIGEST_PREAMBLE}\n\n${digest}`);
|
|
@@ -365,9 +384,9 @@ const ACP_DIGEST_MAX_CHARS = 24_000;
|
|
|
365
384
|
/** stream-json single-prompt silent-drop cap (issue #2, probed 2026-09-30):
|
|
366
385
|
* the CLI drops any prompt past ~25KB with SUCCESS and an empty response,
|
|
367
386
|
* and the dropped turn leaves the conversation permanently unresponsive. */
|
|
368
|
-
const STREAM_JSON_PROMPT_CAP = 25_000;
|
|
387
|
+
export const STREAM_JSON_PROMPT_CAP = 25_000;
|
|
369
388
|
/** Headroom under the cap for the staged-image note and prompt framing. */
|
|
370
|
-
const STREAM_JSON_PROMPT_MARGIN = 4_096;
|
|
389
|
+
export const STREAM_JSON_PROMPT_MARGIN = 4_096;
|
|
371
390
|
|
|
372
391
|
/** Per-engine digest cap. ACP ships the digest as an embeddedContext
|
|
373
392
|
resource block: no prompt cap applies, so the probe-raised cap stands.
|
|
@@ -672,6 +691,18 @@ export interface StreamSimpleDeps {
|
|
|
672
691
|
/** Session keys rotated on `session_compact` awaiting a one-shot
|
|
673
692
|
* compaction handoff into a fresh agy conversation. */
|
|
674
693
|
pendingCompactionHandoff?: Set<string>;
|
|
694
|
+
/** Live pi-side tool visibility (extension wiring). Lets prompt text
|
|
695
|
+
* adapt to the catalog the engine actually got; omitted in tests,
|
|
696
|
+
* which reads as "the configured mode is authoritative". */
|
|
697
|
+
hasActiveTool?: (name: string) => boolean;
|
|
698
|
+
/** Per-provider handoff runtime: the mode each session key's last
|
|
699
|
+
* dispatched turn used (continuations must settle under the same
|
|
700
|
+
* contract as the parked turn) and consecutive warm-session rebuild
|
|
701
|
+
* counts for the churn gate. Created by createStreamSimple. */
|
|
702
|
+
handoffRuntime?: {
|
|
703
|
+
mode: Map<string, "digest" | "sync">;
|
|
704
|
+
rebuildStreak: Map<string, number>;
|
|
705
|
+
};
|
|
675
706
|
/** Daily file log sink (src/daily-log.ts). Records pre-dispatch turn
|
|
676
707
|
* errors that never create a driver turn (and so never reach onTurnEnd). */
|
|
677
708
|
log?: (event: string, data?: unknown, level?: "debug" | "info" | "warn" | "error") => void;
|
|
@@ -1342,6 +1373,57 @@ export interface LateToolResult {
|
|
|
1342
1373
|
images?: Array<{ data: string; mimeType: string }>;
|
|
1343
1374
|
}
|
|
1344
1375
|
|
|
1376
|
+
export interface SteeredUserMessage {
|
|
1377
|
+
/** Transcript index of the message; the watermark hold on a failed
|
|
1378
|
+
* delivery claims up to this index. */
|
|
1379
|
+
index: number;
|
|
1380
|
+
text: string;
|
|
1381
|
+
images: Array<{ data: string; mimeType: string }>;
|
|
1382
|
+
}
|
|
1383
|
+
|
|
1384
|
+
/** User messages pi delivered into the context after the steering floor: pi's
|
|
1385
|
+
* steering poll runs right after tool results, so a message typed while agy
|
|
1386
|
+
* was parked joins the transcript but the continuation pass re-attaches to
|
|
1387
|
+
* the parked turn and sends no new user event (Baluard 2026-11-25: the
|
|
1388
|
+
* message sat in the transcript, agy never saw it, and pi's drained queue
|
|
1389
|
+
* never re-triggered - the turn just ended). The floor is the session's
|
|
1390
|
+
* steering cursor (dispatch length + delivered-through); without one (pi
|
|
1391
|
+
* restart mid-turn) it falls back to the first still-pending toolResult's
|
|
1392
|
+
* index, whose everything-before belongs to the parked turn's dispatched
|
|
1393
|
+
* prompt. Backlog shapes (compaction/branch/bash runs) never count as
|
|
1394
|
+
* steering. Pure; exported for tests. */
|
|
1395
|
+
export function collectSteeredUserMessages(messages: Message[], pendingIds: readonly string[], floor?: number): SteeredUserMessage[] {
|
|
1396
|
+
if (pendingIds.length === 0) return [];
|
|
1397
|
+
let start: number;
|
|
1398
|
+
if (floor !== undefined) {
|
|
1399
|
+
start = floor;
|
|
1400
|
+
} else {
|
|
1401
|
+
const pending = new Set(pendingIds);
|
|
1402
|
+
let anchor = -1;
|
|
1403
|
+
for (let i = 0; i < messages.length; i++) {
|
|
1404
|
+
const m = messages[i];
|
|
1405
|
+
if (m.role !== "toolResult") continue;
|
|
1406
|
+
const id = (m as { toolCallId?: string }).toolCallId;
|
|
1407
|
+
if (id && pending.has(id)) {
|
|
1408
|
+
anchor = i;
|
|
1409
|
+
break;
|
|
1410
|
+
}
|
|
1411
|
+
}
|
|
1412
|
+
if (anchor < 0) return [];
|
|
1413
|
+
start = anchor + 1;
|
|
1414
|
+
}
|
|
1415
|
+
const out: SteeredUserMessage[] = [];
|
|
1416
|
+
for (let i = start; i < messages.length; i++) {
|
|
1417
|
+
const m = messages[i];
|
|
1418
|
+
if (m.role !== "user") continue;
|
|
1419
|
+
if (isBacklogUserShape(blocksToText(m.content))) continue;
|
|
1420
|
+
const parts = lastMessageParts(m);
|
|
1421
|
+
if (!parts.text && parts.images.length === 0) continue;
|
|
1422
|
+
out.push({ index: i, text: parts.text ?? "", images: parts.images });
|
|
1423
|
+
}
|
|
1424
|
+
return out;
|
|
1425
|
+
}
|
|
1426
|
+
|
|
1345
1427
|
/** Frame late tool results so agy treats them as the results its bridge calls
|
|
1346
1428
|
* never received: a park whose round-trip died while the pi tool ran, or an
|
|
1347
1429
|
* escalated result the model never polled. The reason carries the framing. */
|
|
@@ -1377,6 +1459,13 @@ export interface DriverDeps {
|
|
|
1377
1459
|
pendingCompactionHandoff?: Set<string>;
|
|
1378
1460
|
/** Active engine (config), for engine-scoped session keys. */
|
|
1379
1461
|
engine: "stream-json" | "acp";
|
|
1462
|
+
/** Live pi-side tool visibility (see StreamSimpleDeps). */
|
|
1463
|
+
hasActiveTool?: (name: string) => boolean;
|
|
1464
|
+
/** Per-provider handoff runtime (see StreamSimpleDeps). */
|
|
1465
|
+
handoffRuntime?: {
|
|
1466
|
+
mode: Map<string, "digest" | "sync">;
|
|
1467
|
+
rebuildStreak: Map<string, number>;
|
|
1468
|
+
};
|
|
1380
1469
|
/** Daily file log sink for pre-dispatch errors (see StreamSimpleDeps). */
|
|
1381
1470
|
log?: (event: string, data?: unknown, level?: "debug" | "info" | "warn" | "error") => void;
|
|
1382
1471
|
}
|
|
@@ -1639,6 +1728,22 @@ async function runTurnDriver(
|
|
|
1639
1728
|
// agy receives the result via the bridge's MCP HTTP response.
|
|
1640
1729
|
const results = collectToolResults(context.messages, deps.roundTrips.pendingIds);
|
|
1641
1730
|
const isContinuation = results.length > 0;
|
|
1731
|
+
// Scanned before the resolve loop: the pending set must still contain the
|
|
1732
|
+
// parks being resolved. The steering floor is the session's dispatch
|
|
1733
|
+
// cursor when one exists (dispatch length + delivered-through), else the
|
|
1734
|
+
// first-pending-toolResult anchor fallback.
|
|
1735
|
+
const steerCursor = steerCursors.get(key);
|
|
1736
|
+
const steered = ephemeral
|
|
1737
|
+
? []
|
|
1738
|
+
: collectSteeredUserMessages(
|
|
1739
|
+
context.messages,
|
|
1740
|
+
deps.roundTrips.pendingIds,
|
|
1741
|
+
steerCursor ? Math.max(steerCursor.dispatchedAt, steerCursor.deliveredThrough) : undefined,
|
|
1742
|
+
);
|
|
1743
|
+
// Set when a steer leads the dead-turn fallback into a fresh dispatch: the
|
|
1744
|
+
// steer shipped as that dispatch's own prompt, so the post-outcome sweep
|
|
1745
|
+
// must stay off (and its stranded-claim re-sweep with it).
|
|
1746
|
+
let steerLedFresh = false;
|
|
1642
1747
|
// Escalated calls answer through bridge_poll_result, not through an agy
|
|
1643
1748
|
// turn waiting on the park, so note them before resolving.
|
|
1644
1749
|
const escalatedNames = results
|
|
@@ -1734,6 +1839,30 @@ async function runTurnDriver(
|
|
|
1734
1839
|
const effort = entry?.efforts?.length ? toAgyEffort(options?.reasoning, entry.efforts) : undefined;
|
|
1735
1840
|
|
|
1736
1841
|
let handle: TurnHandle | undefined;
|
|
1842
|
+
// True when THIS pass dispatched a fresh driver.run on the digest flow
|
|
1843
|
+
// (the sync dispatch and live re-attaches leave it false): it keys the
|
|
1844
|
+
// settle contract below so a digest redelivery over a sync-latched
|
|
1845
|
+
// session settles digest-shaped.
|
|
1846
|
+
let digestDispatched = false;
|
|
1847
|
+
// The codemode note ships only when the engine's catalog actually has
|
|
1848
|
+
// the tool: pi registers codemode inactive by default, and the note
|
|
1849
|
+
// would otherwise point at scripts the engine cannot call. No probe
|
|
1850
|
+
// dep (tests) reads as "the configured mode is authoritative".
|
|
1851
|
+
let codemodeNote = false;
|
|
1852
|
+
if (config.bridgeTools === "codemode") {
|
|
1853
|
+
// A stale pi handle throws on getActiveTools after /reload or a
|
|
1854
|
+
// session replacement; fall back to the configured value rather
|
|
1855
|
+
// than killing the turn from the prompt-builder path.
|
|
1856
|
+
try {
|
|
1857
|
+
codemodeNote = deps.hasActiveTool?.("codemode") ?? true;
|
|
1858
|
+
} catch {
|
|
1859
|
+
codemodeNote = true;
|
|
1860
|
+
}
|
|
1861
|
+
}
|
|
1862
|
+
// The sync orchestrator for THIS pass when the sync gate dispatched; the
|
|
1863
|
+
// settle (and the park persist) sit outside the fresh-pass block, so the
|
|
1864
|
+
// binding is function-level (the round-1 settle scope trap).
|
|
1865
|
+
let syncTurn: AcpHistorySync | undefined;
|
|
1737
1866
|
// Name of the carrier agent staged for THIS turn's fresh conversation, if
|
|
1738
1867
|
// any. Recorded into stagedAgentByConversation once the outcome binds the
|
|
1739
1868
|
// conversation id, so later gate-closed turns pass the same agent.
|
|
@@ -1745,7 +1874,13 @@ async function runTurnDriver(
|
|
|
1745
1874
|
// Dead turn: claim NOW (single-use). A live turn claims after outcome
|
|
1746
1875
|
// instead — claiming here would eat the post-outcome recovery.
|
|
1747
1876
|
if (!ephemeral) late.push(...collectStranded());
|
|
1748
|
-
|
|
1877
|
+
// A steer with a bound conversation leads the fresh dispatch instead of
|
|
1878
|
+
// stopping quietly: the trailing user run becomes the prompt, so the
|
|
1879
|
+
// message is answered rather than dropped or left to the digest window.
|
|
1880
|
+
// The sweep below must not re-deliver what that dispatch just shipped.
|
|
1881
|
+
const steerCanLead = steered.length > 0 && Boolean(existing?.conversationId);
|
|
1882
|
+
if (isContinuation && late.length === 0 && steerCanLead) steerLedFresh = true;
|
|
1883
|
+
if (isContinuation && late.length === 0 && !steerCanLead) {
|
|
1749
1884
|
if (escalatedNames.length === 0) {
|
|
1750
1885
|
deps.log?.("turn-error", { reason: "tool-result-no-active-turn" }, "warn");
|
|
1751
1886
|
finalize(stream, blocks, "error", "tool result arrived but no antigravity turn is running");
|
|
@@ -1865,6 +2000,114 @@ async function runTurnDriver(
|
|
|
1865
2000
|
}
|
|
1866
2001
|
}
|
|
1867
2002
|
}
|
|
2003
|
+
// --- sync handoff mode (opt-in via AGY_HANDOFF=sync, ACP-only) ---
|
|
2004
|
+
// The checkpoint/plan owns continuity instead of the digest: history
|
|
2005
|
+
// ships as a framed resource block, the record persists the zeroed
|
|
2006
|
+
// contract, and the settle bypasses the digest store writes. Legacy
|
|
2007
|
+
// paths (late/strand redelivery, retry-dropped resume, post-compaction
|
|
2008
|
+
// resume) and the churn latch stay on the digest flow.
|
|
2009
|
+
// A fresh dispatch of the trailing user run opens a new steering window:
|
|
2010
|
+
// everything up to here is the prompt the turn carries, so mid-park
|
|
2011
|
+
// steers must land strictly after this index. Synthetic prompts (late
|
|
2012
|
+
// strands, resume, compaction seeding) do NOT open one - their context
|
|
2013
|
+
// may still hold undelivered steers.
|
|
2014
|
+
if (!resume && !compactionResume && late.length === 0) {
|
|
2015
|
+
steerCursors.set(key, { dispatchedAt: messageCount, deliveredThrough: 0 });
|
|
2016
|
+
}
|
|
2017
|
+
const handoffRuntime = deps.handoffRuntime;
|
|
2018
|
+
const syncTurnRequested = config.handoff === "sync" && engine === "acp";
|
|
2019
|
+
if (
|
|
2020
|
+
syncTurnRequested &&
|
|
2021
|
+
!ephemeral &&
|
|
2022
|
+
!isContinuation &&
|
|
2023
|
+
late.length === 0 &&
|
|
2024
|
+
!resume &&
|
|
2025
|
+
!compactionResume &&
|
|
2026
|
+
!redeliveryConversation &&
|
|
2027
|
+
!existing?.sync?.digestFallback
|
|
2028
|
+
) {
|
|
2029
|
+
const turn = new AcpHistorySync(context.messages, existing, { isBacklogShape: isBacklogUserShape });
|
|
2030
|
+
syncTurn = turn;
|
|
2031
|
+
deps.log?.(
|
|
2032
|
+
"sync-plan",
|
|
2033
|
+
{ key, kind: turn.plan.kind, reason: turn.plan.reason, fresh: turn.freshConversation, history: turn.plan.history.length },
|
|
2034
|
+
"info",
|
|
2035
|
+
);
|
|
2036
|
+
if (existing && turn.plan.kind === "rebuild" && turn.plan.reason === "changed-prefix") {
|
|
2037
|
+
// Count ONLY transcript churn (the checkpoint exists but the
|
|
2038
|
+
// prefix moved: per-turn context-hook rewrites). Failure-induced
|
|
2039
|
+
// rebuilds (invalidReason, unsettled submissions, first-enable
|
|
2040
|
+
// missing checkpoints) are transient and must never pin the
|
|
2041
|
+
// session to digest.
|
|
2042
|
+
const streak = (handoffRuntime?.rebuildStreak.get(key) ?? 0) + 1;
|
|
2043
|
+
handoffRuntime?.rebuildStreak.set(key, streak);
|
|
2044
|
+
if (streak >= 3 && !existing.sync?.digestFallback) {
|
|
2045
|
+
turn.markDigestFallback();
|
|
2046
|
+
deps.log?.("sync-churn-fallback", { key, streak }, "warn");
|
|
2047
|
+
}
|
|
2048
|
+
} else if (turn.plan.kind !== "rebuild") {
|
|
2049
|
+
handoffRuntime?.rebuildStreak.delete(key);
|
|
2050
|
+
}
|
|
2051
|
+
const gateOpen = Boolean(config.systemPrompt) && turn.freshConversation;
|
|
2052
|
+
const sys = gateOpen ? getCurrentSystemPrompt(context.messages) || undefined : undefined;
|
|
2053
|
+
const syncImages = [...images, ...late.flatMap((l) => l.images ?? [])];
|
|
2054
|
+
try {
|
|
2055
|
+
// inputFor hard-fails past the outbound frame budget and the
|
|
2056
|
+
// coordinator calls throw on invariants: both must fail the turn
|
|
2057
|
+
// visibly, not surface as an unhandled rejection.
|
|
2058
|
+
const input = turn.inputFor({
|
|
2059
|
+
prompt: buildFullPrompt(sys, "", userPrompt ?? "", { codemodeOnly: codemodeNote }) + stageImageNote(syncImages),
|
|
2060
|
+
images: syncImages,
|
|
2061
|
+
});
|
|
2062
|
+
turn.bound(key);
|
|
2063
|
+
turn.dispatching();
|
|
2064
|
+
handle = await deps.driver.run({
|
|
2065
|
+
cwd,
|
|
2066
|
+
model: agyModel,
|
|
2067
|
+
effort,
|
|
2068
|
+
mode: config.mode,
|
|
2069
|
+
skipPermissions: config.skipPermissions,
|
|
2070
|
+
timeoutMin: config.turnTimeoutMin,
|
|
2071
|
+
inactivityMin: config.inactivityTimeoutMin,
|
|
2072
|
+
conversationId: turn.boundConversationId,
|
|
2073
|
+
prompt: input.prompt,
|
|
2074
|
+
images: input.images,
|
|
2075
|
+
agent: config.agent,
|
|
2076
|
+
contextBlock: input.contextBlock,
|
|
2077
|
+
onSessionBound: ({ sessionId }) => {
|
|
2078
|
+
turn.adoptBinding(sessionId);
|
|
2079
|
+
if (!rotationGuardArmed()) {
|
|
2080
|
+
const rec = turn.record();
|
|
2081
|
+
if (rec.conversationId) store.set(key, { ...rec, conversationId: rec.conversationId });
|
|
2082
|
+
}
|
|
2083
|
+
},
|
|
2084
|
+
onSessionLoadFailed: () => {
|
|
2085
|
+
// session/load died: re-plan as a rebuild and ship the whole
|
|
2086
|
+
// history to a fresh conversation; the gate re-opens there.
|
|
2087
|
+
const fresh = turn.loadFailed({
|
|
2088
|
+
prompt:
|
|
2089
|
+
buildFullPrompt(config.systemPrompt ? getCurrentSystemPrompt(context.messages) || undefined : undefined, "", userPrompt ?? "", { codemodeOnly: codemodeNote }) +
|
|
2090
|
+
stageImageNote(syncImages),
|
|
2091
|
+
images: syncImages,
|
|
2092
|
+
});
|
|
2093
|
+
// Re-arm the settle: loadFailed invalidated and re-planned
|
|
2094
|
+
// (phase syncing), and the swap prompt below is the turn's
|
|
2095
|
+
// real dispatch — without this the settle finds a
|
|
2096
|
+
// non-settleable coordinator and forces a second rebuild.
|
|
2097
|
+
turn.bound(key);
|
|
2098
|
+
turn.dispatching();
|
|
2099
|
+
return { prompt: fresh.prompt, contextBlock: fresh.contextBlock, images: fresh.images };
|
|
2100
|
+
},
|
|
2101
|
+
signal: options?.signal,
|
|
2102
|
+
});
|
|
2103
|
+
handoffRuntime?.mode.set(key, "sync");
|
|
2104
|
+
} catch (err) {
|
|
2105
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
2106
|
+
deps.log?.("turn-error", { reason: "dispatch-failed", error: msg }, "error");
|
|
2107
|
+
finalize(stream, blocks, "error", err instanceof OutboundFrameBudgetError ? msg : `agy failed to start: ${msg}`);
|
|
2108
|
+
return;
|
|
2109
|
+
}
|
|
2110
|
+
}
|
|
1868
2111
|
const promptBytes = Buffer.byteLength(deliveredPrompt, "utf8");
|
|
1869
2112
|
// A truncated run ships alone: the digest budget is spent, and a
|
|
1870
2113
|
// marker-only digest beside a sliced prompt is noise that also breaks
|
|
@@ -1872,6 +2115,7 @@ async function runTurnDriver(
|
|
|
1872
2115
|
const wantDigest = (config.digest || compactionHandoff || compactionResume) && !runTruncated;
|
|
1873
2116
|
const maxChars = digestMaxCharsForEngine(engine, promptBytes);
|
|
1874
2117
|
const digestRes =
|
|
2118
|
+
!syncTurn &&
|
|
1875
2119
|
wantDigest && maxChars !== null && late.length === 0 && !resume
|
|
1876
2120
|
? buildContextDigestResult(context.messages, watermark, {
|
|
1877
2121
|
bound: Boolean(existing?.conversationId),
|
|
@@ -1906,20 +2150,21 @@ async function runTurnDriver(
|
|
|
1906
2150
|
nextCount = existing?.lastMessageCount ?? watermark;
|
|
1907
2151
|
nextBoundary = existing?.digestBoundary;
|
|
1908
2152
|
}
|
|
1909
|
-
|
|
1910
|
-
|
|
1911
|
-
|
|
1912
|
-
|
|
1913
|
-
|
|
1914
|
-
|
|
1915
|
-
|
|
1916
|
-
|
|
1917
|
-
|
|
1918
|
-
|
|
1919
|
-
|
|
1920
|
-
|
|
1921
|
-
|
|
1922
|
-
|
|
2153
|
+
if (!syncTurn)
|
|
2154
|
+
deps.log?.(
|
|
2155
|
+
"digest",
|
|
2156
|
+
{
|
|
2157
|
+
engine,
|
|
2158
|
+
bound: Boolean(existing?.conversationId),
|
|
2159
|
+
maxChars,
|
|
2160
|
+
bytes: digestFinal ? Buffer.byteLength(digestFinal, "utf8") : 0,
|
|
2161
|
+
windowStart: digestRes?.windowStart,
|
|
2162
|
+
windowEnd: digestRes?.windowEnd,
|
|
2163
|
+
deliveredFrom: digestRes?.deliveredFrom,
|
|
2164
|
+
shipped: Boolean(digestFinal),
|
|
2165
|
+
},
|
|
2166
|
+
digestDropped ? "warn" : "info",
|
|
2167
|
+
);
|
|
1923
2168
|
// The delivered summary id persists only when a digest actually shipped:
|
|
1924
2169
|
// late/resume/budget-skipped turns carry the previous id forward so the
|
|
1925
2170
|
// summary is not lost to a turn that never delivered it.
|
|
@@ -1951,7 +2196,11 @@ async function runTurnDriver(
|
|
|
1951
2196
|
if (deps.engine !== "acp") {
|
|
1952
2197
|
if (rawSysPrompt && !config.agent) {
|
|
1953
2198
|
const stagedName = stageSyspromptAgent(
|
|
1954
|
-
[
|
|
2199
|
+
[
|
|
2200
|
+
SYSTEM_PROMPT_PREAMBLE,
|
|
2201
|
+
rawSysPrompt,
|
|
2202
|
+
codemodeNote ? `${TOOL_PRIORITY_NOTE}\n\n${CODEMODE_NOTE}` : TOOL_PRIORITY_NOTE,
|
|
2203
|
+
].join("\n\n"),
|
|
1955
2204
|
);
|
|
1956
2205
|
if (stagedName) {
|
|
1957
2206
|
agent = stagedName;
|
|
@@ -1986,7 +2235,7 @@ async function runTurnDriver(
|
|
|
1986
2235
|
// is ACP-only.
|
|
1987
2236
|
const requestConversation = redeliveryConversation ?? existing?.conversationId ?? null;
|
|
1988
2237
|
const acpFallback =
|
|
1989
|
-
deps.engine === "acp" && requestConversation && !resume && late.length === 0
|
|
2238
|
+
!syncTurn && deps.engine === "acp" && requestConversation && !resume && late.length === 0
|
|
1990
2239
|
? (() => {
|
|
1991
2240
|
const fbSys = config.systemPrompt
|
|
1992
2241
|
? getCurrentSystemPrompt(context.messages) || undefined
|
|
@@ -2002,7 +2251,7 @@ async function runTurnDriver(
|
|
|
2002
2251
|
// Both features off: the variant would equal the plain prompt.
|
|
2003
2252
|
if (!fbSys && !freshDigest?.text) return undefined;
|
|
2004
2253
|
return {
|
|
2005
|
-
prompt: buildFullPrompt(fbSys, "", deliveredPrompt) + stageImageNote(runImages),
|
|
2254
|
+
prompt: buildFullPrompt(fbSys, "", deliveredPrompt, { codemodeOnly: codemodeNote }) + stageImageNote(runImages),
|
|
2006
2255
|
contextBlock: freshDigest?.text
|
|
2007
2256
|
? {
|
|
2008
2257
|
uri: `urn:pi-bridge:context-digest/fresh/${messageCount}`,
|
|
@@ -2015,42 +2264,53 @@ async function runTurnDriver(
|
|
|
2015
2264
|
const fullPrompt =
|
|
2016
2265
|
(late.length > 0
|
|
2017
2266
|
? buildLateResultPrompt(late, deliveredPrompt || undefined)
|
|
2018
|
-
: buildFullPrompt(sysPrompt, embeddedDigest ? "" : digestFinal, deliveredPrompt)) +
|
|
2267
|
+
: buildFullPrompt(sysPrompt, embeddedDigest ? "" : digestFinal, deliveredPrompt, { codemodeOnly: codemodeNote })) +
|
|
2019
2268
|
stageImageNote(runImages);
|
|
2020
|
-
|
|
2021
|
-
|
|
2022
|
-
|
|
2023
|
-
|
|
2024
|
-
|
|
2025
|
-
|
|
2026
|
-
|
|
2027
|
-
|
|
2028
|
-
|
|
2029
|
-
|
|
2030
|
-
|
|
2031
|
-
|
|
2032
|
-
|
|
2033
|
-
|
|
2034
|
-
|
|
2035
|
-
|
|
2036
|
-
|
|
2037
|
-
|
|
2038
|
-
|
|
2039
|
-
|
|
2040
|
-
|
|
2041
|
-
|
|
2042
|
-
|
|
2043
|
-
|
|
2044
|
-
|
|
2045
|
-
|
|
2046
|
-
|
|
2047
|
-
|
|
2048
|
-
|
|
2049
|
-
|
|
2050
|
-
|
|
2269
|
+
if (!syncTurn) {
|
|
2270
|
+
try {
|
|
2271
|
+
handle = await deps.driver.run({
|
|
2272
|
+
cwd,
|
|
2273
|
+
model: agyModel,
|
|
2274
|
+
effort,
|
|
2275
|
+
mode: config.mode,
|
|
2276
|
+
skipPermissions: config.skipPermissions,
|
|
2277
|
+
timeoutMin: config.turnTimeoutMin,
|
|
2278
|
+
inactivityMin: config.inactivityTimeoutMin,
|
|
2279
|
+
conversationId: redeliveryConversation ?? existing?.conversationId ?? null,
|
|
2280
|
+
prompt: fullPrompt,
|
|
2281
|
+
images: runImages.length > 0 ? runImages : undefined,
|
|
2282
|
+
agent,
|
|
2283
|
+
fallback: acpFallback,
|
|
2284
|
+
contextBlock: embeddedDigest
|
|
2285
|
+
? {
|
|
2286
|
+
uri: `urn:pi-bridge:context-digest/${messageCount}`,
|
|
2287
|
+
text: `${DIGEST_PREAMBLE}\n\n${embeddedDigest}`,
|
|
2288
|
+
}
|
|
2289
|
+
: undefined,
|
|
2290
|
+
signal: options?.signal,
|
|
2291
|
+
});
|
|
2292
|
+
if (!ephemeral) handoffRuntime?.mode.set(key, "digest");
|
|
2293
|
+
digestDispatched = true;
|
|
2294
|
+
} catch (err) {
|
|
2295
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
2296
|
+
// Release stranded claims: the delivery never started, so the next
|
|
2297
|
+
// pass must find them undelivered (tombstone-borne items have no
|
|
2298
|
+
// callId and stay consumed, as before).
|
|
2299
|
+
for (const l of late) if (l.callId) deps.roundTrips.unclaim(l.callId);
|
|
2300
|
+
deps.log?.("turn-error", { reason: "driver-start-failed", error: msg }, "error");
|
|
2301
|
+
finalize(stream, blocks, "error", `agy failed to start: ${msg}`);
|
|
2302
|
+
return;
|
|
2303
|
+
}
|
|
2051
2304
|
}
|
|
2052
2305
|
}
|
|
2053
2306
|
|
|
2307
|
+
if (!handle) {
|
|
2308
|
+
// Unreachable in practice: every non-finalized path above dispatched a
|
|
2309
|
+
// turn. Fail visibly instead of arguing with the type checker.
|
|
2310
|
+
finalize(stream, blocks, "error", "agy turn was not dispatched");
|
|
2311
|
+
return;
|
|
2312
|
+
}
|
|
2313
|
+
|
|
2054
2314
|
ensureStarted(stream, blocks);
|
|
2055
2315
|
const diffCtx = new TurnDiffContext(createExecGitOps());
|
|
2056
2316
|
// Background latch: one WaitMsBeforeAsync-shaped native call this turn is
|
|
@@ -2090,18 +2350,28 @@ async function runTurnDriver(
|
|
|
2090
2350
|
// recreated a conversation, so the snapshot id is the real one, and
|
|
2091
2351
|
// the staged agent must move with the binding or a stream-json resume
|
|
2092
2352
|
// re-runs without its carrier-agent profile.
|
|
2093
|
-
if (!ephemeral && !
|
|
2353
|
+
if (!ephemeral && !rotationGuardArmed() && (syncTurn || !existing)) {
|
|
2094
2354
|
const parkedConv = deps.driver.snapshot().conversationId;
|
|
2095
2355
|
if (parkedConv) {
|
|
2096
|
-
|
|
2097
|
-
|
|
2098
|
-
|
|
2099
|
-
|
|
2100
|
-
|
|
2101
|
-
|
|
2102
|
-
|
|
2103
|
-
|
|
2104
|
-
|
|
2356
|
+
if (syncTurn) {
|
|
2357
|
+
// Sync persists the zeroed contract with the adopted binding;
|
|
2358
|
+
// a rebuild that parked already carried the compaction summary
|
|
2359
|
+
// as history, so the latch has no second consumer.
|
|
2360
|
+
syncTurn.adoptBinding(parkedConv);
|
|
2361
|
+
const rec = syncTurn.record();
|
|
2362
|
+
if (rec.conversationId) store.set(key, { ...rec, conversationId: rec.conversationId });
|
|
2363
|
+
if (syncTurn.freshConversation) deps.pendingCompactionHandoff?.delete(key);
|
|
2364
|
+
} else {
|
|
2365
|
+
store.set(key, {
|
|
2366
|
+
conversationId: parkedConv,
|
|
2367
|
+
lastStepIdx: -1,
|
|
2368
|
+
lastMessageCount: nextCount,
|
|
2369
|
+
digestBoundary: nextBoundary,
|
|
2370
|
+
digestSummaryId: settleSummaryId,
|
|
2371
|
+
});
|
|
2372
|
+
deps.pendingCompactionHandoff?.delete(key);
|
|
2373
|
+
if (stagedAgentName) stagedAgentByConversation.set(parkedConv, stagedAgentName);
|
|
2374
|
+
}
|
|
2105
2375
|
}
|
|
2106
2376
|
}
|
|
2107
2377
|
return;
|
|
@@ -2173,41 +2443,153 @@ async function runTurnDriver(
|
|
|
2173
2443
|
// fix: sweep and deliver as a late run in the same conversation. Single
|
|
2174
2444
|
// shot: claims are single-use, so a re-delivered strand cannot reappear
|
|
2175
2445
|
// here; a late run that parks hands recovery to the next pi pass.
|
|
2446
|
+
// A late-start failure must invalidate the sync contract below: its
|
|
2447
|
+
// checkpoint would claim the steer agy never received.
|
|
2448
|
+
let lateStartFailed = false;
|
|
2176
2449
|
if (!ephemeral && isContinuation && outcome.status === "OK" && !outcome.aborted) {
|
|
2177
|
-
const more = collectStranded();
|
|
2178
|
-
|
|
2450
|
+
const more = steerLedFresh ? [] : collectStranded();
|
|
2451
|
+
// Steered messages join the same late run: pi delivered them into the
|
|
2452
|
+
// context while the turn was parked and the reentry pass sent nothing
|
|
2453
|
+
// to agy, so this sweep is the only delivery window left.
|
|
2454
|
+
if (!steerLedFresh && (more.length > 0 || steered.length > 0)) {
|
|
2179
2455
|
const conv = redeliveryConversation ?? outcome.conversationId ?? existing?.conversationId ?? null;
|
|
2180
|
-
|
|
2181
|
-
const
|
|
2182
|
-
|
|
2183
|
-
|
|
2184
|
-
|
|
2185
|
-
|
|
2186
|
-
|
|
2187
|
-
|
|
2188
|
-
|
|
2189
|
-
timeoutMin: config.turnTimeoutMin,
|
|
2190
|
-
inactivityMin: config.inactivityTimeoutMin,
|
|
2191
|
-
conversationId: conv,
|
|
2192
|
-
prompt: buildLateResultPrompt(more) + stageImageNote(moreImages),
|
|
2193
|
-
images: moreImages.length > 0 ? moreImages : undefined,
|
|
2194
|
-
agent: config.agent ?? (conv ? stagedAgentByConversation.get(conv) : undefined),
|
|
2195
|
-
signal: options?.signal,
|
|
2196
|
-
});
|
|
2197
|
-
if ((await drainTurn(lateHandle)) === "parked") return;
|
|
2198
|
-
outcome = await lateHandle.outcome;
|
|
2199
|
-
} catch (err) {
|
|
2200
|
-
// Release the claims so the next pass can retry the delivery.
|
|
2201
|
-
for (const l of more) if (l.callId) deps.roundTrips.unclaim(l.callId);
|
|
2456
|
+
const steerText = steered.map((s) => s.text).filter(Boolean).join("\n\n");
|
|
2457
|
+
const latePrompt = more.length > 0 ? buildLateResultPrompt(more, steerText || undefined) : steerText;
|
|
2458
|
+
// stream-json silently drops any prompt past the cap (issue #2) and
|
|
2459
|
+
// the dropped turn leaves the conversation unresponsive: slice the
|
|
2460
|
+
// steer visibly instead of killing it.
|
|
2461
|
+
const lateBudget = STREAM_JSON_PROMPT_CAP - STREAM_JSON_PROMPT_MARGIN;
|
|
2462
|
+
let deliveredLatePrompt = latePrompt;
|
|
2463
|
+
if ((deps.engine ?? config.engine) !== "acp" && Buffer.byteLength(latePrompt, "utf8") > lateBudget) {
|
|
2464
|
+
deliveredLatePrompt = `[truncated]\n${Buffer.from(latePrompt, "utf8").subarray(0, Math.max(0, lateBudget - 32)).toString("utf8")}`;
|
|
2202
2465
|
deps.log?.(
|
|
2203
|
-
"turn-
|
|
2204
|
-
{ reason: "
|
|
2205
|
-
"
|
|
2466
|
+
"turn-warning",
|
|
2467
|
+
{ reason: "steer-prompt-truncated", bytes: Buffer.byteLength(latePrompt, "utf8"), budget: lateBudget },
|
|
2468
|
+
"warn",
|
|
2206
2469
|
);
|
|
2207
2470
|
}
|
|
2471
|
+
const moreImages = [...more.flatMap((s) => s.images ?? []), ...steered.flatMap((s) => s.images)];
|
|
2472
|
+
deps.log?.(
|
|
2473
|
+
"steered-redelivery-turn",
|
|
2474
|
+
{ tools: more.map((s) => s.name), steered: steered.length, conversation: conv },
|
|
2475
|
+
"info",
|
|
2476
|
+
);
|
|
2477
|
+
if (!conv) {
|
|
2478
|
+
// Unbindable: a brand-new conversation would answer the steer with
|
|
2479
|
+
// zero context. Release the claims and hold the watermark - the
|
|
2480
|
+
// digest re-offers the steer once a conversation is bound.
|
|
2481
|
+
for (const l of more) if (l.callId) deps.roundTrips.unclaim(l.callId);
|
|
2482
|
+
lateStartFailed = true;
|
|
2483
|
+
if (steered.length > 0) {
|
|
2484
|
+
nextCount = steered[0].index;
|
|
2485
|
+
nextBoundary = boundaryFingerprint(context.messages[steered[0].index - 1]);
|
|
2486
|
+
}
|
|
2487
|
+
deps.log?.("turn-warning", { reason: "steer-redelivery-unbound", steered: steered.length }, "warn");
|
|
2488
|
+
} else {
|
|
2489
|
+
try {
|
|
2490
|
+
const lateHandle = await deps.driver.run({
|
|
2491
|
+
cwd,
|
|
2492
|
+
model: agyModel,
|
|
2493
|
+
effort,
|
|
2494
|
+
mode: config.mode,
|
|
2495
|
+
skipPermissions: config.skipPermissions,
|
|
2496
|
+
timeoutMin: config.turnTimeoutMin,
|
|
2497
|
+
inactivityMin: config.inactivityTimeoutMin,
|
|
2498
|
+
conversationId: conv,
|
|
2499
|
+
prompt: deliveredLatePrompt + stageImageNote(moreImages),
|
|
2500
|
+
images: moreImages.length > 0 ? moreImages : undefined,
|
|
2501
|
+
agent: config.agent ?? (conv ? stagedAgentByConversation.get(conv) : undefined),
|
|
2502
|
+
signal: options?.signal,
|
|
2503
|
+
});
|
|
2504
|
+
// Accepted by agy from here on: a parked late run hands
|
|
2505
|
+
// recovery to the next pass, which must not re-collect it.
|
|
2506
|
+
const cursor = steerCursors.get(key);
|
|
2507
|
+
if (cursor && steered.length > 0) cursor.deliveredThrough = steered[steered.length - 1].index + 1;
|
|
2508
|
+
if ((await drainTurn(lateHandle)) === "parked") return;
|
|
2509
|
+
outcome = await lateHandle.outcome;
|
|
2510
|
+
} catch (err) {
|
|
2511
|
+
// Release the claims so the next pass can retry the delivery.
|
|
2512
|
+
for (const l of more) if (l.callId) deps.roundTrips.unclaim(l.callId);
|
|
2513
|
+
// A steer has no registry to re-arm, only the digest window: hold
|
|
2514
|
+
// the watermark AND the boundary fingerprint at the first
|
|
2515
|
+
// undelivered message, or the next turn reads the mismatched
|
|
2516
|
+
// boundary as a mutated transcript and resets to full history.
|
|
2517
|
+
lateStartFailed = true;
|
|
2518
|
+
if (steered.length > 0) {
|
|
2519
|
+
nextCount = steered[0].index;
|
|
2520
|
+
nextBoundary = boundaryFingerprint(context.messages[steered[0].index - 1]);
|
|
2521
|
+
}
|
|
2522
|
+
deps.log?.(
|
|
2523
|
+
"turn-error",
|
|
2524
|
+
{ reason: "redelivery-start-failed", error: err instanceof Error ? err.message : String(err) },
|
|
2525
|
+
"error",
|
|
2526
|
+
);
|
|
2527
|
+
}
|
|
2528
|
+
}
|
|
2208
2529
|
}
|
|
2209
2530
|
}
|
|
2210
|
-
|
|
2531
|
+
// Sync settle: the orchestrator owns the record write (zeroed contract),
|
|
2532
|
+
// so the digest settle below is bypassed entirely. A continuation of a
|
|
2533
|
+
// parked sync turn reconstructs the coordinator from the record (the
|
|
2534
|
+
// live re-attach fires no hooks) and marks it dispatched so the two-step
|
|
2535
|
+
// settle can terminal. A digest redelivery over a sync-latched session
|
|
2536
|
+
// (dead handle, deadIds) settles digest-shaped instead.
|
|
2537
|
+
const syncContract =
|
|
2538
|
+
syncTurn !== undefined ||
|
|
2539
|
+
(isContinuation && !digestDispatched && !ephemeral && deps.handoffRuntime?.mode.get(key) === "sync");
|
|
2540
|
+
if (syncContract && !ephemeral) {
|
|
2541
|
+
try {
|
|
2542
|
+
const settleSync =
|
|
2543
|
+
syncTurn ??
|
|
2544
|
+
(() => {
|
|
2545
|
+
const recon = new AcpHistorySync(context.messages, existing, {
|
|
2546
|
+
continuation: isContinuation,
|
|
2547
|
+
isBacklogShape: isBacklogUserShape,
|
|
2548
|
+
});
|
|
2549
|
+
recon.bound(key);
|
|
2550
|
+
recon.dispatching();
|
|
2551
|
+
return recon;
|
|
2552
|
+
})();
|
|
2553
|
+
const result = settleSync.finish(
|
|
2554
|
+
{
|
|
2555
|
+
// A late-start failure leaves the steer undelivered: a terminal
|
|
2556
|
+
// checkpoint would claim it. Invalidate so the next turn re-plans
|
|
2557
|
+
// and the rebuild re-ships the steer as the newest user entry.
|
|
2558
|
+
ok: outcome.status === "OK" && !lateStartFailed,
|
|
2559
|
+
conversationId: outcome.conversationId ?? null,
|
|
2560
|
+
aborted: outcome.aborted,
|
|
2561
|
+
promptAttempted: outcome.promptAttempted,
|
|
2562
|
+
promptTerminal: outcome.promptTerminal,
|
|
2563
|
+
},
|
|
2564
|
+
blocks.partial,
|
|
2565
|
+
context.messages,
|
|
2566
|
+
existing?.conversationId,
|
|
2567
|
+
);
|
|
2568
|
+
deps.log?.(
|
|
2569
|
+
"sync-settle",
|
|
2570
|
+
{
|
|
2571
|
+
key,
|
|
2572
|
+
settled: result.settled,
|
|
2573
|
+
...("reason" in result ? { reason: result.reason } : {}),
|
|
2574
|
+
conversation: outcome.conversationId,
|
|
2575
|
+
},
|
|
2576
|
+
"info",
|
|
2577
|
+
);
|
|
2578
|
+
const record = settleSync.record();
|
|
2579
|
+
if (record.conversationId && !rotationGuardArmed()) {
|
|
2580
|
+
store.set(key, { ...record, conversationId: record.conversationId });
|
|
2581
|
+
// A rebuild shipped the compaction summary as history; the one-shot
|
|
2582
|
+
// latch has no second consumer.
|
|
2583
|
+
if (settleSync.freshConversation) deps.pendingCompactionHandoff?.delete(key);
|
|
2584
|
+
}
|
|
2585
|
+
} catch (err) {
|
|
2586
|
+
// A settle invariant failure must not surface as an unhandled
|
|
2587
|
+
// rejection (the caller is void): dropping the record forces a
|
|
2588
|
+
// named rebuild next turn, the safe direction.
|
|
2589
|
+
deps.log?.("sync-settle-failed", { key, error: err instanceof Error ? err.message : String(err) }, "error");
|
|
2590
|
+
store.delete(key);
|
|
2591
|
+
}
|
|
2592
|
+
} else if (!ephemeral && outcome.conversationId) {
|
|
2211
2593
|
// A different id than the stored one means the driver recreated the
|
|
2212
2594
|
// conversation under us (ACP session-load fallback, stream-json CLI
|
|
2213
2595
|
// dropping a stale --conversation). The recreated conversation has seen
|
|
@@ -2229,6 +2611,10 @@ async function runTurnDriver(
|
|
|
2229
2611
|
lastMessageCount: nextCount,
|
|
2230
2612
|
digestBoundary: nextBoundary,
|
|
2231
2613
|
digestSummaryId: settleSummaryId,
|
|
2614
|
+
// The churn latch must survive digest turns (store.set
|
|
2615
|
+
// replaces the record), or the gate re-opens next turn and
|
|
2616
|
+
// the session alternates rebuild/digest forever.
|
|
2617
|
+
...(existing?.sync?.digestFallback ? { sync: existing.sync } : {}),
|
|
2232
2618
|
});
|
|
2233
2619
|
deps.pendingCompactionHandoff?.delete(key);
|
|
2234
2620
|
if (stagedAgentName) stagedAgentByConversation.set(outcome.conversationId, stagedAgentName);
|
|
@@ -2274,6 +2660,13 @@ export function createStreamSimple(
|
|
|
2274
2660
|
deps: StreamSimpleDeps,
|
|
2275
2661
|
): (model: Model<Api>, context: TranscriptContext, options?: SimpleStreamOptions) => AssistantMessageEventStream {
|
|
2276
2662
|
const { entries, store, roundTrips } = deps;
|
|
2663
|
+
// Per-provider handoff runtime: the park-time mode latch (continuations
|
|
2664
|
+
// must settle under the same contract as the parked turn) and the churn
|
|
2665
|
+
// gate's consecutive-rebuild counter, both keyed by session key.
|
|
2666
|
+
const handoffRuntime = {
|
|
2667
|
+
mode: new Map<string, "digest" | "sync">(),
|
|
2668
|
+
rebuildStreak: new Map<string, number>(),
|
|
2669
|
+
};
|
|
2277
2670
|
|
|
2278
2671
|
return function streamSimple(model, context, options) {
|
|
2279
2672
|
const stream = createAssistantMessageEventStream();
|
|
@@ -2352,6 +2745,8 @@ export function createStreamSimple(
|
|
|
2352
2745
|
onNativeBackground: deps.onNativeBackground,
|
|
2353
2746
|
roster: deps.roster,
|
|
2354
2747
|
pendingCompactionHandoff: deps.pendingCompactionHandoff,
|
|
2748
|
+
handoffRuntime,
|
|
2749
|
+
hasActiveTool: deps.hasActiveTool,
|
|
2355
2750
|
// Record the engine of the driver that will ACTUALLY run: if the
|
|
2356
2751
|
// ACP driver is absent, the config switch falls back to stream,
|
|
2357
2752
|
// and keying the session as @acp would store a stream
|