@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/config.ts
CHANGED
|
@@ -49,8 +49,8 @@ export type Engine = "stream-json" | "acp";
|
|
|
49
49
|
* fall back here. Startup checks that the required agy CLI is available. */
|
|
50
50
|
export const DEFAULT_ENGINE: Engine = "acp";
|
|
51
51
|
export type AgyMode = "accept-edits" | "plan";
|
|
52
|
-
export type ThinkingTier = "low" | "medium" | "high";
|
|
53
|
-
export type BridgeTools = "none" | "mcp" | "all";
|
|
52
|
+
export type ThinkingTier = "low" | "medium" | "high" | "xhigh";
|
|
53
|
+
export type BridgeTools = "none" | "mcp" | "all" | "codemode";
|
|
54
54
|
|
|
55
55
|
/** How ACP turns report token usage while Gate B stands (agy sends none).
|
|
56
56
|
* "estimate" (default): word-boundary regex over prompt/response/thought
|
|
@@ -104,6 +104,10 @@ export interface AgyConfig {
|
|
|
104
104
|
/** Official-server ACP engine options (used when engine = "acp"). */
|
|
105
105
|
acp: AcpConfig;
|
|
106
106
|
mode: AgyMode;
|
|
107
|
+
/** Fresh-conversation handoff style. "digest" (default) ships the bounded
|
|
108
|
+
* context digest; "sync" ships canonical history checkpoints (ACP only —
|
|
109
|
+
* stream-json keeps the digest path regardless). AGY_HANDOFF=sync opts in. */
|
|
110
|
+
handoff: "digest" | "sync";
|
|
107
111
|
/** Fail-closed kill switch for provider turns. ON = every provider turn
|
|
108
112
|
* is refused visibly: the agy CLI has no review-only enforcement on any
|
|
109
113
|
* path (probed 2026-10-07, upstream #1181: plan mode stages a plan and
|
|
@@ -175,6 +179,11 @@ export interface AgyConfig {
|
|
|
175
179
|
* message, and a conversation opened mid-session starts without prior
|
|
176
180
|
* pi-side context. */
|
|
177
181
|
digest: boolean;
|
|
182
|
+
/** Migration marker (issue #25): set once when a stale persisted
|
|
183
|
+
* digest:false from the pre-default-flip era is upgraded to the ON
|
|
184
|
+
* default. Presence keeps later deliberate `/agy digest off` choices
|
|
185
|
+
* from being re-migrated. */
|
|
186
|
+
digestMigrated?: boolean;
|
|
178
187
|
/** Prepend pi's composed system prompt (pi tool guidance + the global
|
|
179
188
|
* agent-dir AGENTS.md and ancestor AGENTS.md/CLAUDE.md) to the FIRST
|
|
180
189
|
* prompt of each fresh agy conversation.
|
|
@@ -215,6 +224,7 @@ export interface AgyConfig {
|
|
|
215
224
|
const DEFAULTS: AgyConfig = {
|
|
216
225
|
engine: DEFAULT_ENGINE,
|
|
217
226
|
mode: "accept-edits",
|
|
227
|
+
handoff: "digest",
|
|
218
228
|
readOnly: false,
|
|
219
229
|
skipPermissions: true,
|
|
220
230
|
defaultModel: "gemini-4-hydrogen",
|
|
@@ -348,6 +358,22 @@ export function removeLegacyAcpBin(configFile: string = configPath()): boolean {
|
|
|
348
358
|
return true;
|
|
349
359
|
}
|
|
350
360
|
|
|
361
|
+
/** One-time handoff for upgraders from the digest-off default era (issue
|
|
362
|
+
* #25): pre-flip saves baked digest:false into config.json as a bare
|
|
363
|
+
* default, and silently keeping it makes mid-session handoffs lose
|
|
364
|
+
* history. Runs at session_start (loadConfig stays side-effect free);
|
|
365
|
+
* AGY_DIGEST env wins; the marker key keeps a deliberate post-migration
|
|
366
|
+
* `/agy digest off` from being flipped back. Returns whether a stale
|
|
367
|
+
* false was rewritten (caller warns once). */
|
|
368
|
+
export function migrateStaleDigestDefault(configFile: string = configPath()): { migrated: boolean } {
|
|
369
|
+
const file = readConfigFile(configFile);
|
|
370
|
+
if (process.env.AGY_DIGEST !== undefined) return { migrated: false };
|
|
371
|
+
if (file.digestMigrated) return { migrated: false };
|
|
372
|
+
if (file.digest !== false) return { migrated: false };
|
|
373
|
+
saveConfig({ digest: true, digestMigrated: true }, configFile);
|
|
374
|
+
return { migrated: true };
|
|
375
|
+
}
|
|
376
|
+
|
|
351
377
|
/** Load config merged over defaults. Env vars override the file when set. */
|
|
352
378
|
export function loadConfig(configFile: string = configPath()): AgyConfig {
|
|
353
379
|
let file: Partial<AgyConfig> = readConfigFile(configFile);
|
|
@@ -377,6 +403,12 @@ export function loadConfig(configFile: string = configPath()): AgyConfig {
|
|
|
377
403
|
? "plan"
|
|
378
404
|
: "accept-edits";
|
|
379
405
|
|
|
406
|
+
const handoffRaw = (process.env.AGY_HANDOFF ?? file.handoff ?? DEFAULTS.handoff).toString().toLowerCase();
|
|
407
|
+
const handoff: "digest" | "sync" = handoffRaw === "sync" ? "sync" : handoffRaw === "digest" ? "digest" : (() => {
|
|
408
|
+
parseWarnings.push(`handoff: ${String(handoffRaw)} is not digest|sync; using ${DEFAULTS.handoff}`);
|
|
409
|
+
return DEFAULTS.handoff;
|
|
410
|
+
})();
|
|
411
|
+
|
|
380
412
|
const envPerm = process.env.AGY_SKIP_PERMISSIONS;
|
|
381
413
|
const skipPermissions =
|
|
382
414
|
envPerm !== undefined
|
|
@@ -402,7 +434,7 @@ export function loadConfig(configFile: string = configPath()): AgyConfig {
|
|
|
402
434
|
const envThink = process.env.AGY_DEFAULT_THINKING;
|
|
403
435
|
const thinkRaw = String(envThink ?? file.defaultThinking ?? DEFAULTS.defaultThinking).toLowerCase();
|
|
404
436
|
const defaultThinking: ThinkingTier =
|
|
405
|
-
thinkRaw === "low" || thinkRaw === "high" ? thinkRaw : "medium";
|
|
437
|
+
thinkRaw === "low" || thinkRaw === "high" || thinkRaw === "xhigh" ? thinkRaw : "medium";
|
|
406
438
|
|
|
407
439
|
const askTool = process.env.AGY_ASK_TOOL !== undefined
|
|
408
440
|
? ["1", "true", "on"].includes(process.env.AGY_ASK_TOOL.toLowerCase())
|
|
@@ -414,9 +446,12 @@ export function loadConfig(configFile: string = configPath()): AgyConfig {
|
|
|
414
446
|
|
|
415
447
|
const bridgeRaw = String(process.env.AGY_BRIDGE_TOOLS ?? file.bridgeTools ?? DEFAULTS.bridgeTools).toLowerCase();
|
|
416
448
|
const bridgeTools: BridgeTools =
|
|
417
|
-
bridgeRaw === "none" || bridgeRaw === "all" || bridgeRaw === "mcp"
|
|
449
|
+
bridgeRaw === "none" || bridgeRaw === "all" || bridgeRaw === "mcp" || bridgeRaw === "codemode"
|
|
418
450
|
? bridgeRaw
|
|
419
|
-
:
|
|
451
|
+
: (() => {
|
|
452
|
+
parseWarnings.push(`bridgeTools: ${bridgeRaw} is not all|mcp|codemode|none; using ${DEFAULTS.bridgeTools}`);
|
|
453
|
+
return DEFAULTS.bridgeTools;
|
|
454
|
+
})();
|
|
420
455
|
|
|
421
456
|
// Extra long-window tool names for the bridge escalation (issue #6).
|
|
422
457
|
// Comma-separated in the env; junk entries and junk shapes are dropped,
|
|
@@ -492,6 +527,7 @@ export function loadConfig(configFile: string = configPath()): AgyConfig {
|
|
|
492
527
|
engine,
|
|
493
528
|
acp,
|
|
494
529
|
mode,
|
|
530
|
+
handoff,
|
|
495
531
|
readOnly,
|
|
496
532
|
skipPermissions,
|
|
497
533
|
defaultModel,
|
package/src/driver-types.ts
CHANGED
|
@@ -39,6 +39,33 @@ export interface DriverTurnRequest extends DriverProfile {
|
|
|
39
39
|
* resource block instead of inline prompt text (G1 on ACP). Stream-json
|
|
40
40
|
* embeds the digest in the prompt string and ignores this. */
|
|
41
41
|
contextBlock?: { uri: string; text: string };
|
|
42
|
+
/** Fresh-session variant for the ACP load-failure path (issue #25): when
|
|
43
|
+
* session/load fails and the driver falls back to a new session, it
|
|
44
|
+
* swaps prompt/contextBlock for this, so the fresh conversation still
|
|
45
|
+
* receives the system prompt and the full bound:false digest instead of
|
|
46
|
+
* answering blind. The provider prebuilds it for bound turns; the
|
|
47
|
+
* stream-json driver ignores it (the CLI drops stale ids silently and
|
|
48
|
+
* the swap point is undetectable). */
|
|
49
|
+
fallback?: { prompt: string; contextBlock?: { uri: string; text: string } };
|
|
50
|
+
/** History-sync lifecycle hooks (ACP only; optional). onSessionBound
|
|
51
|
+
* fires after the session is established (new, loaded, reused, or the
|
|
52
|
+
* load-failure fresh creation) and before config apply, so the provider
|
|
53
|
+
* can persist the binding first. onBeforePrompt fires just before the
|
|
54
|
+
* prompt RPC (write-ahead dispatch signal). Both fail the turn when they
|
|
55
|
+
* throw: a silent hook failure would checkpoint state the transport
|
|
56
|
+
* never confirmed. */
|
|
57
|
+
onSessionBound?: (info: { sessionId: string; reused: boolean; fresh: boolean }) => void | Promise<void>;
|
|
58
|
+
onBeforePrompt?: (info: { sessionId: string }) => void | Promise<void>;
|
|
59
|
+
/** Fired when session/load fails, BEFORE the fresh-session creation, so
|
|
60
|
+
* the provider can invalidate and re-prepare without an orphaned
|
|
61
|
+
* session. Returning a rebuild input swaps it in as the fresh
|
|
62
|
+
* conversation's prompt/contextBlock/images (replacing the fix-3
|
|
63
|
+
* fallback swap, which digest mode uses instead); images must carry the
|
|
64
|
+
* full rebuild set, since a fresh conversation holds no history. */
|
|
65
|
+
onSessionLoadFailed?: (info: {
|
|
66
|
+
sessionId: string;
|
|
67
|
+
error: unknown;
|
|
68
|
+
}) => { prompt: string; contextBlock?: { uri: string; text: string }; images?: Array<{ data: string; mimeType: string }> } | void;
|
|
42
69
|
signal?: AbortSignal;
|
|
43
70
|
/** Overall turn cap in minutes (default 10). Fractional values are valid
|
|
44
71
|
* (tests use sub-minute caps). 0 disables the cap. */
|
|
@@ -105,6 +132,13 @@ export interface TurnOutcome {
|
|
|
105
132
|
* guard (not a user abort, not a process crash). With sawResult false on
|
|
106
133
|
* a resumed conversation this marks the conversation as poisoned. */
|
|
107
134
|
deadline?: "timeout" | "stall";
|
|
135
|
+
/** ACP provenance, populated in #settle from the turn flags (??=) so
|
|
136
|
+
* every path - failTurn, connection exit, abort - carries them. The
|
|
137
|
+
* weaker meaning is documented: attempted = the driver invoked the
|
|
138
|
+
* prompt call, not that the transport wrote it. Stream-json leaves
|
|
139
|
+
* both undefined (nothing consumes them there). */
|
|
140
|
+
promptAttempted?: boolean;
|
|
141
|
+
promptTerminal?: boolean;
|
|
108
142
|
}
|
|
109
143
|
|
|
110
144
|
export interface TurnHandle {
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import type { Message } from "@earendil-works/pi-ai";
|
|
3
|
+
|
|
4
|
+
export interface HistoryImage {
|
|
5
|
+
data: string;
|
|
6
|
+
mimeType: string;
|
|
7
|
+
sha256: string;
|
|
8
|
+
entryId: string;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export type HistoryContent =
|
|
12
|
+
| { type: "text"; text: string }
|
|
13
|
+
| { type: "image"; mimeType: string; sha256: string }
|
|
14
|
+
| { type: "toolCall"; id: string; name: string; arguments: unknown };
|
|
15
|
+
|
|
16
|
+
export interface HistoryEntry {
|
|
17
|
+
id: string;
|
|
18
|
+
hash: string;
|
|
19
|
+
/** Index in the caller's original messages, including ignored system
|
|
20
|
+
* entries. Message-index to entry-index conversions must go through
|
|
21
|
+
* this field; the two index spaces are not interchangeable. */
|
|
22
|
+
sourceIndex: number;
|
|
23
|
+
role: "user" | "assistant" | "toolResult";
|
|
24
|
+
content: HistoryContent[];
|
|
25
|
+
status?: "interrupted" | "error";
|
|
26
|
+
toolCallId?: string;
|
|
27
|
+
toolName?: string;
|
|
28
|
+
isError?: boolean;
|
|
29
|
+
errorMessage?: string;
|
|
30
|
+
images: HistoryImage[];
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface HistoryProjection {
|
|
34
|
+
entries: HistoryEntry[];
|
|
35
|
+
/** prefixes[n] hashes exactly the first n semantic entries. */
|
|
36
|
+
prefixes: string[];
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface HistoryCheckpoint {
|
|
40
|
+
entryCount: number;
|
|
41
|
+
hash: string;
|
|
42
|
+
entryId?: string;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function hash(text: string): string {
|
|
46
|
+
return createHash("sha256").update(text).digest("hex");
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export const EMPTY_HISTORY_HASH = hash("pi-history-v1");
|
|
50
|
+
|
|
51
|
+
/** Tool object key order is not conversational meaning. */
|
|
52
|
+
function stable(value: unknown): unknown {
|
|
53
|
+
if (Array.isArray(value)) return value.map(stable);
|
|
54
|
+
if (value !== null && typeof value === "object") {
|
|
55
|
+
return Object.fromEntries(
|
|
56
|
+
Object.entries(value)
|
|
57
|
+
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
|
|
58
|
+
.filter(([, item]) => item !== undefined)
|
|
59
|
+
.map(([key, item]) => [key, stable(item)]),
|
|
60
|
+
);
|
|
61
|
+
}
|
|
62
|
+
return value;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function semantic(entry: Omit<HistoryEntry, "id" | "hash" | "sourceIndex" | "images">): string {
|
|
66
|
+
return JSON.stringify(stable(entry));
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function projectMessage(message: Message, sourceIndex: number, ordinal: number): HistoryEntry | undefined {
|
|
70
|
+
// System/tool declarations have their own carrier-agent contract. Overlay
|
|
71
|
+
// ownership must be resolved by the caller, never by matching user text.
|
|
72
|
+
if (message.role === "system") return;
|
|
73
|
+
const content: HistoryContent[] = [];
|
|
74
|
+
const images: Omit<HistoryImage, "entryId">[] = [];
|
|
75
|
+
const blocks = typeof message.content === "string" ? [{ type: "text" as const, text: message.content }] : message.content;
|
|
76
|
+
for (const block of blocks) {
|
|
77
|
+
if (block.type === "text") {
|
|
78
|
+
if (!block.text) continue;
|
|
79
|
+
const previous = content.at(-1);
|
|
80
|
+
if (previous?.type === "text") previous.text += block.text;
|
|
81
|
+
else content.push({ type: "text", text: block.text });
|
|
82
|
+
} else if (block.type === "image") {
|
|
83
|
+
if (typeof block.data !== "string" || !block.data || typeof block.mimeType !== "string" || !block.mimeType) continue;
|
|
84
|
+
const sha256 = createHash("sha256").update(block.data, "base64").digest("hex");
|
|
85
|
+
content.push({ type: "image", mimeType: block.mimeType, sha256 });
|
|
86
|
+
images.push({ data: block.data, mimeType: block.mimeType, sha256 });
|
|
87
|
+
} else if (block.type === "toolCall") {
|
|
88
|
+
content.push({ type: "toolCall", id: block.id, name: block.name, arguments: stable(block.arguments) });
|
|
89
|
+
}
|
|
90
|
+
// Thinking/signatures, usage and UI metadata never enter the projection.
|
|
91
|
+
}
|
|
92
|
+
const body: Omit<HistoryEntry, "id" | "hash" | "sourceIndex" | "images"> = {
|
|
93
|
+
role: message.role,
|
|
94
|
+
content,
|
|
95
|
+
};
|
|
96
|
+
if (message.role === "assistant") {
|
|
97
|
+
if (message.stopReason === "aborted") body.status = "interrupted";
|
|
98
|
+
else if (message.stopReason === "error") {
|
|
99
|
+
body.status = "error";
|
|
100
|
+
if (message.errorMessage) body.errorMessage = message.errorMessage;
|
|
101
|
+
}
|
|
102
|
+
} else if (message.role === "toolResult") {
|
|
103
|
+
body.toolCallId = message.toolCallId;
|
|
104
|
+
body.toolName = message.toolName;
|
|
105
|
+
body.isError = message.isError;
|
|
106
|
+
}
|
|
107
|
+
const fingerprint = hash(semantic(body));
|
|
108
|
+
const id = "m" + ordinal + "-" + fingerprint.slice(0, 16);
|
|
109
|
+
return {
|
|
110
|
+
...body,
|
|
111
|
+
id,
|
|
112
|
+
hash: fingerprint,
|
|
113
|
+
sourceIndex,
|
|
114
|
+
images: images.map((image) => ({ ...image, entryId: id })),
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Pure projection of the canonical transcript. Explicit exclusions may only
|
|
119
|
+
* contain messages whose transient ownership the caller has established. */
|
|
120
|
+
export function projectHistory(messages: readonly Message[], excluded?: ReadonlySet<Message>): HistoryProjection {
|
|
121
|
+
const entries: HistoryEntry[] = [];
|
|
122
|
+
const prefixes = [EMPTY_HISTORY_HASH];
|
|
123
|
+
for (let sourceIndex = 0; sourceIndex < messages.length; sourceIndex++) {
|
|
124
|
+
const message = messages[sourceIndex];
|
|
125
|
+
if (excluded?.has(message)) continue;
|
|
126
|
+
const entry = projectMessage(message, sourceIndex, entries.length);
|
|
127
|
+
if (!entry) continue;
|
|
128
|
+
entries.push(entry);
|
|
129
|
+
prefixes.push(hash(prefixes[prefixes.length - 1] + ":" + entry.hash));
|
|
130
|
+
}
|
|
131
|
+
return { entries, prefixes };
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
export function semanticMessageHash(message: Message): string | undefined {
|
|
135
|
+
return projectMessage(message, 0, 0)?.hash;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export function historyCheckpoint(projection: HistoryProjection, entryCount = projection.entries.length): HistoryCheckpoint {
|
|
139
|
+
if (!Number.isSafeInteger(entryCount) || entryCount < 0 || entryCount > projection.entries.length) {
|
|
140
|
+
throw new RangeError("History checkpoint is outside the projected transcript");
|
|
141
|
+
}
|
|
142
|
+
const entry = projection.entries[entryCount - 1];
|
|
143
|
+
return { entryCount, hash: projection.prefixes[entryCount], ...(entry ? { entryId: entry.id } : {}) };
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export function matchesCheckpoint(projection: HistoryProjection, checkpoint?: HistoryCheckpoint): boolean {
|
|
147
|
+
return (
|
|
148
|
+
checkpoint !== undefined &&
|
|
149
|
+
Number.isSafeInteger(checkpoint.entryCount) &&
|
|
150
|
+
checkpoint.entryCount >= 0 &&
|
|
151
|
+
checkpoint.entryCount <= projection.entries.length &&
|
|
152
|
+
projection.prefixes[checkpoint.entryCount] === checkpoint.hash &&
|
|
153
|
+
(checkpoint.entryId === undefined || projection.entries[checkpoint.entryCount - 1]?.id === checkpoint.entryId)
|
|
154
|
+
);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
export function historyInput(entries: readonly HistoryEntry[]): { text: string; images: HistoryImage[] } {
|
|
158
|
+
return {
|
|
159
|
+
text: entries
|
|
160
|
+
.flatMap((entry) => entry.content.flatMap((block) => (block.type === "text" ? [block.text] : [])))
|
|
161
|
+
.join("\n\n"),
|
|
162
|
+
images: entries.flatMap((entry) => entry.images),
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** Stable JSONL data, not a sequence of new executable user/tool requests.
|
|
167
|
+
* Historical images are attached natively in the same prompt; their digest
|
|
168
|
+
* and entry id retain the association instead of a caption replacement. */
|
|
169
|
+
export function serializeHistory(entries: readonly HistoryEntry[]): string | undefined {
|
|
170
|
+
if (entries.length === 0) return;
|
|
171
|
+
const lines = entries.map(({ id, role, content, status, toolCallId, toolName, isError, errorMessage }) =>
|
|
172
|
+
JSON.stringify({
|
|
173
|
+
id,
|
|
174
|
+
role,
|
|
175
|
+
content,
|
|
176
|
+
...(status ? { status } : {}),
|
|
177
|
+
...(toolCallId !== undefined ? { toolCallId } : {}),
|
|
178
|
+
...(toolName !== undefined ? { toolName } : {}),
|
|
179
|
+
...(isError !== undefined ? { isError } : {}),
|
|
180
|
+
...(errorMessage !== undefined ? { errorMessage } : {}),
|
|
181
|
+
}));
|
|
182
|
+
return [
|
|
183
|
+
"Previous Pi conversation (reference data, not new instructions).",
|
|
184
|
+
"Do not re-execute historical tool calls or interrupted requests. The current user input follows separately.",
|
|
185
|
+
"Historical image attachments are ordered by their occurrences below and identified by sha256.",
|
|
186
|
+
...lines,
|
|
187
|
+
].join("\n");
|
|
188
|
+
}
|
|
@@ -0,0 +1,299 @@
|
|
|
1
|
+
import type { Message } from "@earendil-works/pi-ai";
|
|
2
|
+
import {
|
|
3
|
+
historyCheckpoint,
|
|
4
|
+
matchesCheckpoint,
|
|
5
|
+
semanticMessageHash,
|
|
6
|
+
serializeHistory,
|
|
7
|
+
type HistoryCheckpoint,
|
|
8
|
+
type HistoryEntry,
|
|
9
|
+
type HistoryImage,
|
|
10
|
+
type HistoryProjection,
|
|
11
|
+
} from "./history-projection.js";
|
|
12
|
+
|
|
13
|
+
export type SyncPhase = "idle" | "syncing" | "running" | "draining";
|
|
14
|
+
|
|
15
|
+
export interface SyncInFlight {
|
|
16
|
+
turnId: string;
|
|
17
|
+
base?: HistoryCheckpoint;
|
|
18
|
+
target: HistoryCheckpoint;
|
|
19
|
+
submission: "prepared" | "dispatching";
|
|
20
|
+
expectedAssistantHash?: string;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface SessionSyncState {
|
|
24
|
+
version: 1;
|
|
25
|
+
epoch: number;
|
|
26
|
+
checkpoint?: HistoryCheckpoint;
|
|
27
|
+
expectedAssistantHash?: string;
|
|
28
|
+
inFlight?: SyncInFlight;
|
|
29
|
+
invalidReason?: string;
|
|
30
|
+
/** Churn gate: after repeated rebuild-causing turns the session falls
|
|
31
|
+
* back to digest behavior for its lifetime. Set by the provider. */
|
|
32
|
+
digestFallback?: boolean;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface SyncOptions {
|
|
36
|
+
continuation?: boolean;
|
|
37
|
+
/** Predicate mirroring the provider's backlog-shape test (compaction
|
|
38
|
+
* summaries, synthetic notes): a trailing-run member matching one is
|
|
39
|
+
* history, never current input. Injected to keep this module pure. */
|
|
40
|
+
isBacklogShape?: (text: string) => boolean;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface HistorySyncPlan {
|
|
44
|
+
kind: "continue" | "rebuild" | "resume";
|
|
45
|
+
reason: string;
|
|
46
|
+
checkpoint?: HistoryCheckpoint;
|
|
47
|
+
target: HistoryCheckpoint;
|
|
48
|
+
history: HistoryEntry[];
|
|
49
|
+
currentUser: HistoryEntry[];
|
|
50
|
+
historyImages: HistoryImage[];
|
|
51
|
+
embeddedContext?: string;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function hashValue(value: unknown): value is string {
|
|
55
|
+
return typeof value === "string" && /^[a-f0-9]{64}$/.test(value);
|
|
56
|
+
}
|
|
57
|
+
function record(value: unknown): value is Record<string, unknown> {
|
|
58
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
59
|
+
}
|
|
60
|
+
function narrowCheckpoint(value: unknown): HistoryCheckpoint | undefined {
|
|
61
|
+
if (!record(value) || !Number.isSafeInteger(value.entryCount) || (value.entryCount as number) < 0 || !hashValue(value.hash)) return;
|
|
62
|
+
if (value.entryId !== undefined && typeof value.entryId !== "string") return;
|
|
63
|
+
return {
|
|
64
|
+
entryCount: value.entryCount as number,
|
|
65
|
+
hash: value.hash,
|
|
66
|
+
...(typeof value.entryId === "string" ? { entryId: value.entryId } : {}),
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Persist only the small protocol journal, never a second transcript. */
|
|
71
|
+
export function narrowSessionSync(value: unknown): SessionSyncState | undefined {
|
|
72
|
+
if (!record(value) || value.version !== 1) return;
|
|
73
|
+
const result: SessionSyncState = {
|
|
74
|
+
version: 1,
|
|
75
|
+
epoch: Number.isSafeInteger(value.epoch) && (value.epoch as number) >= 0 ? (value.epoch as number) : 0,
|
|
76
|
+
};
|
|
77
|
+
let malformed = false;
|
|
78
|
+
if (value.checkpoint !== undefined) {
|
|
79
|
+
result.checkpoint = narrowCheckpoint(value.checkpoint);
|
|
80
|
+
malformed ||= result.checkpoint === undefined;
|
|
81
|
+
}
|
|
82
|
+
if (value.expectedAssistantHash !== undefined) {
|
|
83
|
+
if (hashValue(value.expectedAssistantHash)) result.expectedAssistantHash = value.expectedAssistantHash;
|
|
84
|
+
else malformed = true;
|
|
85
|
+
}
|
|
86
|
+
if (typeof value.invalidReason === "string") result.invalidReason = value.invalidReason;
|
|
87
|
+
if (value.digestFallback === true) result.digestFallback = true;
|
|
88
|
+
if (value.inFlight !== undefined) {
|
|
89
|
+
const flight = value.inFlight;
|
|
90
|
+
if (!record(flight) || typeof flight.turnId !== "string" || !flight.turnId || (flight.submission !== "prepared" && flight.submission !== "dispatching")) {
|
|
91
|
+
malformed = true;
|
|
92
|
+
} else {
|
|
93
|
+
const target = narrowCheckpoint(flight.target);
|
|
94
|
+
const base = flight.base === undefined ? undefined : narrowCheckpoint(flight.base);
|
|
95
|
+
if (!target || (flight.base !== undefined && !base) || (flight.expectedAssistantHash !== undefined && !hashValue(flight.expectedAssistantHash))) {
|
|
96
|
+
malformed = true;
|
|
97
|
+
} else {
|
|
98
|
+
result.inFlight = {
|
|
99
|
+
turnId: flight.turnId,
|
|
100
|
+
target,
|
|
101
|
+
submission: flight.submission,
|
|
102
|
+
...(base ? { base } : {}),
|
|
103
|
+
...(hashValue(flight.expectedAssistantHash) ? { expectedAssistantHash: flight.expectedAssistantHash } : {}),
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
if (malformed) result.invalidReason = "invalid-sync-state";
|
|
109
|
+
return result;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function absorbAssistant(projection: HistoryProjection, base: HistoryCheckpoint | undefined, expected?: string): HistoryCheckpoint | undefined {
|
|
113
|
+
if (!matchesCheckpoint(projection, base)) return;
|
|
114
|
+
if (!expected) return base;
|
|
115
|
+
const entry = projection.entries[base!.entryCount];
|
|
116
|
+
if (entry?.role !== "assistant" || entry.hash !== expected) return;
|
|
117
|
+
return historyCheckpoint(projection, base!.entryCount + 1);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** A provider's returned assistant is not canonical until Pi echoes it back.
|
|
121
|
+
* Lenient on purpose: the stored checkpoint already claimed its span, so a
|
|
122
|
+
* foreign turn parked at the boundary rides the delta instead of forcing a
|
|
123
|
+
* rebuild; only a prefix mismatch invalidates. */
|
|
124
|
+
export function reconcileCheckpoint(projection: HistoryProjection, state?: SessionSyncState): HistoryCheckpoint | undefined {
|
|
125
|
+
if (!matchesCheckpoint(projection, state?.checkpoint)) return;
|
|
126
|
+
const expected = state?.expectedAssistantHash;
|
|
127
|
+
const base = state!.checkpoint!;
|
|
128
|
+
if (!expected) return base;
|
|
129
|
+
const entry = projection.entries[base.entryCount];
|
|
130
|
+
if (entry?.role !== "assistant" || entry.hash !== expected) return base;
|
|
131
|
+
return historyCheckpoint(projection, base.entryCount + 1);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function entryText(entry: HistoryEntry): string {
|
|
135
|
+
return entry.content.flatMap((block) => (block.type === "text" ? [block.text] : [])).join("");
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** Trailing run of consecutive user entries, truncated at backlog-shaped
|
|
139
|
+
* members: compaction summaries and synthetic notes are history, never
|
|
140
|
+
* current input (issue #24's queued-run rule, entry-indexed). */
|
|
141
|
+
function trailingUserRunStart(projection: HistoryProjection, options: SyncOptions): number {
|
|
142
|
+
const { entries } = projection;
|
|
143
|
+
const end = entries.length;
|
|
144
|
+
let start = end;
|
|
145
|
+
for (let i = end - 1; i >= 0; i--) {
|
|
146
|
+
const entry = entries[i]!;
|
|
147
|
+
if (entry.role !== "user") break;
|
|
148
|
+
if (options.isBacklogShape?.(entryText(entry))) break;
|
|
149
|
+
start = i;
|
|
150
|
+
}
|
|
151
|
+
return start;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
export function planHistorySync(projection: HistoryProjection, state?: SessionSyncState, options: SyncOptions = {}): HistorySyncPlan {
|
|
155
|
+
const checkpoint = reconcileCheckpoint(projection, state);
|
|
156
|
+
let kind: HistorySyncPlan["kind"] = "continue";
|
|
157
|
+
let reason = "matching-prefix";
|
|
158
|
+
if (state?.invalidReason) {
|
|
159
|
+
kind = "rebuild";
|
|
160
|
+
reason = state.invalidReason;
|
|
161
|
+
} else if (options.continuation && state?.inFlight) {
|
|
162
|
+
const consumed = absorbAssistant(projection, state.inFlight.target, state.inFlight.expectedAssistantHash);
|
|
163
|
+
if (!consumed) {
|
|
164
|
+
kind = "rebuild";
|
|
165
|
+
reason = "changed-inflight-prefix";
|
|
166
|
+
} else if (projection.entries.slice(consumed.entryCount).some((entry) => entry.role === "user")) {
|
|
167
|
+
kind = "rebuild";
|
|
168
|
+
reason = "new-user-during-turn";
|
|
169
|
+
} else {
|
|
170
|
+
kind = "resume";
|
|
171
|
+
reason = "live-tool-continuation";
|
|
172
|
+
}
|
|
173
|
+
} else if (state?.inFlight) {
|
|
174
|
+
kind = "rebuild";
|
|
175
|
+
reason = "unsettled-submission";
|
|
176
|
+
} else if (!checkpoint) {
|
|
177
|
+
kind = "rebuild";
|
|
178
|
+
reason = state?.checkpoint ? "changed-prefix" : "missing-checkpoint";
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
const end = projection.entries.length;
|
|
182
|
+
let currentStart = trailingUserRunStart(projection, options);
|
|
183
|
+
// Earlier inputs of a confirmed-or-parked turn stay historical even when
|
|
184
|
+
// Pi shows consecutive user messages without an assistant between them
|
|
185
|
+
// (queued steering runs). Candidates kept through invalidation so a
|
|
186
|
+
// cancellation cannot erase an earlier user.
|
|
187
|
+
const priorInput = state?.inFlight?.target;
|
|
188
|
+
const priorBoundary = matchesCheckpoint(projection, priorInput)
|
|
189
|
+
? priorInput!.entryCount
|
|
190
|
+
: matchesCheckpoint(projection, state?.checkpoint)
|
|
191
|
+
? state!.checkpoint!.entryCount
|
|
192
|
+
: 0;
|
|
193
|
+
// Identical-retry guard: the parked target of a failed turn can cover the
|
|
194
|
+
// whole transcript (entryCount == end). Clamping then yields an empty
|
|
195
|
+
// current input and stalls pi's retry behind "No user message"; a
|
|
196
|
+
// never-confirmed turn may re-send its user run.
|
|
197
|
+
if (priorBoundary < end) currentStart = Math.max(currentStart, priorBoundary);
|
|
198
|
+
const history = kind === "resume" ? [] : projection.entries.slice(kind === "rebuild" ? 0 : checkpoint!.entryCount, currentStart);
|
|
199
|
+
return {
|
|
200
|
+
kind,
|
|
201
|
+
reason,
|
|
202
|
+
...(checkpoint ? { checkpoint } : {}),
|
|
203
|
+
target: historyCheckpoint(projection),
|
|
204
|
+
history,
|
|
205
|
+
currentUser: kind === "resume" ? [] : projection.entries.slice(currentStart),
|
|
206
|
+
historyImages: history.flatMap((entry) => entry.images),
|
|
207
|
+
...(history.length ? { embeddedContext: serializeHistory(history) } : {}),
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** Controls one logical AGY turn across any number of Pi tool parks. Runtime
|
|
212
|
+
* liveness belongs to the caller: loading an inFlight record never revives it. */
|
|
213
|
+
export class SessionSyncCoordinator {
|
|
214
|
+
#phase: SyncPhase = "idle";
|
|
215
|
+
#state: SessionSyncState;
|
|
216
|
+
#plan?: HistorySyncPlan;
|
|
217
|
+
|
|
218
|
+
constructor(state?: SessionSyncState) {
|
|
219
|
+
this.#state = narrowSessionSync(state) ?? { version: 1, epoch: 0 };
|
|
220
|
+
}
|
|
221
|
+
get phase(): SyncPhase {
|
|
222
|
+
return this.#phase;
|
|
223
|
+
}
|
|
224
|
+
get snapshot(): SessionSyncState {
|
|
225
|
+
return structuredClone(this.#state);
|
|
226
|
+
}
|
|
227
|
+
markDigestFallback(): void {
|
|
228
|
+
this.#state.digestFallback = true;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
prepare(projection: HistoryProjection, options: SyncOptions = {}): HistorySyncPlan {
|
|
232
|
+
if (this.#phase !== "idle" && !(options.continuation && this.#phase === "running")) {
|
|
233
|
+
throw new Error("Cannot synchronize while session is " + this.#phase);
|
|
234
|
+
}
|
|
235
|
+
this.#plan = planHistorySync(projection, this.#state, options);
|
|
236
|
+
this.#phase = "syncing";
|
|
237
|
+
return this.#plan;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
bound(turnId: string): void {
|
|
241
|
+
if (this.#phase !== "syncing" || !this.#plan) throw new Error("Synchronize before binding a turn");
|
|
242
|
+
const plan = this.#plan;
|
|
243
|
+
const continuing = plan.kind === "resume";
|
|
244
|
+
if (continuing && this.#state.inFlight?.turnId !== turnId) throw new Error("Continuation belongs to another turn");
|
|
245
|
+
const base = continuing ? this.#state.inFlight?.base : plan.kind === "continue" ? plan.checkpoint : undefined;
|
|
246
|
+
if (plan.kind === "rebuild") this.#state.epoch++;
|
|
247
|
+
this.#state = {
|
|
248
|
+
version: 1,
|
|
249
|
+
epoch: this.#state.epoch,
|
|
250
|
+
...(this.#state.digestFallback ? { digestFallback: true } : {}),
|
|
251
|
+
...(base ? { checkpoint: base } : {}),
|
|
252
|
+
inFlight: { turnId, ...(base ? { base } : {}), target: plan.target, submission: continuing ? "dispatching" : "prepared" },
|
|
253
|
+
};
|
|
254
|
+
this.#phase = "running";
|
|
255
|
+
this.#plan = undefined;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
dispatching(): void {
|
|
259
|
+
if (this.#phase !== "running" || !this.#state.inFlight) throw new Error("No running turn to submit");
|
|
260
|
+
this.#state.inFlight.submission = "dispatching";
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
park(projection: HistoryProjection, assistant: Message): void {
|
|
264
|
+
if (this.#phase !== "running" || !this.#state.inFlight) throw new Error("No running turn to park");
|
|
265
|
+
this.#state.inFlight.target = historyCheckpoint(projection);
|
|
266
|
+
this.#state.inFlight.expectedAssistantHash = semanticMessageHash(assistant);
|
|
267
|
+
// A Pi toolUse response does not finish the remote session/prompt.
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
terminal(projection: HistoryProjection, assistant: Message): void {
|
|
271
|
+
if (this.#phase !== "running") throw new Error("No running turn to settle");
|
|
272
|
+
this.#state.checkpoint = historyCheckpoint(projection);
|
|
273
|
+
this.#state.expectedAssistantHash = semanticMessageHash(assistant);
|
|
274
|
+
delete this.#state.inFlight;
|
|
275
|
+
this.#phase = "idle";
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/** True while a turn is bound and unsettled: the only phase terminal()
|
|
279
|
+
* accepts. Callers outside the driver flow (orchestrator finish) must
|
|
280
|
+
* check this before settling, or the throw becomes a provider crash. */
|
|
281
|
+
get settleable(): boolean {
|
|
282
|
+
return this.#phase === "running";
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
draining(): void {
|
|
286
|
+
if (this.#phase !== "running" && this.#phase !== "syncing") throw new Error("No active turn to cancel");
|
|
287
|
+
this.#phase = "draining";
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/** Caller must first settle/close the old transport. Keep the inFlight
|
|
291
|
+
* input boundary and unknown submission, so cancellation cannot erase an
|
|
292
|
+
* earlier user. */
|
|
293
|
+
invalidate(reason: string): void {
|
|
294
|
+
this.#state.invalidReason = reason;
|
|
295
|
+
this.#state.epoch++;
|
|
296
|
+
this.#phase = "idle";
|
|
297
|
+
this.#plan = undefined;
|
|
298
|
+
}
|
|
299
|
+
}
|