@zvada/agent-server 0.3.16 → 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 (48) hide show
  1. package/CHANGELOG.md +73 -0
  2. package/README.md +30 -2
  3. package/docs/consuming.md +9 -2
  4. package/docs/harnesses.md +19 -6
  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/agents/codex-app-server/adapter.ts +31 -3
  14. package/src/core/agents/codex-sdk/adapter.ts +45 -15
  15. package/src/core/agents/codex-sdk/codex-sdk-agent.ts +25 -1
  16. package/src/core/agents/types.ts +2 -1
  17. package/src/core/index.ts +2 -0
  18. package/src/core/provision/pins.ts +2 -1
  19. package/src/core/runtime/agent-runtime.ts +53 -23
  20. package/src/core/runtime/event-processor.ts +10 -5
  21. package/src/core/runtime/event-sink.ts +45 -2
  22. package/src/core/runtime/model-lists.ts +24 -9
  23. package/src/protocol/history.ts +267 -0
  24. package/src/protocol/ids.ts +4 -5
  25. package/src/protocol/index.ts +1 -0
  26. package/src/protocol/wire.ts +82 -1
  27. package/src/server/agent-server.ts +167 -94
  28. package/src/server/bin.ts +22 -1
  29. package/src/server/history.ts +166 -0
  30. package/src/server/index.ts +1 -0
  31. package/src/server/session-store.ts +225 -0
  32. package/src/server/wire-error.ts +52 -0
  33. package/src/sync/event-log.ts +132 -0
  34. package/src/sync/fit.ts +124 -0
  35. package/src/sync/history-reader.ts +52 -0
  36. package/src/sync/history-sqlite.ts +344 -0
  37. package/src/sync/history.ts +226 -0
  38. package/src/sync/index.ts +6 -0
  39. package/src/sync/journal-sqlite.ts +353 -0
  40. package/src/sync/journal.ts +73 -0
  41. package/src/sync/node-sqlite.ts +20 -0
  42. package/src/sync/recovery.ts +112 -0
  43. package/src/sync/retry.ts +49 -0
  44. package/src/sync/schema.ts +56 -0
  45. package/src/sync/sql.ts +106 -0
  46. package/src/sync/sqlite-file.ts +38 -0
  47. package/src/sync/sqlite.ts +21 -0
  48. package/src/sync/worker.ts +259 -0
@@ -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
+ }