@zvada/agent-server 0.3.17 → 0.3.18

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.
Files changed (44) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/README.md +30 -2
  3. package/docs/consuming.md +9 -2
  4. package/docs/harnesses.md +11 -3
  5. package/docs/sync-experiment.md +190 -0
  6. package/docs/sync-history.md +181 -0
  7. package/docs/sync-integration.md +133 -0
  8. package/package.json +14 -2
  9. package/src/client/client.ts +138 -33
  10. package/src/client/history.ts +88 -0
  11. package/src/client/index.ts +1 -1
  12. package/src/client/request.ts +19 -0
  13. package/src/core/index.ts +2 -0
  14. package/src/core/provision/pins.ts +2 -1
  15. package/src/core/runtime/agent-runtime.ts +53 -23
  16. package/src/core/runtime/event-processor.ts +10 -5
  17. package/src/core/runtime/event-sink.ts +45 -2
  18. package/src/core/runtime/model-lists.ts +24 -9
  19. package/src/protocol/history.ts +267 -0
  20. package/src/protocol/ids.ts +4 -5
  21. package/src/protocol/index.ts +1 -0
  22. package/src/protocol/wire.ts +82 -1
  23. package/src/server/agent-server.ts +167 -94
  24. package/src/server/bin.ts +22 -1
  25. package/src/server/history.ts +166 -0
  26. package/src/server/index.ts +1 -0
  27. package/src/server/session-store.ts +225 -0
  28. package/src/server/wire-error.ts +52 -0
  29. package/src/sync/event-log.ts +132 -0
  30. package/src/sync/fit.ts +124 -0
  31. package/src/sync/history-reader.ts +52 -0
  32. package/src/sync/history-sqlite.ts +344 -0
  33. package/src/sync/history.ts +226 -0
  34. package/src/sync/index.ts +6 -0
  35. package/src/sync/journal-sqlite.ts +353 -0
  36. package/src/sync/journal.ts +73 -0
  37. package/src/sync/node-sqlite.ts +20 -0
  38. package/src/sync/recovery.ts +112 -0
  39. package/src/sync/retry.ts +49 -0
  40. package/src/sync/schema.ts +56 -0
  41. package/src/sync/sql.ts +106 -0
  42. package/src/sync/sqlite-file.ts +38 -0
  43. package/src/sync/sqlite.ts +21 -0
  44. package/src/sync/worker.ts +259 -0
