@estebanforge/pi-antigravity-bridge 1.14.0 → 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/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";
@@ -242,19 +243,28 @@ export const SYSTEM_PROMPT_END = "[END SYSTEM PROMPT]";
242
243
  * the user's machine must go through the bridge. Rides the systemPrompt
243
244
  * gate: the note ships only when the system prompt ships. */
244
245
  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, execute). 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
+ "[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
247
 
247
248
  /** Assemble the full agy prompt: system prompt block, pi-side digest, user
248
249
  * prompt. Empty parts are dropped. Pure; exported for unit testing.
249
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
+
250
258
  export function buildFullPrompt(
251
259
  systemPrompt: string | undefined,
252
260
  digest: string,
253
261
  prompt: string,
262
+ options?: { codemodeOnly?: boolean },
254
263
  ): string {
255
264
  const parts: string[] = [];
256
265
  if (systemPrompt) {
257
- parts.push(`${SYSTEM_PROMPT_PREAMBLE}\n\n${systemPrompt}\n\n${TOOL_PRIORITY_NOTE}\n\n${SYSTEM_PROMPT_END}`);
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}`);
258
268
  }
259
269
  if (digest) {
260
270
  parts.push(`${DIGEST_PREAMBLE}\n\n${digest}`);
@@ -672,6 +682,18 @@ export interface StreamSimpleDeps {
672
682
  /** Session keys rotated on `session_compact` awaiting a one-shot
673
683
  * compaction handoff into a fresh agy conversation. */
674
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
+ };
675
697
  /** Daily file log sink (src/daily-log.ts). Records pre-dispatch turn
676
698
  * errors that never create a driver turn (and so never reach onTurnEnd). */
677
699
  log?: (event: string, data?: unknown, level?: "debug" | "info" | "warn" | "error") => void;
@@ -1377,6 +1399,13 @@ export interface DriverDeps {
1377
1399
  pendingCompactionHandoff?: Set<string>;
1378
1400
  /** Active engine (config), for engine-scoped session keys. */
1379
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
+ };
1380
1409
  /** Daily file log sink for pre-dispatch errors (see StreamSimpleDeps). */
1381
1410
  log?: (event: string, data?: unknown, level?: "debug" | "info" | "warn" | "error") => void;
1382
1411
  }
@@ -1734,6 +1763,30 @@ async function runTurnDriver(
1734
1763
  const effort = entry?.efforts?.length ? toAgyEffort(options?.reasoning, entry.efforts) : undefined;
1735
1764
 
1736
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;
1737
1790
  // Name of the carrier agent staged for THIS turn's fresh conversation, if
1738
1791
  // any. Recorded into stagedAgentByConversation once the outcome binds the
1739
1792
  // conversation id, so later gate-closed turns pass the same agent.
@@ -1865,6 +1918,106 @@ async function runTurnDriver(
1865
1918
  }
1866
1919
  }
1867
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
+ }
1868
2021
  const promptBytes = Buffer.byteLength(deliveredPrompt, "utf8");
1869
2022
  // A truncated run ships alone: the digest budget is spent, and a
1870
2023
  // marker-only digest beside a sliced prompt is noise that also breaks
