@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.
@@ -47,6 +47,25 @@ export interface DriverTurnRequest extends DriverProfile {
47
47
  * stream-json driver ignores it (the CLI drops stale ids silently and
48
48
  * the swap point is undetectable). */
49
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;
50
69
  signal?: AbortSignal;
51
70
  /** Overall turn cap in minutes (default 10). Fractional values are valid
52
71
  * (tests use sub-minute caps). 0 disables the cap. */
@@ -113,6 +132,13 @@ export interface TurnOutcome {
113
132
  * guard (not a user abort, not a process crash). With sawResult false on
114
133
  * a resumed conversation this marks the conversation as poisoned. */
115
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;
116
142
  }
117
143
 
118
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
+ }
package/src/models.ts CHANGED
@@ -35,14 +35,15 @@ const DISCOVERY_TIMEOUT_MS = 8_000;
35
35
  * real output and 1 MiB dwarfs any encoding difference. */
36
36
  export const MODELS_OUTPUT_CAP_BYTES = 1024 * 1024;
37
37
 
38
- /** Reasoning-effort tiers agy accepts via --effort. */
39
- export type AgyEffort = "low" | "medium" | "high";
38
+ /** Reasoning-effort tiers agy accepts via --effort. xhigh exists on the
39
+ * Gemini 4 line (agy 1.5.16 catalog); other families walk down to high. */
40
+ export type AgyEffort = "low" | "medium" | "high" | "xhigh";
40
41
 
41
- /** low < medium < high, for sorting/clamping. */
42
- const EFFORT_RANK: Record<AgyEffort, number> = { low: 0, medium: 1, high: 2 };
42
+ /** low < medium < high < xhigh, for sorting/clamping. */
43
+ const EFFORT_RANK: Record<AgyEffort, number> = { low: 0, medium: 1, high: 2, xhigh: 3 };
43
44
 
44
45
  /** pi thinking-effort order mirrors agy's, for clamping. */
45
- export const AGY_EFFORT_ORDER: readonly AgyEffort[] = ["low", "medium", "high"];
46
+ export const AGY_EFFORT_ORDER: readonly AgyEffort[] = ["low", "medium", "high", "xhigh"];
46
47
 
47
48
  /** Map pi's thinking level onto one of the tiers `efforts` the base actually
48
49
  * supports, clamping to the nearest available. agy rejects an effort tier a
@@ -63,8 +64,10 @@ export function toAgyEffort(
63
64
  case "medium":
64
65
  candidate = "medium";
65
66
  break;
66
- case "high":
67
67
  case "xhigh":
68
+ candidate = "xhigh";
69
+ break;
70
+ case "high":
68
71
  case "max":
69
72
  candidate = "high";
70
73
  break;
@@ -86,7 +89,7 @@ export function toAgyEffort(
86
89
  * -high/-medium/-low suffix - a shape only unverified families should
87
90
  * produce now, and those stay whole. Every Claude slug carries a tier
88
91
  * suffix and collapses to its base. */
89
- const TIER_RE = /^(.+)-(high|medium|low)$/;
92
+ const TIER_RE = /^(.+)-(xhigh|high|medium|low)$/;
90
93
 
91
94
  /** agy emits clean slug ids (gemini-3.6-flash-high). Validate col1 of each
92
95
  * line so a banner / auth / "Fetching models…" line can't register as a
@@ -346,14 +349,16 @@ export function slugify(full: string): string {
346
349
 
347
350
  /** Build the thinkingLevelMap for an effort-driven base: hide "off" and
348
351
  * "minimal" always (agy has no no-thinking mode; a base REQUIRES an effort),
349
- * and hide any of low/medium/high the base doesn't offer (e.g. Pro has no
350
- * medium). pi's getSupportedThinkingLevels treats a null value as hidden, so
351
- * the toggle then shows exactly agy's slider stops. */
352
+ * and hide any of low/medium/high/xhigh the base doesn't offer (e.g. Pro has
353
+ * no medium). pi's getSupportedThinkingLevels treats a null value as hidden
354
+ * for low/medium/high, but xhigh additionally requires an EXPLICIT non-null
355
+ * entry to appear at all, so a base that ships xhigh maps it to itself. */
352
356
  function thinkingLevelMapFor(efforts: readonly AgyEffort[]): ThinkingLevelMap {
353
357
  const map: Record<string, string | null> = { off: null, minimal: null };
354
- for (const level of ["low", "medium", "high"] as const) {
358
+ for (const level of ["low", "medium", "high", "xhigh"] as const) {
355
359
  if (!efforts.includes(level)) map[level] = null;
356
360
  }
361
+ if (efforts.includes("xhigh")) map.xhigh = "xhigh";
357
362
  return map as ThinkingLevelMap;
358
363
  }
359
364