@@ -0,0 +1,112 @@
1
+ import {
2
+ type LifecycleEvent,
3
+ PARTIAL_INPUT_META_KEY,
4
+ type Part,
5
+ decodeLifecycleEvent,
6
+ emptyConversation,
7
+ isUnknownEvent,
8
+ reduceConversation,
9
+ } from "../protocol/index.ts";
10
+
11
+ /** What a tool that was running when the process died reports. */
12
+ export const INTERRUPTED_TOOL_ERROR =
13
+ "Tool execution was interrupted when agent-server stopped. Its outcome is unknown and its effects were not undone. Check the current state before continuing or retrying.";
14
+
15
+ function closePart(part: Part, at: number): Part | undefined {
16
+ if (part.type === "tool") {
17
+ const state = part.state;
18
+ if (state.status === "pending")
19
+ return {
20
+ ...part,
21
+ state: {
22
+ status: "failed",
23
+ input: {},
24
+ error: INTERRUPTED_TOOL_ERROR,
25
+ time: { start: at, end: at },
26
+ ...(state.partialInput && {
27
+ _meta: { ...state._meta, [PARTIAL_INPUT_META_KEY]: state.partialInput },
28
+ }),
29
+ },
30
+ };
31
+ if (state.status === "in_progress")
32
+ return {
33
+ ...part,
34
+ state: {
35
+ status: "failed",
36
+ input: state.input,
37
+ error: INTERRUPTED_TOOL_ERROR,
38
+ time: { start: state.time.start, end: at },
39
+ ...(state._meta && { _meta: state._meta }),
40
+ },
41
+ };
42
+ return undefined;
43
+ }
44
+ if ((part.type === "text" || part.type === "reasoning") && part.state === "streaming")
45
+ return { ...part, state: "done" };
46
+ return undefined;
47
+ }
48
+
49
+ /**
50
+ * The facts that close what an interrupted turn left open, to commit before
51
+ * its `turn.ended`: pending permissions resolve as cancelled, running tools
52
+ * fail with an outcome-unknown error, streaming text is marked done, and open
53
+ * messages end. `events` is the turn's committed history, oldest first.
54
+ */
55
+ export function interruptionFacts(
56
+ events: Iterable<unknown>,
57
+ sessionId: string,
58
+ turnId: string,
59
+ at: number,
60
+ ): LifecycleEvent[] {
61
+ let state = emptyConversation();
62
+ const address = new Map<string, { messageId: string; outputIndex: number; partIndex: number }>();
63
+ for (const raw of events) {
64
+ const event = decodeLifecycleEvent(raw);
65
+ state = reduceConversation(state, event);
66
+ if (!isUnknownEvent(event) && event.type === "message.part" && event.turnId === turnId)
67
+ address.set(event.part.id, {
68
+ messageId: event.messageId,
69
+ outputIndex: event.outputIndex,
70
+ partIndex: event.partIndex,
71
+ });
72
+ }
73
+ const facts: LifecycleEvent[] = [];
74
+ for (const permission of state.permissions)
75
+ if (permission.turnId === turnId && permission.outcome === undefined)
76
+ facts.push({
77
+ type: "permission.resolved",
78
+ sessionId,
79
+ turnId,
80
+ requestId: permission.requestId,
81
+ outcome: { outcome: "cancelled" },
82
+ timestamp: at,
83
+ });
84
+ for (const entry of state.timeline) {
85
+ if (entry.kind !== "message" || entry.turnId !== turnId) continue;
86
+ // A tool keeps running after the model message that called it ends, and
87
+ // its later states update the part under that ended message.
88
+ for (const part of entry.parts) {
89
+ if ("raw" in part) continue;
90
+ const where = address.get(part.id);
91
+ const closed = where && closePart(part, at);
92
+ if (where && closed)
93
+ facts.push({
94
+ type: "message.part",
95
+ sessionId,
96
+ turnId,
97
+ ...where,
98
+ part: closed,
99
+ timestamp: at,
100
+ });
101
+ }
102
+ if (entry.endedAt === undefined)
103
+ facts.push({
104
+ type: "message.ended",
105
+ sessionId,
106
+ turnId,
107
+ messageId: entry.messageId,
108
+ timestamp: at,
109
+ });
110
+ }
111
+ return facts;
112
+ }
@@ -0,0 +1,49 @@
1
+ /** Resolves after `ms`, or as soon as `signal` aborts (without throwing). */
2
+ export function pause(ms: number, signal?: AbortSignal): Promise<void> {
3
+ if (signal?.aborted) return Promise.resolve();
4
+ return new Promise((resolve) => {
5
+ const done = () => {
6
+ clearTimeout(timer);
7
+ signal?.removeEventListener("abort", done);
8
+ resolve();
9
+ };
10
+ const timer = setTimeout(done, ms);
11
+ signal?.addEventListener("abort", done, { once: true });
12
+ });
13
+ }
14
+
15
+ /** The shortest time between two waits that brought nothing. */
16
+ const IDLE_FLOOR_MS = 100;
17
+ /** After a wait that brought nothing, pause what remains of the idle floor: a
18
+ * wait answered at once (a zero timeout, or one a short request timeout clamps)
19
+ * must not spin. */
20
+ export function idleAfter(waitStartedAt: number, signal?: AbortSignal): Promise<void> {
21
+ return pause(Math.max(0, IDLE_FLOOR_MS - (Date.now() - waitStartedAt)), signal);
22
+ }
23
+
24
+ /**
25
+ * The host's retry policy: the delay in ms before retrying `error` after
26
+ * `failures` consecutive failures, or undefined to give up. Retry transport
27
+ * failures (`ConnectionClosedError`); never retry a HistoryError.
28
+ */
29
+ export type RetryPolicy = (error: unknown, failures: number) => number | undefined;
30
+
31
+ /** Consecutive failures under a retry policy. Only progress puts them behind:
32
+ * a read that changes nothing does not repair a channel that keeps failing. */
33
+ export class RetryBudget {
34
+ private consecutive = 0;
35
+ constructor(private readonly policy?: RetryPolicy) {}
36
+ get failures(): number {
37
+ return this.consecutive;
38
+ }
39
+ /** The delay before retrying (at most a minute), or `error` rethrown when
40
+ * the policy gives up. */
41
+ fail(error: unknown): number {
42
+ const ms = this.policy?.(error, ++this.consecutive);
43
+ if (ms === undefined || !Number.isFinite(ms) || ms < 0) throw error;
44
+ return Math.min(ms, 60_000);
45
+ }
46
+ progressed(): void {
47
+ this.consecutive = 0;
48
+ }
49
+ }
@@ -0,0 +1,56 @@
1
+ import type { Db } from "./sql.ts";
2
+
3
+ /** Nothing has been released yet, so there are no migrations: an empty file
4
+ * gets this schema, and a released change will add ordered migrations keyed
5
+ * by `user_version`. Version 1 was an unreleased experiment's layout. */
6
+ export const SCHEMA_VERSION = 2;
7
+
8
+ const DDL = `
9
+ CREATE TABLE identity (id TEXT PRIMARY KEY);
10
+ -- Every history this store holds, run here or copied in: descriptor and head.
11
+ CREATE TABLE histories (
12
+ source_id TEXT NOT NULL, session_id TEXT NOT NULL, descriptor TEXT NOT NULL,
13
+ head_seq INTEGER NOT NULL, head_hash TEXT NOT NULL,
14
+ PRIMARY KEY (source_id, session_id));
15
+ -- Every history's records: canonical event JSON, hash-chained per history.
16
+ CREATE TABLE events (
17
+ source_id TEXT NOT NULL, session_id TEXT NOT NULL, seq INTEGER NOT NULL,
18
+ hash TEXT NOT NULL, body TEXT NOT NULL,
19
+ PRIMARY KEY (source_id, session_id, seq));
20
+ -- The sessions this store executes; their histories have its identity as source.
21
+ CREATE TABLE sessions (
22
+ session_id TEXT PRIMARY KEY, harness TEXT NOT NULL, native_id TEXT,
23
+ closed INTEGER NOT NULL DEFAULT 0, recovery_required INTEGER NOT NULL DEFAULT 0);
24
+ -- Admitted turns: the request's fingerprint and input, then how it settled.
25
+ CREATE TABLE turns (
26
+ session_id TEXT NOT NULL, turn_id TEXT NOT NULL, fingerprint TEXT NOT NULL,
27
+ input TEXT NOT NULL, state TEXT NOT NULL, terminal_seq INTEGER,
28
+ PRIMARY KEY (session_id, turn_id));
29
+ CREATE UNIQUE INDEX one_active_turn ON turns (session_id) WHERE state = 'admitted';
30
+ -- Branch commits by id, so a retried commit returns the version it first made.
31
+ CREATE TABLE commits (
32
+ session_id TEXT NOT NULL, commit_id TEXT NOT NULL, fingerprint TEXT NOT NULL,
33
+ version TEXT NOT NULL, PRIMARY KEY (session_id, commit_id));
34
+ -- Cached conversation projections; the events stay authoritative.
35
+ CREATE TABLE checkpoints (
36
+ source_id TEXT NOT NULL, session_id TEXT NOT NULL, format TEXT NOT NULL,
37
+ seq INTEGER NOT NULL, body TEXT NOT NULL,
38
+ PRIMARY KEY (source_id, session_id, format));
39
+ PRAGMA user_version = ${SCHEMA_VERSION};
40
+ `;
41
+
42
+ /** Create or check the schema; returns the store's identity, minting it once. */
43
+ export function openSchema(db: Db, newId: () => string): string {
44
+ const { user_version: version } = db.one<{ user_version: number }>("PRAGMA user_version")!;
45
+ if (version !== 0 && version !== SCHEMA_VERSION)
46
+ throw new Error(
47
+ `Unsupported journal schema ${version}; this build reads schema ${SCHEMA_VERSION}`,
48
+ );
49
+ return db.atomic(() => {
50
+ if (version === 0) {
51
+ db.exec(DDL);
52
+ db.run("INSERT INTO identity(id) VALUES (?)", newId());
53
+ }
54
+ return db.one<{ id: string }>("SELECT id FROM identity")!.id;
55
+ });
56
+ }
@@ -0,0 +1,106 @@
1
+ export type SqlValue = string | number | null;
2
+
3
+ /** The shared implementation uses only positional scalar bindings. */
4
+ export interface SqlStatement {
5
+ run(...params: SqlValue[]): unknown;
6
+ get(...params: SqlValue[]): unknown;
7
+ all(...params: SqlValue[]): unknown[];
8
+ iterate(...params: SqlValue[]): Iterable<unknown>;
9
+ finalize?(): void;
10
+ }
11
+ /** A synchronous SQLite connection: Bun's, Node's, or any like them. */
12
+ export interface SqlConnection {
13
+ exec(sql: string): void;
14
+ prepare(sql: string): SqlStatement;
15
+ /** Run `write` as one transaction, for a host that manages its own (such as a
16
+ * Durable Object's `transactionSync`). Without it: BEGIN IMMEDIATE…COMMIT. */
17
+ transaction?<T>(write: () => T): T;
18
+ close(): void;
19
+ }
20
+
21
+ /** One connection's prepared statements, typed reads and transactions. */
22
+ export class Db {
23
+ private readonly statements = new Map<string, SqlStatement>();
24
+ private depth = 0;
25
+ private closed = false;
26
+
27
+ constructor(private readonly connection: SqlConnection) {}
28
+
29
+ exec(sql: string): void {
30
+ this.connection.exec(sql);
31
+ }
32
+ /** One row, or undefined: Bun answers a missing row with null, Node with undefined. */
33
+ one<T>(sql: string, ...params: SqlValue[]): T | undefined {
34
+ return (this.statement(sql).get(...params) ?? undefined) as T | undefined;
35
+ }
36
+ all<T>(sql: string, ...params: SqlValue[]): T[] {
37
+ return this.statement(sql).all(...params) as T[];
38
+ }
39
+ /** Rows one at a time; stop early freely. */
40
+ *each<T>(sql: string, ...params: SqlValue[]): Generator<T> {
41
+ const statement = this.statement(sql);
42
+ let finished = false;
43
+ try {
44
+ yield* statement.iterate(...params) as Iterable<T>;
45
+ finished = true;
46
+ } finally {
47
+ // Bun (1.3.6) leaves a statement whose loop stopped early unusable for
48
+ // its next iterate(): retire it, and the next use prepares it afresh.
49
+ if (!finished) {
50
+ this.statements.delete(sql);
51
+ statement.finalize?.();
52
+ }
53
+ }
54
+ }
55
+ run(sql: string, ...params: SqlValue[]): void {
56
+ this.statement(sql).run(...params);
57
+ }
58
+ /** Runs `write` in one transaction; a nested call joins the outer one. */
59
+ atomic<T>(write: () => T): T {
60
+ if (this.depth) return write();
61
+ if (this.connection.transaction) {
62
+ this.depth++;
63
+ try {
64
+ return this.connection.transaction(write);
65
+ } finally {
66
+ this.depth--;
67
+ }
68
+ }
69
+ // Explicit statements avoid Bun 1.3.6 transaction-wrapper statements holding
70
+ // the exclusive SQLite connection open until garbage collection.
71
+ this.connection.exec("BEGIN IMMEDIATE");
72
+ this.depth++;
73
+ try {
74
+ const result = write();
75
+ this.connection.exec("COMMIT");
76
+ return result;
77
+ } catch (error) {
78
+ try {
79
+ this.connection.exec("ROLLBACK");
80
+ } catch {
81
+ /* preserve the original storage error */
82
+ }
83
+ throw error;
84
+ } finally {
85
+ this.depth--;
86
+ }
87
+ }
88
+ close(): void {
89
+ if (this.closed) return;
90
+ this.closed = true;
91
+ // Bun's bounded query cache can evict a statement without immediately
92
+ // finalizing it. Own/finalize the finite SQL catalog to release the OS lock.
93
+ for (const statement of this.statements.values()) statement.finalize?.();
94
+ this.statements.clear();
95
+ this.connection.close();
96
+ }
97
+
98
+ private statement(sql: string): SqlStatement {
99
+ let statement = this.statements.get(sql);
100
+ if (!statement) {
101
+ statement = this.connection.prepare(sql);
102
+ this.statements.set(sql, statement);
103
+ }
104
+ return statement;
105
+ }
106
+ }
@@ -0,0 +1,38 @@
1
+ import { closeSync, mkdirSync, openSync } from "node:fs";
2
+ import { dirname } from "node:path";
3
+ import type { SqlConnection } from "./sql.ts";
4
+
5
+ /**
6
+ * A journal file for one owning process: created private (0600 in a 0700
7
+ * directory), then opened in WAL with every commit synced and an exclusive
8
+ * lock, so another process cannot open it (serve readers over the wire).
9
+ * Process death releases the lock.
10
+ */
11
+ export function openJournalFile(
12
+ path: string,
13
+ open: (file: string) => SqlConnection,
14
+ ): SqlConnection {
15
+ if (path !== ":memory:") {
16
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
17
+ try {
18
+ closeSync(openSync(path, "wx", 0o600));
19
+ } catch (error) {
20
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
21
+ }
22
+ }
23
+ const connection = open(path);
24
+ try {
25
+ connection.exec(
26
+ "PRAGMA busy_timeout=0; PRAGMA locking_mode=EXCLUSIVE; PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL;",
27
+ );
28
+ } catch (error) {
29
+ connection.close();
30
+ if (/database is locked/.test((error as Error).message))
31
+ throw new Error(
32
+ `Journal ${path} is locked by another process: one process owns a journal, others reach it over the wire`,
33
+ { cause: error },
34
+ );
35
+ throw error;
36
+ }
37
+ return connection;
38
+ }
@@ -0,0 +1,21 @@
1
+ import { Database } from "bun:sqlite";
2
+ import { SqliteJournal } from "./journal-sqlite.ts";
3
+ import { openJournalFile } from "./sqlite-file.ts";
4
+
5
+ /** Bun adapter. Use one journal owner per file and RPC for concurrent readers. */
6
+ export class SqliteSessionJournal extends SqliteJournal {
7
+ constructor(path: string) {
8
+ super(
9
+ openJournalFile(path, (file) => {
10
+ const db = new Database(file, { create: true, strict: true });
11
+ return {
12
+ exec: (sql) => {
13
+ db.exec(sql);
14
+ },
15
+ prepare: (sql) => db.prepare(sql),
16
+ close: () => db.close(true),
17
+ };
18
+ }),
19
+ );
20
+ }
21
+ }
@@ -0,0 +1,259 @@
1
+ import {
2
+ type HistoryApi,
3
+ type HistoryArchive,
4
+ type HistoryVersion,
5
+ HistoryVersionSchema,
6
+ type SessionRef,
7
+ sameHistory,
8
+ sameVersion,
9
+ } from "../protocol/index.ts";
10
+ import { type HistoryTransferOptions, transferHistory } from "./history.ts";
11
+ import { RetryBudget, type RetryPolicy, idleAfter, pause } from "./retry.ts";
12
+
13
+ export type HistorySyncState =
14
+ | "starting"
15
+ | "syncing"
16
+ | "synced"
17
+ | "retrying"
18
+ | "blocked"
19
+ | "stopped";
20
+ export interface HistorySyncStatus {
21
+ ref: SessionRef;
22
+ state: HistorySyncState;
23
+ /** The source's head as this worker last read it. */
24
+ localVersion?: HistoryVersion;
25
+ /** What the destination has committed, as this worker last checked it. The
26
+ * destination is the record of what remains to send: nothing is saved here. */
27
+ acknowledged?: HistoryVersion;
28
+ /** Records the destination lacks, once both versions are known. */
29
+ pendingRecords?: number;
30
+ /** Imported since start: pages, their records, and their JSON bytes. */
31
+ pages: number;
32
+ records: number;
33
+ bytes: number;
34
+ /** Consecutive failures; while `retrying` or `blocked`, `error` is the latest. */
35
+ failures: number;
36
+ error?: unknown;
37
+ }
38
+ export interface HistorySyncOptions extends Pick<HistoryTransferOptions, "pageSize" | "pageBytes"> {
39
+ /** Briefly batch bursts without delaying local durability. Default 25ms. */
40
+ batchMs?: number;
41
+ /** The longest single wait on the source while idle. */
42
+ waitMs?: number;
43
+ retry?: RetryPolicy;
44
+ }
45
+ export interface SyncBarrierOptions {
46
+ signal?: AbortSignal;
47
+ timeoutMs?: number;
48
+ }
49
+
50
+ /** Local cancellation does not cancel the remote RPC; its own deadline still applies. */
51
+ async function interruptible<T>(value: T | Promise<T>, signal: AbortSignal): Promise<T> {
52
+ signal.throwIfAborted();
53
+ return new Promise((resolve, reject) => {
54
+ const aborted = () => {
55
+ signal.removeEventListener("abort", aborted);
56
+ reject(signal.reason);
57
+ };
58
+ signal.addEventListener("abort", aborted, { once: true });
59
+ Promise.resolve(value)
60
+ .then(resolve, reject)
61
+ .finally(() => signal.removeEventListener("abort", aborted));
62
+ });
63
+ }
64
+
65
+ /** One explicitly selected history and destination. Own this lifetime in the
66
+ * host, not in a UI component. Recreate after a blocked failure or destination
67
+ * replacement. Networking remains the host's authenticated/reconnecting client. */
68
+ class HistorySync {
69
+ private readonly abort = new AbortController();
70
+ private readonly listeners = new Set<(status: HistorySyncStatus) => void>();
71
+ private current: HistorySyncStatus;
72
+ /** Resolves on stop or blocked failure; inspect status for the outcome. */
73
+ readonly done: Promise<void>;
74
+ constructor(
75
+ private readonly source: HistoryApi,
76
+ private readonly destination: HistoryArchive,
77
+ private readonly ref: SessionRef,
78
+ private readonly options: HistorySyncOptions,
79
+ ) {
80
+ const batchMs = options.batchMs ?? 25;
81
+ if (!Number.isFinite(batchMs) || batchMs < 0 || batchMs > 60_000)
82
+ throw new Error("Invalid sync batch delay");
83
+ const waitMs = options.waitMs ?? 0;
84
+ if (!Number.isFinite(waitMs) || waitMs < 0 || waitMs > 20_000)
85
+ throw new Error("Invalid sync wait");
86
+ this.current = {
87
+ ref: { sourceId: ref.sourceId, sessionId: ref.sessionId },
88
+ state: "starting",
89
+ pages: 0,
90
+ records: 0,
91
+ bytes: 0,
92
+ failures: 0,
93
+ };
94
+ this.done = this.run();
95
+ }
96
+ status(): HistorySyncStatus {
97
+ return structuredClone(this.current);
98
+ }
99
+ subscribe(listener: (status: HistorySyncStatus) => void): () => void {
100
+ this.listeners.add(listener);
101
+ return () => {
102
+ this.listeners.delete(listener);
103
+ };
104
+ }
105
+ private set(patch: Partial<HistorySyncStatus>): void {
106
+ // Stopped is final: work still landing after stop() is not news.
107
+ if (this.current.state === "stopped") return;
108
+ const next = { ...this.current, ...patch };
109
+ next.pendingRecords =
110
+ next.localVersion && next.acknowledged
111
+ ? Math.max(0, next.localVersion.seq - next.acknowledged.seq)
112
+ : undefined;
113
+ this.current = next;
114
+ for (const listener of this.listeners) {
115
+ try {
116
+ listener(this.status());
117
+ } catch {
118
+ /* observers cannot change durability */
119
+ }
120
+ }
121
+ }
122
+ private async run(): Promise<void> {
123
+ const signal = this.abort.signal;
124
+ const budget = new RetryBudget(this.options.retry);
125
+ let acknowledged: HistoryVersion | undefined;
126
+ try {
127
+ while (!signal.aborted) {
128
+ try {
129
+ // Idle costs one wait on the source; a pass runs once it moves past
130
+ // what the destination holds.
131
+ const waited = Date.now();
132
+ const local = acknowledged
133
+ ? (
134
+ await this.source.wait(
135
+ { after: acknowledged, timeoutMs: this.options.waitMs },
136
+ signal,
137
+ )
138
+ ).version
139
+ : (await this.source.head(this.ref)).version;
140
+ if (acknowledged && sameVersion(local, acknowledged)) {
141
+ budget.progressed();
142
+ await idleAfter(waited, signal);
143
+ continue;
144
+ }
145
+ this.set({ state: "syncing", localVersion: local });
146
+ await pause(this.options.batchMs ?? 25, signal);
147
+ signal.throwIfAborted();
148
+ const { version } = await transferHistory(this.source, this.destination, this.ref, {
149
+ signal,
150
+ pageSize: this.options.pageSize,
151
+ pageBytes: this.options.pageBytes,
152
+ onPage: (page, pageBytes) => {
153
+ budget.progressed();
154
+ this.set({
155
+ pages: this.current.pages + 1,
156
+ records: this.current.records + page.records.length,
157
+ bytes: this.current.bytes + pageBytes,
158
+ });
159
+ },
160
+ });
161
+ if (!acknowledged || version.seq > acknowledged.seq) budget.progressed();
162
+ acknowledged = version;
163
+ const head = (await this.source.head(this.ref)).version;
164
+ this.set({
165
+ state: sameVersion(head, version) ? "synced" : "syncing",
166
+ localVersion: head,
167
+ acknowledged: version,
168
+ failures: budget.failures,
169
+ error: undefined,
170
+ });
171
+ } catch (error) {
172
+ if (signal.aborted) break;
173
+ const delay = budget.fail(error);
174
+ this.set({ state: "retrying", failures: budget.failures, error });
175
+ await pause(delay, signal);
176
+ }
177
+ }
178
+ } catch (error) {
179
+ if (!signal.aborted) this.set({ state: "blocked", failures: budget.failures, error });
180
+ }
181
+ }
182
+ /** Pin the current local head, then wait for its durable remote acknowledgement.
183
+ * New events may arrive after this barrier; they do not extend its target. */
184
+ async flush(options: SyncBarrierOptions = {}): Promise<HistoryVersion> {
185
+ return this.barrier(undefined, options);
186
+ }
187
+ async waitUntilSynced(
188
+ target: HistoryVersion,
189
+ options: SyncBarrierOptions = {},
190
+ ): Promise<HistoryVersion> {
191
+ return this.barrier(HistoryVersionSchema.parse(target), options);
192
+ }
193
+ private async barrier(
194
+ pinned: HistoryVersion | undefined,
195
+ options: SyncBarrierOptions,
196
+ ): Promise<HistoryVersion> {
197
+ const timeout = options.timeoutMs ?? 30_000;
198
+ if (!Number.isFinite(timeout) || timeout < 0 || timeout > 2_147_483_647)
199
+ throw new Error("Invalid sync barrier timeout");
200
+ const deadline = new AbortController();
201
+ const signal = AbortSignal.any([
202
+ this.abort.signal,
203
+ deadline.signal,
204
+ ...(options.signal ? [options.signal] : []),
205
+ ]);
206
+ const timer = setTimeout(() => deadline.abort(new Error("Sync barrier timed out")), timeout);
207
+ try {
208
+ signal.throwIfAborted();
209
+ if (this.current.state === "blocked") throw this.current.error;
210
+ const target = pinned ?? (await interruptible(this.source.head(this.ref), signal)).version;
211
+ if (!sameHistory(target, this.ref))
212
+ throw new Error("Sync barrier belongs to another history");
213
+ // Reject a forged hash even when its sequence is below an acknowledged head.
214
+ await interruptible(
215
+ this.source.read({ ...this.ref, after: target, through: target }),
216
+ signal,
217
+ );
218
+ signal.throwIfAborted();
219
+ return await new Promise<HistoryVersion>((resolve, reject) => {
220
+ let off = () => {};
221
+ const finish = (error?: unknown, failed = false) => {
222
+ off();
223
+ signal.removeEventListener("abort", aborted);
224
+ if (failed) reject(error);
225
+ else resolve(target);
226
+ };
227
+ const aborted = () => finish(signal.reason, true);
228
+ const check = (status: HistorySyncStatus) => {
229
+ if (status.state === "blocked") return finish(status.error, true);
230
+ if (status.state === "stopped") return finish(new Error("Sync stopped"), true);
231
+ if (status.acknowledged && status.acknowledged.seq >= target.seq) finish();
232
+ };
233
+ off = this.subscribe(check);
234
+ signal.addEventListener("abort", aborted, { once: true });
235
+ check(this.current);
236
+ });
237
+ } finally {
238
+ clearTimeout(timer);
239
+ }
240
+ }
241
+
242
+ /** Cancels waits and joins in-flight work; host RPCs must have bounded timeouts. */
243
+ async stop(): Promise<void> {
244
+ this.abort.abort(new Error("Sync stopped"));
245
+ this.set({ state: "stopped" });
246
+ await this.done;
247
+ this.listeners.clear();
248
+ }
249
+ }
250
+ export type { HistorySync };
251
+ /** Keep `destination` holding `ref` as it grows, until stopped or blocked. */
252
+ export function startHistorySync(
253
+ source: HistoryApi,
254
+ destination: HistoryArchive,
255
+ ref: SessionRef,
256
+ options: HistorySyncOptions = {},
257
+ ): HistorySync {
258
+ return new HistorySync(source, destination, ref, options);
259
+ }