@@ -1872,6 +2025,7 @@ async function runTurnDriver(
1872
2025
  const wantDigest = (config.digest || compactionHandoff || compactionResume) && !runTruncated;
1873
2026
  const maxChars = digestMaxCharsForEngine(engine, promptBytes);
1874
2027
  const digestRes =
2028
+ !syncTurn &&
1875
2029
  wantDigest && maxChars !== null && late.length === 0 && !resume
1876
2030
  ? buildContextDigestResult(context.messages, watermark, {
1877
2031
  bound: Boolean(existing?.conversationId),
@@ -1906,20 +2060,21 @@ async function runTurnDriver(
1906
2060
  nextCount = existing?.lastMessageCount ?? watermark;
1907
2061
  nextBoundary = existing?.digestBoundary;
1908
2062
  }
1909
- deps.log?.(
1910
- "digest",
1911
- {
1912
- engine,
1913
- bound: Boolean(existing?.conversationId),
1914
- maxChars,
1915
- bytes: digestFinal ? Buffer.byteLength(digestFinal, "utf8") : 0,
1916
- windowStart: digestRes?.windowStart,
1917
- windowEnd: digestRes?.windowEnd,
1918
- deliveredFrom: digestRes?.deliveredFrom,
1919
- shipped: Boolean(digestFinal),
1920
- },
1921
- digestDropped ? "warn" : "info",
1922
- );
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
+ );
1923
2078
  // The delivered summary id persists only when a digest actually shipped:
1924
2079
  // late/resume/budget-skipped turns carry the previous id forward so the
1925
2080
  // summary is not lost to a turn that never delivered it.
@@ -1951,7 +2106,11 @@ async function runTurnDriver(
1951
2106
  if (deps.engine !== "acp") {
1952
2107
  if (rawSysPrompt && !config.agent) {
1953
2108
  const stagedName = stageSyspromptAgent(
1954
- [SYSTEM_PROMPT_PREAMBLE, rawSysPrompt, TOOL_PRIORITY_NOTE].join("\n\n"),
2109
+ [
2110
+ SYSTEM_PROMPT_PREAMBLE,
2111
+ rawSysPrompt,
2112
+ codemodeNote ? `${TOOL_PRIORITY_NOTE}\n\n${CODEMODE_NOTE}` : TOOL_PRIORITY_NOTE,
2113
+ ].join("\n\n"),
1955
2114
  );
1956
2115
  if (stagedName) {
1957
2116
  agent = stagedName;
@@ -1986,7 +2145,7 @@ async function runTurnDriver(
1986
2145
  // is ACP-only.
1987
2146
  const requestConversation = redeliveryConversation ?? existing?.conversationId ?? null;
1988
2147
  const acpFallback =
1989
- deps.engine === "acp" && requestConversation && !resume && late.length === 0
2148
+ !syncTurn && deps.engine === "acp" && requestConversation && !resume && late.length === 0
1990
2149
  ? (() => {
1991
2150
  const fbSys = config.systemPrompt
1992
2151
  ? getCurrentSystemPrompt(context.messages) || undefined
@@ -2002,7 +2161,7 @@ async function runTurnDriver(
2002
2161
  // Both features off: the variant would equal the plain prompt.
2003
2162
  if (!fbSys && !freshDigest?.text) return undefined;
2004
2163
  return {
2005
- prompt: buildFullPrompt(fbSys, "", deliveredPrompt) + stageImageNote(runImages),
2164
+ prompt: buildFullPrompt(fbSys, "", deliveredPrompt, { codemodeOnly: codemodeNote }) + stageImageNote(runImages),
2006
2165
  contextBlock: freshDigest?.text
2007
2166
  ? {
2008
2167
  uri: `urn:pi-bridge:context-digest/fresh/${messageCount}`,
@@ -2015,42 +2174,53 @@ async function runTurnDriver(
2015
2174
  const fullPrompt =
2016
2175
  (late.length > 0
2017
2176
  ? buildLateResultPrompt(late, deliveredPrompt || undefined)
2018
- : buildFullPrompt(sysPrompt, embeddedDigest ? "" : digestFinal, deliveredPrompt)) +
2177
+ : buildFullPrompt(sysPrompt, embeddedDigest ? "" : digestFinal, deliveredPrompt, { codemodeOnly: codemodeNote })) +
2019
2178
  stageImageNote(runImages);
2020
- try {
2021
- handle = await deps.driver.run({
2022
- cwd,
2023
- model: agyModel,
2024
- effort,
2025
- mode: config.mode,
2026
- skipPermissions: config.skipPermissions,
2027
- timeoutMin: config.turnTimeoutMin,
2028
- inactivityMin: config.inactivityTimeoutMin,
2029
- conversationId: redeliveryConversation ?? existing?.conversationId ?? null,
2030
- prompt: fullPrompt,
2031
- images: runImages.length > 0 ? runImages : undefined,
2032
- agent,
2033
- fallback: acpFallback,
2034
- contextBlock: embeddedDigest
2035
- ? {
2036
- uri: `urn:pi-bridge:context-digest/${messageCount}`,
2037
- text: `${DIGEST_PREAMBLE}\n\n${embeddedDigest}`,
2038
- }
2039
- : undefined,
2040
- signal: options?.signal,
2041
- });
2042
- } catch (err) {
2043
- const msg = err instanceof Error ? err.message : String(err);
2044
- // Release stranded claims: the delivery never started, so the next
2045
- // pass must find them undelivered (tombstone-borne items have no
2046
- // callId and stay consumed, as before).
2047
- for (const l of late) if (l.callId) deps.roundTrips.unclaim(l.callId);
2048
- deps.log?.("turn-error", { reason: "driver-start-failed", error: msg }, "error");
2049
- finalize(stream, blocks, "error", `agy failed to start: ${msg}`);
2050
- return;
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
+ }
2051
2214
  }
2052
2215
  }
2053
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
+
2054
2224
  ensureStarted(stream, blocks);
2055
2225
  const diffCtx = new TurnDiffContext(createExecGitOps());
2056
2226
  // Background latch: one WaitMsBeforeAsync-shaped native call this turn is
@@ -2090,18 +2260,28 @@ async function runTurnDriver(
2090
2260
  // recreated a conversation, so the snapshot id is the real one, and
2091
2261
  // the staged agent must move with the binding or a stream-json resume
2092
2262
  // re-runs without its carrier-agent profile.
2093
- if (!ephemeral && !existing && !rotationGuardArmed()) {
2263
+ if (!ephemeral && !rotationGuardArmed() && (syncTurn || !existing)) {
2094
2264
  const parkedConv = deps.driver.snapshot().conversationId;
2095
2265
  if (parkedConv) {
2096
- store.set(key, {
2097
- conversationId: parkedConv,
2098
- lastStepIdx: -1,
2099
- lastMessageCount: nextCount,
2100
- digestBoundary: nextBoundary,
2101
- digestSummaryId: settleSummaryId,
2102
- });
2103
- deps.pendingCompactionHandoff?.delete(key);
2104
- if (stagedAgentName) stagedAgentByConversation.set(parkedConv, stagedAgentName);
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
+ }
2105
2285
  }
2106
2286
  }
2107
2287
  return;
@@ -2207,7 +2387,65 @@ async function runTurnDriver(
2207
2387
  }
2208
2388
  }
2209
2389
  }
2210
- if (!ephemeral && outcome.conversationId) {
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) {
2211
2449
  // A different id than the stored one means the driver recreated the
2212
2450
  // conversation under us (ACP session-load fallback, stream-json CLI
2213
2451
  // dropping a stale --conversation). The recreated conversation has seen
@@ -2229,6 +2467,10 @@ async function runTurnDriver(
2229
2467
  lastMessageCount: nextCount,
2230
2468
  digestBoundary: nextBoundary,
2231
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 } : {}),
2232
2474
  });
2233
2475
  deps.pendingCompactionHandoff?.delete(key);
2234
2476
  if (stagedAgentName) stagedAgentByConversation.set(outcome.conversationId, stagedAgentName);
@@ -2274,6 +2516,13 @@ export function createStreamSimple(
2274
2516
  deps: StreamSimpleDeps,
2275
2517
  ): (model: Model<Api>, context: TranscriptContext, options?: SimpleStreamOptions) => AssistantMessageEventStream {
2276
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
+ };
2277
2526
 
2278
2527
  return function streamSimple(model, context, options) {
2279
2528
  const stream = createAssistantMessageEventStream();
@@ -2352,6 +2601,8 @@ export function createStreamSimple(
2352
2601
  onNativeBackground: deps.onNativeBackground,
2353
2602
  roster: deps.roster,
2354
2603
  pendingCompactionHandoff: deps.pendingCompactionHandoff,
2604
+ handoffRuntime,
2605
+ hasActiveTool: deps.hasActiveTool,
2355
2606
  // Record the engine of the driver that will ACTUALLY run: if the
2356
2607
  // ACP driver is absent, the config switch falls back to stream,
2357
2608
  // and keying the session as @acp would store a stream
package/src/sessions.ts CHANGED
@@ -11,6 +11,7 @@
11
11
  import fs from "node:fs";
12
12
  import path from "node:path";
13
13
  import { bridgeDir } from "./config.js";
14
+ import { narrowSessionSync, type SessionSyncState } from "./history-sync.js";
14
15
 
15
16
  function defaultStorePath(): string {
16
17
  return path.join(bridgeDir(), "sessions.json");
@@ -35,6 +36,11 @@ export interface AgySession {
35
36
  * builder neither re-injects that summary nor restarts its window on
36
37
  * it. Optional/absent when no compaction existed at write time. */
37
38
  digestSummaryId?: string;
39
+ /** History-sync protocol journal (handoff = "sync"). Absent on digest
40
+ * records and on records predating the sync mode. Zeroed digest
41
+ * watermark fields accompany it (the sync persist contract), so a
42
+ * later flip back to digest re-offers the backlog once, safely. */
43
+ sync?: SessionSyncState;
38
44
  }
39
45
 
40
46
  type StoreMap = Record<string, AgySession>;
@@ -56,12 +62,17 @@ function narrowStoreMap(parsed: unknown): StoreMap {
56
62
  const mc = (value as { lastMessageCount?: unknown }).lastMessageCount;
57
63
  const db = (value as { digestBoundary?: unknown }).digestBoundary;
58
64
  const dci = (value as { digestSummaryId?: unknown }).digestSummaryId;
65
+ // Malformed sync journals narrow to an invalid-sync-state marker
66
+ // (never throws; self-heals via a named rebuild), so the field is
67
+ // kept but flagged.
68
+ const sync = narrowSessionSync((value as { sync?: unknown }).sync);
59
69
  clean[key] = {
60
70
  conversationId,
61
71
  lastStepIdx: typeof idx === "number" && Number.isFinite(idx) ? idx : -1,
62
72
  lastMessageCount: typeof mc === "number" && Number.isFinite(mc) ? mc : 0,
63
73
  ...(typeof db === "string" ? { digestBoundary: db } : {}),
64
74
  ...(typeof dci === "string" ? { digestSummaryId: dci } : {}),
75
+ ...(sync ? { sync } : {}),
65
76
  };
66
77
  }
67
78
  return clean;
@@ -105,6 +116,7 @@ export class SessionStore {
105
116
  lastMessageCount: s.lastMessageCount ?? 0,
106
117
  ...(s.digestBoundary !== undefined ? { digestBoundary: s.digestBoundary } : {}),
107
118
  ...(s.digestSummaryId !== undefined ? { digestSummaryId: s.digestSummaryId } : {}),
119
+ ...(s.sync !== undefined ? { sync: structuredClone(s.sync) } : {}),
108
120
  };
109
121
  }
110
122