@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.
- package/CHANGELOG.md +56 -0
- package/README.md +30 -2
- package/docs/consuming.md +9 -2
- package/docs/harnesses.md +11 -3
- package/docs/sync-experiment.md +190 -0
- package/docs/sync-history.md +181 -0
- package/docs/sync-integration.md +133 -0
- package/package.json +14 -2
- package/src/client/client.ts +138 -33
- package/src/client/history.ts +88 -0
- package/src/client/index.ts +1 -1
- package/src/client/request.ts +19 -0
- package/src/core/index.ts +2 -0
- package/src/core/provision/pins.ts +2 -1
- package/src/core/runtime/agent-runtime.ts +53 -23
- package/src/core/runtime/event-processor.ts +10 -5
- package/src/core/runtime/event-sink.ts +45 -2
- package/src/core/runtime/model-lists.ts +24 -9
- package/src/protocol/history.ts +267 -0
- package/src/protocol/ids.ts +4 -5
- package/src/protocol/index.ts +1 -0
- package/src/protocol/wire.ts +82 -1
- package/src/server/agent-server.ts +167 -94
- package/src/server/bin.ts +22 -1
- package/src/server/history.ts +166 -0
- package/src/server/index.ts +1 -0
- package/src/server/session-store.ts +225 -0
- package/src/server/wire-error.ts +52 -0
- package/src/sync/event-log.ts +132 -0
- package/src/sync/fit.ts +124 -0
- package/src/sync/history-reader.ts +52 -0
- package/src/sync/history-sqlite.ts +344 -0
- package/src/sync/history.ts +226 -0
- package/src/sync/index.ts +6 -0
- package/src/sync/journal-sqlite.ts +353 -0
- package/src/sync/journal.ts +73 -0
- package/src/sync/node-sqlite.ts +20 -0
- package/src/sync/recovery.ts +112 -0
- package/src/sync/retry.ts +49 -0
- package/src/sync/schema.ts +56 -0
- package/src/sync/sql.ts +106 -0
- package/src/sync/sqlite-file.ts +38 -0
- package/src/sync/sqlite.ts +21 -0
- package/src/sync/worker.ts +259 -0
|
@@ -29,7 +29,7 @@ import type { AgentRegistry } from "../agents/registry.ts";
|
|
|
29
29
|
import { type DiagnosticHandler, emitDiagnostic } from "../diagnostics.ts";
|
|
30
30
|
import { TurnConflictError } from "../utils/errors.ts";
|
|
31
31
|
import { EventProcessor, endedExecution } from "./event-processor.ts";
|
|
32
|
-
import type
|
|
32
|
+
import { type EventSink, EventSinkError } from "./event-sink.ts";
|
|
33
33
|
import { ModelLists, type ModelsQuery } from "./model-lists.ts";
|
|
34
34
|
|
|
35
35
|
/** What a completed turn reports back to the caller (in addition to the streamed events). */
|
|
@@ -75,8 +75,8 @@ function canonicalJson(value: unknown): string {
|
|
|
75
75
|
return `{${entries.join(",")}}`;
|
|
76
76
|
}
|
|
77
77
|
|
|
78
|
-
//
|
|
79
|
-
const turnKeyOf = (sessionId: string, turnId: string) =>
|
|
78
|
+
// Caller-supplied IDs need not be UUIDs; encode the tuple without delimiter collisions.
|
|
79
|
+
const turnKeyOf = (sessionId: string, turnId: string) => JSON.stringify([sessionId, turnId]);
|
|
80
80
|
const inputKeyOf = (request: RunRequest) =>
|
|
81
81
|
canonicalJson({ input: request.input, config: request.config });
|
|
82
82
|
|
|
@@ -114,14 +114,18 @@ export class AgentRuntime {
|
|
|
114
114
|
string,
|
|
115
115
|
{ inputKey: string; promise: Promise<RunSummary> }
|
|
116
116
|
>();
|
|
117
|
-
/** Recently
|
|
117
|
+
/** Recently settled turns per session (bounded LRU). Retries converge on the
|
|
118
|
+
* stored summary, or on the sink failure that stopped the turn mid-execution. */
|
|
118
119
|
private readonly completedTurns = new Map<
|
|
119
120
|
string,
|
|
120
|
-
Map<string, { inputKey: string
|
|
121
|
+
Map<string, { inputKey: string } & ({ summary: RunSummary } | { failure: EventSinkError })>
|
|
121
122
|
>();
|
|
122
123
|
/** Per-session convergence window; old turns fall out and a stale retry would re-execute. */
|
|
123
124
|
private static readonly COMPLETED_TURN_MEMORY = 16;
|
|
124
125
|
private shutdownPromise?: Promise<void>;
|
|
126
|
+
/** Aborted as shutdown begins, and part of every run's signal: a run still
|
|
127
|
+
* setting up then, which its harness has not yet tracked, stops too. */
|
|
128
|
+
private readonly stopping = new AbortController();
|
|
125
129
|
private readonly modelLists = new ModelLists();
|
|
126
130
|
|
|
127
131
|
constructor(
|
|
@@ -163,7 +167,8 @@ export class AgentRuntime {
|
|
|
163
167
|
* Probe how `run()` would admit this request WITHOUT executing anything:
|
|
164
168
|
* `new` (would run), `inflight`/`completed` (an identical request was
|
|
165
169
|
* already admitted — a retry must converge, not re-execute). Throws
|
|
166
|
-
* `TurnConflictError` when this turnId was admitted with DIFFERENT input
|
|
170
|
+
* `TurnConflictError` when this turnId was admitted with DIFFERENT input,
|
|
171
|
+
* and the turn's `EventSinkError` when its durable sink stopped it.
|
|
167
172
|
* Wire seats use this to quick-ack a duplicate instead of starting it.
|
|
168
173
|
*/
|
|
169
174
|
admission(request: RunRequest): TurnAdmission {
|
|
@@ -179,6 +184,8 @@ export class AgentRuntime {
|
|
|
179
184
|
if (done.inputKey !== inputKeyOf(request)) {
|
|
180
185
|
throw new TurnConflictError(request.sessionId, request.turnId);
|
|
181
186
|
}
|
|
187
|
+
// It may have run tools before its sink failed: never run it again.
|
|
188
|
+
if ("failure" in done) throw done.failure;
|
|
182
189
|
return { status: "completed", summary: done.summary };
|
|
183
190
|
}
|
|
184
191
|
return { status: "new" };
|
|
@@ -220,13 +227,16 @@ export class AgentRuntime {
|
|
|
220
227
|
// probe could observe the settled turn as still inflight.
|
|
221
228
|
running.then(
|
|
222
229
|
(summary) => {
|
|
223
|
-
this.rememberTurn(request.sessionId, request.turnId, inputKey, summary);
|
|
230
|
+
this.rememberTurn(request.sessionId, request.turnId, { inputKey, summary });
|
|
224
231
|
this.inflightTurns.delete(turnKey);
|
|
225
232
|
this.activeRuns.delete(running);
|
|
226
233
|
},
|
|
227
234
|
// A rejected run is NOT memoized: it died before executing the turn
|
|
228
|
-
// loop (registry/setup), so a retry is allowed to try again.
|
|
229
|
-
|
|
235
|
+
// loop (registry/setup), so a retry is allowed to try again. Unless its
|
|
236
|
+
// durable sink stopped it, possibly after it had run tools.
|
|
237
|
+
(error) => {
|
|
238
|
+
if (error instanceof EventSinkError)
|
|
239
|
+
this.rememberTurn(request.sessionId, request.turnId, { inputKey, failure: error });
|
|
230
240
|
this.inflightTurns.delete(turnKey);
|
|
231
241
|
this.activeRuns.delete(running);
|
|
232
242
|
},
|
|
@@ -237,15 +247,14 @@ export class AgentRuntime {
|
|
|
237
247
|
private rememberTurn(
|
|
238
248
|
sessionId: string,
|
|
239
249
|
turnId: string,
|
|
240
|
-
inputKey: string,
|
|
241
|
-
summary: RunSummary,
|
|
250
|
+
settled: { inputKey: string } & ({ summary: RunSummary } | { failure: EventSinkError }),
|
|
242
251
|
): void {
|
|
243
252
|
let perSession = this.completedTurns.get(sessionId);
|
|
244
253
|
if (!perSession) {
|
|
245
254
|
perSession = new Map();
|
|
246
255
|
this.completedTurns.set(sessionId, perSession);
|
|
247
256
|
}
|
|
248
|
-
perSession.set(turnId,
|
|
257
|
+
perSession.set(turnId, settled);
|
|
249
258
|
while (perSession.size > AgentRuntime.COMPLETED_TURN_MEMORY) {
|
|
250
259
|
const oldest = perSession.keys().next().value;
|
|
251
260
|
if (oldest === undefined) break;
|
|
@@ -283,11 +292,22 @@ export class AgentRuntime {
|
|
|
283
292
|
let applied: AppliedExecution | undefined;
|
|
284
293
|
|
|
285
294
|
// Isolate sink failures: a misbehaving transport must never break the
|
|
286
|
-
// turn's lifecycle bracketing (turn.started ... turn.ended).
|
|
295
|
+
// turn's lifecycle bracketing (turn.started ... turn.ended). Except a
|
|
296
|
+
// sink's EventSinkError: its writes are a durability boundary, so the turn
|
|
297
|
+
// stops rather than run on unrecorded, and every later emit fails with it.
|
|
298
|
+
let fatal: EventSinkError | undefined;
|
|
287
299
|
const emit = async (e: LifecycleEvent) => {
|
|
300
|
+
if (fatal) throw fatal;
|
|
288
301
|
try {
|
|
289
302
|
await sink.emit(e);
|
|
290
303
|
} catch (err) {
|
|
304
|
+
if (err instanceof EventSinkError) {
|
|
305
|
+
fatal = err;
|
|
306
|
+
// Refuses pending permissions and interrupts the harness. Whether
|
|
307
|
+
// the native execution stopped stays unconfirmed.
|
|
308
|
+
void this.cancel(config.harness, sessionId).catch(() => {});
|
|
309
|
+
throw err;
|
|
310
|
+
}
|
|
291
311
|
// The turn must not fail on a misbehaving sink — but the host gets
|
|
292
312
|
// to know its sink dropped an event.
|
|
293
313
|
emitDiagnostic(this.options.onDiagnostic, {
|
|
@@ -328,7 +348,7 @@ export class AgentRuntime {
|
|
|
328
348
|
toolCall: PermissionToolCall,
|
|
329
349
|
permOpts?: { signal?: AbortSignal },
|
|
330
350
|
): Promise<PermissionDecision> => {
|
|
331
|
-
if (permOpts?.signal?.aborted) return { decision: "cancel" };
|
|
351
|
+
if (fatal || permOpts?.signal?.aborted) return { decision: "cancel" };
|
|
332
352
|
// A standing `*_always` rule from an earlier prompt in this session
|
|
333
353
|
// answers without a round-trip (and without fake prompt events). The
|
|
334
354
|
// rule carries the verdict only — an `updatedInput` edit belongs to the
|
|
@@ -349,20 +369,24 @@ export class AgentRuntime {
|
|
|
349
369
|
const settle = (o: PermissionOutcome): Promise<void> | void => {
|
|
350
370
|
if (!this.pendingPermissions.delete(requestId)) return;
|
|
351
371
|
turnRequestIds.delete(requestId);
|
|
352
|
-
|
|
353
|
-
//
|
|
354
|
-
//
|
|
355
|
-
//
|
|
356
|
-
|
|
372
|
+
// The harness gets the decision once `permission.resolved` is
|
|
373
|
+
// written, so a durable sink records an approval before its tool
|
|
374
|
+
// runs and a failed write refuses it. Recorded so the in-run drain
|
|
375
|
+
// sequences it before turn.ended no matter WHO settled (broker,
|
|
376
|
+
// respondPermission, cancel) — external callers ignore the promise.
|
|
377
|
+
const settled = emit({
|
|
357
378
|
type: "permission.resolved",
|
|
358
379
|
sessionId,
|
|
359
380
|
turnId,
|
|
360
381
|
requestId,
|
|
361
382
|
outcome: o,
|
|
362
383
|
timestamp: Date.now(),
|
|
363
|
-
})
|
|
364
|
-
|
|
365
|
-
|
|
384
|
+
}).then(
|
|
385
|
+
() => resolveOutcome(o),
|
|
386
|
+
() => resolveOutcome({ outcome: "cancelled" }),
|
|
387
|
+
);
|
|
388
|
+
settleEmits.push(settled);
|
|
389
|
+
return settled;
|
|
366
390
|
};
|
|
367
391
|
this.pendingPermissions.set(requestId, { sessionId, settle });
|
|
368
392
|
turnRequestIds.add(requestId);
|
|
@@ -440,7 +464,9 @@ export class AgentRuntime {
|
|
|
440
464
|
apiKey: config.apiKey,
|
|
441
465
|
disableTools: config.disableTools,
|
|
442
466
|
...(modelThinking && { modelThinking }),
|
|
443
|
-
signal: opts.signal
|
|
467
|
+
signal: opts.signal
|
|
468
|
+
? AbortSignal.any([opts.signal, this.stopping.signal])
|
|
469
|
+
: this.stopping.signal,
|
|
444
470
|
onNativeSession: (id, info) => {
|
|
445
471
|
// Agents report once the native conversation is confirmed; guard against a
|
|
446
472
|
// misbehaving harness re-reporting after emission. Agents always pass
|
|
@@ -571,6 +597,9 @@ export class AgentRuntime {
|
|
|
571
597
|
.filter((pending) => pending.sessionId === sessionId)
|
|
572
598
|
.map((pending) => pending.settle({ outcome: "cancelled" })),
|
|
573
599
|
);
|
|
600
|
+
// A harness this runtime does not run (a session restored from a journal
|
|
601
|
+
// written with another registry) holds nothing here to release.
|
|
602
|
+
if (!this.registry.has(harness)) return;
|
|
574
603
|
const agent = this.registry.getAgent(harness);
|
|
575
604
|
if (agent.release) await agent.release(sessionId);
|
|
576
605
|
else await agent.cancel(sessionId);
|
|
@@ -588,6 +617,7 @@ export class AgentRuntime {
|
|
|
588
617
|
}
|
|
589
618
|
|
|
590
619
|
private async performShutdown(drainTimeoutMs: number): Promise<void> {
|
|
620
|
+
this.stopping.abort();
|
|
591
621
|
await Promise.all(
|
|
592
622
|
[...this.pendingPermissions.values()].map((pending) =>
|
|
593
623
|
pending.settle({ outcome: "cancelled" }),
|
|
@@ -131,21 +131,23 @@ export class EventProcessor {
|
|
|
131
131
|
timestamp: Date.now(),
|
|
132
132
|
};
|
|
133
133
|
return;
|
|
134
|
-
case "compacted":
|
|
134
|
+
case "compacted": {
|
|
135
135
|
// Harnesses report compaction after the fact — a single completed
|
|
136
136
|
// upsert of the positional entity (its first appearance anchors it).
|
|
137
|
+
const at = Date.now();
|
|
137
138
|
yield {
|
|
138
139
|
type: "session.compaction",
|
|
139
140
|
sessionId: this.sessionId,
|
|
140
141
|
turnId: this.turnId,
|
|
141
|
-
compactionId: generateUUIDv7(),
|
|
142
|
+
compactionId: generateUUIDv7(at),
|
|
142
143
|
status: "completed",
|
|
143
144
|
...(ev.trigger && { trigger: ev.trigger }),
|
|
144
145
|
...(ev.preTokens !== undefined && { preTokens: ev.preTokens }),
|
|
145
146
|
...(ev.postTokens !== undefined && { postTokens: ev.postTokens }),
|
|
146
|
-
timestamp:
|
|
147
|
+
timestamp: at,
|
|
147
148
|
};
|
|
148
149
|
return;
|
|
150
|
+
}
|
|
149
151
|
}
|
|
150
152
|
}
|
|
151
153
|
|
|
@@ -186,7 +188,10 @@ export class EventProcessor {
|
|
|
186
188
|
): Generator<LifecycleEvent> {
|
|
187
189
|
if (this.openMessageId) yield* this.closeMessage();
|
|
188
190
|
if (role === "assistant") this.answered = true;
|
|
189
|
-
|
|
191
|
+
// One clock reading: a consumer that dates a message by its id agrees
|
|
192
|
+
// with one that dates it by this event.
|
|
193
|
+
const startedAt = Date.now();
|
|
194
|
+
const messageId = id ?? generateUUIDv7(startedAt);
|
|
190
195
|
this.openMessageId = messageId;
|
|
191
196
|
this.openMessageParent = parentToolCallId;
|
|
192
197
|
this.currentOutputIndex = this.nextOutputIndex++;
|
|
@@ -207,7 +212,7 @@ export class EventProcessor {
|
|
|
207
212
|
// assistant message (top-level AND parented sub-agent output) keeps it,
|
|
208
213
|
// since `config.model` is the only per-turn model signal available.
|
|
209
214
|
...(role === "assistant" && this.execution?.model && { model: this.execution?.model }),
|
|
210
|
-
timestamp:
|
|
215
|
+
timestamp: startedAt,
|
|
211
216
|
};
|
|
212
217
|
}
|
|
213
218
|
|
|
@@ -9,6 +9,19 @@ export interface EventSink {
|
|
|
9
9
|
emit(event: LifecycleEvent): void | Promise<void>;
|
|
10
10
|
}
|
|
11
11
|
|
|
12
|
+
/**
|
|
13
|
+
* Throw this FROM a sink whose writes are a durability boundary, such as a
|
|
14
|
+
* journal: the turn stops rather than run on unrecorded, its harness is
|
|
15
|
+
* cancelled, and a retry of the same turn converges on this failure instead of
|
|
16
|
+
* running it again. Anything else a sink throws is isolated (a diagnostic).
|
|
17
|
+
*/
|
|
18
|
+
export class EventSinkError extends Error {
|
|
19
|
+
override readonly name = "EventSinkError";
|
|
20
|
+
constructor(cause: unknown) {
|
|
21
|
+
super("Required event sink failed; execution needs recovery", { cause });
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
12
25
|
/** Build a sink from a plain callback. */
|
|
13
26
|
export function callbackSink(fn: (event: LifecycleEvent) => void | Promise<void>): EventSink {
|
|
14
27
|
return { emit: fn };
|
|
@@ -27,11 +40,41 @@ export class CollectingSink implements EventSink {
|
|
|
27
40
|
}
|
|
28
41
|
}
|
|
29
42
|
|
|
30
|
-
/**
|
|
43
|
+
/**
|
|
44
|
+
* Write one event at a time, in the order they were emitted. A permission
|
|
45
|
+
* response can arrive while its request is still being written (from inside
|
|
46
|
+
* the sink, or from another caller), so an async sink that must record the
|
|
47
|
+
* request before the response wraps itself in this.
|
|
48
|
+
*/
|
|
49
|
+
export function serialSink(sink: EventSink): EventSink {
|
|
50
|
+
let tail: Promise<void> = Promise.resolve();
|
|
51
|
+
return {
|
|
52
|
+
emit(event) {
|
|
53
|
+
const write = tail.then(() => sink.emit(event));
|
|
54
|
+
tail = write.catch(() => {});
|
|
55
|
+
return write;
|
|
56
|
+
},
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Fan out to several sinks at once. Every sink gets every event, whichever
|
|
62
|
+
* throws; a durability failure (`EventSinkError`) outranks an ordinary one.
|
|
63
|
+
* A sink that answers a permission during `emit` reenters the tee: place it
|
|
64
|
+
* after the durable sink, or wrap the tee in `serialSink`.
|
|
65
|
+
*/
|
|
31
66
|
export function teeSink(...sinks: EventSink[]): EventSink {
|
|
32
67
|
return {
|
|
33
68
|
async emit(event) {
|
|
34
|
-
|
|
69
|
+
const errors: unknown[] = [];
|
|
70
|
+
for (const sink of sinks) {
|
|
71
|
+
try {
|
|
72
|
+
await sink.emit(event);
|
|
73
|
+
} catch (error) {
|
|
74
|
+
errors.push(error);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
if (errors.length) throw errors.find((error) => error instanceof EventSinkError) ?? errors[0];
|
|
35
78
|
},
|
|
36
79
|
};
|
|
37
80
|
}
|
|
@@ -53,6 +53,22 @@ export function catalogModelList(harness: AgentHarness, fetchedAt = Date.now()):
|
|
|
53
53
|
/** An alias (Claude `opus`, `default`) runs a model that depends on the account. */
|
|
54
54
|
const isAlias = (model: ModelDescriptor) => model.resolvedId !== undefined;
|
|
55
55
|
|
|
56
|
+
/**
|
|
57
|
+
* The row of `models` for `model`: the row with that id, else a row that runs
|
|
58
|
+
* it as an alias. Without `aliases`, a row whose own id is an alias does not
|
|
59
|
+
* match by id, since another login's alias may run another model.
|
|
60
|
+
*/
|
|
61
|
+
function rowFor(
|
|
62
|
+
models: readonly ModelDescriptor[],
|
|
63
|
+
model: string,
|
|
64
|
+
{ aliases }: { aliases: boolean },
|
|
65
|
+
): ModelDescriptor | undefined {
|
|
66
|
+
return (
|
|
67
|
+
models.find((row) => row.id === model && (aliases || !isAlias(row))) ??
|
|
68
|
+
models.find((row) => row.resolvedId === model)
|
|
69
|
+
);
|
|
70
|
+
}
|
|
71
|
+
|
|
56
72
|
/**
|
|
57
73
|
* Model lists per harness, login and folder. Concurrent reads of one key share
|
|
58
74
|
* a single CLI read, and a result is stored only if no newer read started
|
|
@@ -142,7 +158,9 @@ export class ModelLists {
|
|
|
142
158
|
* The levels `model` runs on a turn with this login and folder. First the
|
|
143
159
|
* list read for that login; failing that, any login's list or the catalog,
|
|
144
160
|
* but only for a model id that is not an alias: an alias such as Claude's
|
|
145
|
-
* `opus` runs a model that depends on the account and provider.
|
|
161
|
+
* `opus` runs a model that depends on the account and provider. A full id
|
|
162
|
+
* that a list names only through an alias (Claude lists Opus 5.5 as `opus`)
|
|
163
|
+
* takes that row's levels, which are the levels of the model it runs.
|
|
146
164
|
* `undefined` when nothing known applies.
|
|
147
165
|
*/
|
|
148
166
|
thinkingFor(
|
|
@@ -154,22 +172,19 @@ export class ModelLists {
|
|
|
154
172
|
);
|
|
155
173
|
for (const key of own) {
|
|
156
174
|
const list = this.entries.get(key)?.list;
|
|
157
|
-
const found = list?.source === "live" && list.models
|
|
175
|
+
const found = list?.source === "live" && rowFor(list.models, model, { aliases: true });
|
|
158
176
|
if (found) return found.thinking.levels;
|
|
159
177
|
}
|
|
160
178
|
let newest: { levels: readonly ThinkingLevel[]; fetchedAt: number } | undefined;
|
|
161
179
|
for (const { list } of this.entries.values()) {
|
|
162
180
|
if (list.harness !== query.harness || list.source !== "live") continue;
|
|
163
181
|
if (newest && newest.fetchedAt >= list.fetchedAt) continue;
|
|
164
|
-
const found = list.models
|
|
165
|
-
if (found
|
|
166
|
-
newest = { levels: found.thinking.levels, fetchedAt: list.fetchedAt };
|
|
182
|
+
const found = rowFor(list.models, model, { aliases: false });
|
|
183
|
+
if (found) newest = { levels: found.thinking.levels, fetchedAt: list.fetchedAt };
|
|
167
184
|
}
|
|
168
185
|
if (newest) return newest.levels;
|
|
169
|
-
const
|
|
170
|
-
|
|
171
|
-
);
|
|
172
|
-
return listed && !isAlias(listed) ? listed.thinking.levels : undefined;
|
|
186
|
+
const catalog = CATALOG_MODELS.filter((candidate) => candidate.harness === query.harness);
|
|
187
|
+
return rowFor(catalog, model, { aliases: false })?.thinking.levels;
|
|
173
188
|
}
|
|
174
189
|
|
|
175
190
|
private async read(
|
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { decodeLifecycleEvent } from "./lifecycle.ts";
|
|
3
|
+
import { WIRE_ERROR_CODES } from "./wire.ts";
|
|
4
|
+
|
|
5
|
+
/** Portable session history: versioned, append-only event logs that any host
|
|
6
|
+
* can pull, import, fork and follow. These methods never execute agent work. */
|
|
7
|
+
export const HISTORY_METHODS = {
|
|
8
|
+
list: "history/list",
|
|
9
|
+
head: "history/head",
|
|
10
|
+
read: "history/pull",
|
|
11
|
+
import: "history/import",
|
|
12
|
+
fork: "history/fork",
|
|
13
|
+
commit: "history/commit",
|
|
14
|
+
wait: "history/wait",
|
|
15
|
+
checkpoint: "history/checkpoint",
|
|
16
|
+
} as const;
|
|
17
|
+
export const HISTORY_MAX_RECORDS = 256;
|
|
18
|
+
/** How long `history/wait` waits by default before answering with an unchanged head. */
|
|
19
|
+
export const HISTORY_WAIT_TIMEOUT_MS = 15_000;
|
|
20
|
+
export const HISTORY_MAX_BYTES = 8 * 1024 * 1024;
|
|
21
|
+
|
|
22
|
+
const id = z.string().min(1).max(512);
|
|
23
|
+
const seq = z.number().int().min(0).max(Number.MAX_SAFE_INTEGER);
|
|
24
|
+
/** A history: the store that writes it (`sourceId`) and its session. */
|
|
25
|
+
export const SessionRefSchema = z.object({ sourceId: id, sessionId: id });
|
|
26
|
+
export type SessionRef = z.infer<typeof SessionRefSchema>;
|
|
27
|
+
|
|
28
|
+
/** Keep the original JSON intact. Decoding for display is a separate operation,
|
|
29
|
+
* so an older relay cannot strip a newer producer's fields or unknown parts. */
|
|
30
|
+
export const HistoryRecordSchema = z.object({ seq: seq.min(1), event: z.unknown() });
|
|
31
|
+
export type HistoryRecord = z.infer<typeof HistoryRecordSchema>;
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Why a history operation was refused. Stores throw it and the wire carries it
|
|
35
|
+
* (one error code per reason), so a remote store fails the way a local one does:
|
|
36
|
+
* - `missing`: no such history, or not at the requested version;
|
|
37
|
+
* - `conflict`: the request contradicts committed history (another payload or
|
|
38
|
+
* hash for a committed version, a stale expected head, a reused commit id);
|
|
39
|
+
* - `unauthorized`: the host refused this caller;
|
|
40
|
+
* - `invalid`: a malformed request, or one this store cannot hold.
|
|
41
|
+
* None of these succeed when retried unchanged.
|
|
42
|
+
*/
|
|
43
|
+
export class HistoryError extends Error {
|
|
44
|
+
override readonly name = "HistoryError";
|
|
45
|
+
constructor(
|
|
46
|
+
readonly reason: "missing" | "conflict" | "unauthorized" | "invalid",
|
|
47
|
+
message: string,
|
|
48
|
+
) {
|
|
49
|
+
super(message);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** The wire error code of each refusal; clients rebuild the HistoryError from it. */
|
|
54
|
+
export const HISTORY_ERROR_CODES = {
|
|
55
|
+
missing: WIRE_ERROR_CODES.unknownHistory,
|
|
56
|
+
conflict: WIRE_ERROR_CODES.historyConflict,
|
|
57
|
+
unauthorized: WIRE_ERROR_CODES.notAuthorized,
|
|
58
|
+
invalid: WIRE_ERROR_CODES.invalidParams,
|
|
59
|
+
} as const satisfies Record<HistoryError["reason"], number>;
|
|
60
|
+
|
|
61
|
+
/** Parse a history request or slice, refusing a malformed one as `invalid`,
|
|
62
|
+
* the way a remote store refuses it. */
|
|
63
|
+
export function parseHistoryRequest<S extends z.ZodType>(schema: S, value: unknown): z.output<S> {
|
|
64
|
+
const parsed = schema.safeParse(value);
|
|
65
|
+
if (!parsed.success)
|
|
66
|
+
throw new HistoryError(
|
|
67
|
+
"invalid",
|
|
68
|
+
parsed.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join("; "),
|
|
69
|
+
);
|
|
70
|
+
return parsed.data;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export function jsonBytes(value: unknown): number {
|
|
74
|
+
return new TextEncoder().encode(JSON.stringify(value)).byteLength;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Records a history holds: contiguous, of its session, and never raw harness output. */
|
|
78
|
+
export function validateHistoryRecords(sessionId: string, records: readonly HistoryRecord[]): void {
|
|
79
|
+
let previous: number | undefined;
|
|
80
|
+
for (const record of records) {
|
|
81
|
+
if (previous !== undefined && record.seq !== previous + 1)
|
|
82
|
+
throw new HistoryError("invalid", "History records must be contiguous and ordered");
|
|
83
|
+
// Unknown event types are kept as they are; a known type must be well formed.
|
|
84
|
+
let event: ReturnType<typeof decodeLifecycleEvent>;
|
|
85
|
+
try {
|
|
86
|
+
event = decodeLifecycleEvent(record.event);
|
|
87
|
+
} catch {
|
|
88
|
+
throw new HistoryError("invalid", `History record ${record.seq} is a malformed event`);
|
|
89
|
+
}
|
|
90
|
+
if (
|
|
91
|
+
!record.event ||
|
|
92
|
+
typeof record.event !== "object" ||
|
|
93
|
+
(record.event as { sessionId?: unknown }).sessionId !== sessionId
|
|
94
|
+
)
|
|
95
|
+
throw new HistoryError("invalid", "History event belongs to a different session");
|
|
96
|
+
if (event.type === "raw")
|
|
97
|
+
throw new HistoryError("invalid", "Raw harness records are not part of session history");
|
|
98
|
+
if (event.type === "message.part") {
|
|
99
|
+
const raw = record.event as {
|
|
100
|
+
messageId: string;
|
|
101
|
+
part: { sessionId: string; messageId: string };
|
|
102
|
+
};
|
|
103
|
+
if (raw.part.sessionId !== sessionId || raw.part.messageId !== raw.messageId)
|
|
104
|
+
throw new HistoryError("invalid", "History part belongs to a different message or session");
|
|
105
|
+
}
|
|
106
|
+
previous = record.seq;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export const HistoryVersionSchema = SessionRefSchema.extend({
|
|
111
|
+
seq,
|
|
112
|
+
hash: z.string().regex(/^[a-f0-9]{64}$/),
|
|
113
|
+
});
|
|
114
|
+
export type HistoryVersion = z.infer<typeof HistoryVersionSchema>;
|
|
115
|
+
export const HistoryDescriptorSchema = SessionRefSchema.extend({
|
|
116
|
+
format: z.literal(1),
|
|
117
|
+
kind: z.enum(["execution", "branch"]),
|
|
118
|
+
parent: HistoryVersionSchema.optional(),
|
|
119
|
+
});
|
|
120
|
+
export type HistoryDescriptor = z.infer<typeof HistoryDescriptorSchema>;
|
|
121
|
+
export const HistoryHeadSchema = z.object({
|
|
122
|
+
descriptor: HistoryDescriptorSchema,
|
|
123
|
+
version: HistoryVersionSchema,
|
|
124
|
+
});
|
|
125
|
+
export type HistoryHead = z.infer<typeof HistoryHeadSchema>;
|
|
126
|
+
export const HistoryListSchema = z.object({
|
|
127
|
+
after: z.object({ storeId: z.string(), ref: SessionRefSchema }).optional(),
|
|
128
|
+
limit: z.number().int().min(1).max(100).default(50),
|
|
129
|
+
});
|
|
130
|
+
export type HistoryList = z.input<typeof HistoryListSchema>;
|
|
131
|
+
export const HistoryCatalogSchema = z.object({
|
|
132
|
+
entries: z.array(HistoryHeadSchema).max(100),
|
|
133
|
+
next: z.object({ storeId: z.string(), ref: SessionRefSchema }).nullable(),
|
|
134
|
+
});
|
|
135
|
+
export type HistoryCatalog = z.infer<typeof HistoryCatalogSchema>;
|
|
136
|
+
export const HistoryPullSchema = SessionRefSchema.extend({
|
|
137
|
+
after: HistoryVersionSchema.optional(),
|
|
138
|
+
through: HistoryVersionSchema.optional(),
|
|
139
|
+
limit: z.number().int().min(1).max(HISTORY_MAX_RECORDS).default(HISTORY_MAX_RECORDS),
|
|
140
|
+
maxBytes: z.number().int().min(2048).max(HISTORY_MAX_BYTES).default(HISTORY_MAX_BYTES),
|
|
141
|
+
});
|
|
142
|
+
export type HistoryPull = z.input<typeof HistoryPullSchema>;
|
|
143
|
+
export const HistorySliceSchema = z.object({
|
|
144
|
+
descriptor: HistoryDescriptorSchema,
|
|
145
|
+
base: HistoryVersionSchema,
|
|
146
|
+
next: HistoryVersionSchema,
|
|
147
|
+
head: HistoryVersionSchema,
|
|
148
|
+
records: z.array(HistoryRecordSchema).max(HISTORY_MAX_RECORDS),
|
|
149
|
+
hasMore: z.boolean(),
|
|
150
|
+
});
|
|
151
|
+
export type HistorySlice = z.infer<typeof HistorySliceSchema>;
|
|
152
|
+
export const HistoryForkSchema = z.object({
|
|
153
|
+
sessionId: id,
|
|
154
|
+
from: HistoryVersionSchema.optional(),
|
|
155
|
+
});
|
|
156
|
+
export type HistoryFork = z.infer<typeof HistoryForkSchema>;
|
|
157
|
+
export const HistoryCommitSchema = z.object({
|
|
158
|
+
commitId: id,
|
|
159
|
+
expected: HistoryVersionSchema,
|
|
160
|
+
events: z.array(z.unknown()).min(1).max(HISTORY_MAX_RECORDS),
|
|
161
|
+
});
|
|
162
|
+
export type HistoryCommit = z.infer<typeof HistoryCommitSchema>;
|
|
163
|
+
export const HistoryWaitSchema = z.object({
|
|
164
|
+
after: HistoryVersionSchema,
|
|
165
|
+
timeoutMs: z.number().int().min(0).max(20_000).default(HISTORY_WAIT_TIMEOUT_MS),
|
|
166
|
+
});
|
|
167
|
+
export type HistoryWait = z.input<typeof HistoryWaitSchema>;
|
|
168
|
+
|
|
169
|
+
/** Projection cache format changes whenever reducer semantics become incompatible.
|
|
170
|
+
* Raw canonical events remain authoritative and are never pruned by this cache. */
|
|
171
|
+
export const CONVERSATION_CHECKPOINT_FORMAT = "agent-server.conversation.v1";
|
|
172
|
+
export const HistoryCheckpointRequestSchema = z.object({ through: HistoryVersionSchema });
|
|
173
|
+
export type HistoryCheckpointRequest = z.infer<typeof HistoryCheckpointRequestSchema>;
|
|
174
|
+
export const HistoryCheckpointSchema = z.object({
|
|
175
|
+
version: HistoryVersionSchema,
|
|
176
|
+
format: z.string().min(1).max(128),
|
|
177
|
+
/** Unknown formats are ignored by older readers, who replay the canonical log. */
|
|
178
|
+
conversation: z.unknown(),
|
|
179
|
+
});
|
|
180
|
+
export type HistoryCheckpoint = z.infer<typeof HistoryCheckpointSchema>;
|
|
181
|
+
|
|
182
|
+
/** Portable ports: network adapters, Node/Bun stores and cloud hosts implement
|
|
183
|
+
* these same methods. No provider, SQLite or WebSocket dependency. */
|
|
184
|
+
export interface HistoryReader {
|
|
185
|
+
head(ref: { sourceId: string; sessionId: string }): HistoryHead | Promise<HistoryHead>;
|
|
186
|
+
read(request: HistoryPull): HistorySlice | Promise<HistorySlice>;
|
|
187
|
+
/** Optional cached projection at or before the pinned version. Never builds on read. */
|
|
188
|
+
checkpoint?(
|
|
189
|
+
request: HistoryCheckpointRequest,
|
|
190
|
+
): HistoryCheckpoint | null | Promise<HistoryCheckpoint | null>;
|
|
191
|
+
}
|
|
192
|
+
export interface HistoryArchive extends HistoryReader {
|
|
193
|
+
import(slice: HistorySlice): HistoryVersion | Promise<HistoryVersion>;
|
|
194
|
+
}
|
|
195
|
+
export interface HistoryApi extends HistoryArchive {
|
|
196
|
+
checkpoint(
|
|
197
|
+
request: HistoryCheckpointRequest,
|
|
198
|
+
): HistoryCheckpoint | null | Promise<HistoryCheckpoint | null>;
|
|
199
|
+
list(request?: HistoryList): HistoryCatalog | Promise<HistoryCatalog>;
|
|
200
|
+
fork(request: HistoryFork): HistoryHead | Promise<HistoryHead>;
|
|
201
|
+
commit(request: HistoryCommit): HistoryVersion | Promise<HistoryVersion>;
|
|
202
|
+
/** Wakeup only. Always pull the durable suffix after waking. */
|
|
203
|
+
wait(request: HistoryWait, signal?: AbortSignal): Promise<HistoryHead>;
|
|
204
|
+
}
|
|
205
|
+
export interface HistoryStore extends HistoryApi {
|
|
206
|
+
readonly sourceId: string;
|
|
207
|
+
/** Host-local wakeups; storage is authoritative, so callers recheck the head. */
|
|
208
|
+
onChange(listener: (ref: { sourceId: string; sessionId: string }) => void): () => void;
|
|
209
|
+
}
|
|
210
|
+
export function canonicalHistoryJson(value: unknown): string {
|
|
211
|
+
if (value === null || typeof value !== "object") return JSON.stringify(value) ?? "null";
|
|
212
|
+
if (Array.isArray(value)) return `[${value.map(canonicalHistoryJson).join(",")}]`;
|
|
213
|
+
return `{${Object.entries(value)
|
|
214
|
+
.filter(([, v]) => v !== undefined)
|
|
215
|
+
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
|
|
216
|
+
.map(([k, v]) => `${JSON.stringify(k)}:${canonicalHistoryJson(v)}`)
|
|
217
|
+
.join(",")}}`;
|
|
218
|
+
}
|
|
219
|
+
/**
|
|
220
|
+
* The hash chain every store computes alike. A history's version 0 hashes its
|
|
221
|
+
* canonical descriptor; each record's version hashes
|
|
222
|
+
* `canonicalHistoryJson({ event, previous, seq })` — built here from the
|
|
223
|
+
* record's canonical event JSON, so stored bodies hash without re-encoding.
|
|
224
|
+
* A version is the lowercase hex sha256 of its preimage.
|
|
225
|
+
*/
|
|
226
|
+
export function historyRootPreimage(descriptor: HistoryDescriptor): string {
|
|
227
|
+
return canonicalHistoryJson(descriptor);
|
|
228
|
+
}
|
|
229
|
+
export function historyRecordPreimage(previous: string, seq: number, body: string): string {
|
|
230
|
+
return `{"event":${body},"previous":${JSON.stringify(previous)},"seq":${seq}}`;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
export function sameHistory(
|
|
234
|
+
a: { sourceId: string; sessionId: string },
|
|
235
|
+
b: { sourceId: string; sessionId: string },
|
|
236
|
+
) {
|
|
237
|
+
return a.sourceId === b.sourceId && a.sessionId === b.sessionId;
|
|
238
|
+
}
|
|
239
|
+
export function sameVersion(a: HistoryVersion, b: HistoryVersion) {
|
|
240
|
+
return sameHistory(a, b) && a.seq === b.seq && a.hash === b.hash;
|
|
241
|
+
}
|
|
242
|
+
export function validateHistorySlice(value: unknown): HistorySlice {
|
|
243
|
+
const page = parseHistoryRequest(HistorySliceSchema, value);
|
|
244
|
+
if (jsonBytes(page) > HISTORY_MAX_BYTES)
|
|
245
|
+
throw new HistoryError("invalid", "History slice exceeds byte limit");
|
|
246
|
+
if (![page.base, page.next, page.head].every((v) => sameHistory(v, page.descriptor)))
|
|
247
|
+
throw new HistoryError("invalid", "History identity mismatch");
|
|
248
|
+
validateHistoryRecords(page.descriptor.sessionId, page.records);
|
|
249
|
+
const end = page.records.at(-1)?.seq ?? page.base.seq;
|
|
250
|
+
if (
|
|
251
|
+
(page.records.length && page.records[0]!.seq !== page.base.seq + 1) ||
|
|
252
|
+
page.next.seq !== end ||
|
|
253
|
+
end > page.head.seq ||
|
|
254
|
+
page.hasMore !== end < page.head.seq ||
|
|
255
|
+
(!page.records.length && (!sameVersion(page.base, page.next) || page.hasMore)) ||
|
|
256
|
+
(end === page.head.seq && !sameVersion(page.next, page.head))
|
|
257
|
+
)
|
|
258
|
+
throw new HistoryError("invalid", "Invalid history slice boundaries");
|
|
259
|
+
return page;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/** Network SDK methods always return promises; storage ports may be synchronous. */
|
|
263
|
+
export type AsyncHistoryApi = {
|
|
264
|
+
[K in keyof HistoryApi]: (
|
|
265
|
+
...args: Parameters<HistoryApi[K]>
|
|
266
|
+
) => Promise<Awaited<ReturnType<HistoryApi[K]>>>;
|
|
267
|
+
};
|
package/src/protocol/ids.ts
CHANGED
|
@@ -1,12 +1,11 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* UUIDv7 — time-ordered identifiers. The leading 48 bits are a millisecond
|
|
3
3
|
* timestamp, so ids sort chronologically (handy for ordering parts/messages
|
|
4
|
-
* without a separate createdAt column).
|
|
5
|
-
*
|
|
4
|
+
* without a separate createdAt column). Pass `timestamp` when the id names
|
|
5
|
+
* something whose time you also report, so the two agree. Uses Web Crypto,
|
|
6
|
+
* available on both Bun and Node >= 20 via `globalThis.crypto`.
|
|
6
7
|
*/
|
|
7
|
-
export function generateUUIDv7(): string {
|
|
8
|
-
const timestamp = Date.now();
|
|
9
|
-
|
|
8
|
+
export function generateUUIDv7(timestamp = Date.now()): string {
|
|
10
9
|
const rand = new Uint8Array(10);
|
|
11
10
|
crypto.getRandomValues(rand);
|
|
12
11
|
|
package/src/protocol/index.ts
CHANGED