@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.
- package/CHANGELOG.md +73 -0
- package/README.md +30 -2
- package/docs/consuming.md +9 -2
- package/docs/harnesses.md +19 -6
- 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/agents/codex-app-server/adapter.ts +31 -3
- package/src/core/agents/codex-sdk/adapter.ts +45 -15
- package/src/core/agents/codex-sdk/codex-sdk-agent.ts +25 -1
- package/src/core/agents/types.ts +2 -1
- 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
|
@@ -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
package/src/protocol/wire.ts
CHANGED
|
@@ -5,6 +5,7 @@ import {
|
|
|
5
5
|
type DecodedLifecycleEvent,
|
|
6
6
|
LifecycleEventSchema,
|
|
7
7
|
PermissionOutcomeSchema,
|
|
8
|
+
TurnEndedEventSchema,
|
|
8
9
|
type UnknownEvent,
|
|
9
10
|
decodeLifecycleEvent,
|
|
10
11
|
} from "./lifecycle.ts";
|
|
@@ -54,6 +55,25 @@ export const WIRE_ERROR_CODES = {
|
|
|
54
55
|
sessionClosing: -32005,
|
|
55
56
|
/** A turn with this turnId already ran (or is running) with DIFFERENT input. */
|
|
56
57
|
turnConflict: -32006,
|
|
58
|
+
/** A durable session was closed; its id is not reused. */
|
|
59
|
+
sessionClosed: -32007,
|
|
60
|
+
/**
|
|
61
|
+
* The session's last turn was cut off by a server restart and its native
|
|
62
|
+
* execution may still be running. Confirm it stopped (`session/confirmStopped`
|
|
63
|
+
* with `data.headSeq`) before starting another turn.
|
|
64
|
+
*/
|
|
65
|
+
recoveryRequired: -32008,
|
|
66
|
+
/**
|
|
67
|
+
* This server process has not run the durable session yet: pass its
|
|
68
|
+
* `data.nativeSessionId` as `config.resumeSessionId`, or use a new session.
|
|
69
|
+
*/
|
|
70
|
+
resumeRequired: -32009,
|
|
71
|
+
/** The host refused this caller the history operation. */
|
|
72
|
+
notAuthorized: -32010,
|
|
73
|
+
/** No such history, or it does not hold the requested version. */
|
|
74
|
+
unknownHistory: -32011,
|
|
75
|
+
/** The request contradicts committed history (payload, hash, expected head or commit id). */
|
|
76
|
+
historyConflict: -32012,
|
|
57
77
|
} as const;
|
|
58
78
|
|
|
59
79
|
// ---- methods -----------------------------------------------------------------
|
|
@@ -66,6 +86,10 @@ export const WIRE_METHODS = {
|
|
|
66
86
|
permissionRespond: "permission/respond",
|
|
67
87
|
eventsReplay: "events/replay",
|
|
68
88
|
modelsList: "models/list",
|
|
89
|
+
/** Durable servers only (`historyId` in `initialize`); others answer methodNotFound. */
|
|
90
|
+
turnGet: "turn/get",
|
|
91
|
+
sessionGet: "session/get",
|
|
92
|
+
sessionConfirmStopped: "session/confirmStopped",
|
|
69
93
|
shutdown: "shutdown",
|
|
70
94
|
/** Server -> client notification carrying one sequenced lifecycle event. */
|
|
71
95
|
event: "event",
|
|
@@ -95,6 +119,12 @@ export const InitializeResultSchema = z.object({
|
|
|
95
119
|
* fact four downstream heuristics used to guess.
|
|
96
120
|
*/
|
|
97
121
|
instanceId: z.string(),
|
|
122
|
+
/**
|
|
123
|
+
* Durable servers only: the journal's identity, the `sourceId` of every
|
|
124
|
+
* session history it serves. It outlives the process, and so do the session
|
|
125
|
+
* logs: a client keeps its seq cursors while this is unchanged.
|
|
126
|
+
*/
|
|
127
|
+
historyId: z.string().optional(),
|
|
98
128
|
/** Capabilities per registered harness — only available harnesses appear. */
|
|
99
129
|
harnesses: z.record(z.string(), AgentCapabilitiesSchema),
|
|
100
130
|
});
|
|
@@ -124,6 +154,8 @@ export const TurnStartResultSchema = z.object({
|
|
|
124
154
|
* execution happened; catch up on its events via `events/replay`.
|
|
125
155
|
*/
|
|
126
156
|
deduplicated: z.boolean().optional(),
|
|
157
|
+
/** A deduplicated turn that already ended, on a durable server: its `turn.ended`. */
|
|
158
|
+
terminal: TurnEndedEventSchema.optional(),
|
|
127
159
|
});
|
|
128
160
|
export type TurnStartResult = z.infer<typeof TurnStartResultSchema>;
|
|
129
161
|
|
|
@@ -220,6 +252,7 @@ export interface DecodedEventsReplayResult {
|
|
|
220
252
|
events: DecodedWireEventEnvelope[];
|
|
221
253
|
firstAvailableSeq: number | null;
|
|
222
254
|
latestSeq: number | null;
|
|
255
|
+
hasMore?: boolean;
|
|
223
256
|
}
|
|
224
257
|
|
|
225
258
|
/**
|
|
@@ -234,6 +267,7 @@ export function decodeEventsReplayResult(value: unknown): DecodedEventsReplayRes
|
|
|
234
267
|
events: z.array(z.unknown()),
|
|
235
268
|
firstAvailableSeq: z.number().int().positive().nullable(),
|
|
236
269
|
latestSeq: z.number().int().positive().nullable(),
|
|
270
|
+
hasMore: z.boolean().optional(),
|
|
237
271
|
})
|
|
238
272
|
.parse(value);
|
|
239
273
|
return { ...parsed, events: parsed.events.map((event) => decodeWireEventEnvelope(event)) };
|
|
@@ -249,12 +283,14 @@ export type EventsReplayParams = z.infer<typeof EventsReplayParamsSchema>;
|
|
|
249
283
|
/**
|
|
250
284
|
* Replay is served from a bounded per-session ring buffer. When
|
|
251
285
|
* `firstAvailableSeq > fromSeq`, the requested prefix was evicted and the gap
|
|
252
|
-
* is unfillable — the consumer must treat its local view as stale.
|
|
286
|
+
* is unfillable — the consumer must treat its local view as stale. A durable
|
|
287
|
+
* server keeps every event and answers in pages: `hasMore` asks for the next.
|
|
253
288
|
*/
|
|
254
289
|
export const EventsReplayResultSchema = z.object({
|
|
255
290
|
events: z.array(WireEventEnvelopeSchema),
|
|
256
291
|
firstAvailableSeq: z.number().int().positive().nullable(),
|
|
257
292
|
latestSeq: z.number().int().positive().nullable(),
|
|
293
|
+
hasMore: z.boolean().optional(),
|
|
258
294
|
});
|
|
259
295
|
export type EventsReplayResult = z.infer<typeof EventsReplayResultSchema>;
|
|
260
296
|
|
|
@@ -279,6 +315,51 @@ export type ModelsListParams = z.infer<typeof ModelsListParamsSchema>;
|
|
|
279
315
|
/** Never an error for an available harness: without a live list it is the catalog, with `error`. */
|
|
280
316
|
export const ModelsListResultSchema = ModelListSchema;
|
|
281
317
|
|
|
318
|
+
/**
|
|
319
|
+
* `turn/get`: a durable turn's receipt. Admission records it, with the input,
|
|
320
|
+
* before the `turn/start` ack, so a turn whose process died before its first
|
|
321
|
+
* event is still known; `interrupted` means a restart cut it off.
|
|
322
|
+
*/
|
|
323
|
+
export const TurnGetParamsSchema = z.object({ sessionId: z.string(), turnId: z.string() });
|
|
324
|
+
export type TurnGetParams = z.infer<typeof TurnGetParamsSchema>;
|
|
325
|
+
export const TurnReceiptSchema = TurnGetParamsSchema.extend({
|
|
326
|
+
state: z.enum(["admitted", "completed", "interrupted"]),
|
|
327
|
+
input: AgentInputSchema.optional(),
|
|
328
|
+
terminal: TurnEndedEventSchema.optional(),
|
|
329
|
+
});
|
|
330
|
+
export type TurnReceipt = z.infer<typeof TurnReceiptSchema>;
|
|
331
|
+
|
|
332
|
+
/** `session/get`: what a durable server knows about a session. */
|
|
333
|
+
export const SessionGetParamsSchema = z.object({ sessionId: z.string() });
|
|
334
|
+
export type SessionGetParams = z.infer<typeof SessionGetParamsSchema>;
|
|
335
|
+
export const DurableSessionSchema = z.object({
|
|
336
|
+
sessionId: z.string(),
|
|
337
|
+
harness: AgentHarnessSchema,
|
|
338
|
+
/** The seq of its latest event; 0 before the first. */
|
|
339
|
+
headSeq: z.number().int().nonnegative(),
|
|
340
|
+
nativeSessionId: z.string().nullable(),
|
|
341
|
+
closed: z.boolean(),
|
|
342
|
+
/** A restart cut off a turn: see `recoveryRequired` and `session/confirmStopped`. */
|
|
343
|
+
recoveryRequired: z.boolean(),
|
|
344
|
+
});
|
|
345
|
+
export type DurableSession = z.infer<typeof DurableSessionSchema>;
|
|
346
|
+
|
|
347
|
+
/**
|
|
348
|
+
* `session/confirmStopped`: the caller checked that the native execution a
|
|
349
|
+
* restart cut off is no longer running (history alone cannot prove that a
|
|
350
|
+
* detached agent or tool process died). `expectedHeadSeq` fences a stale
|
|
351
|
+
* confirmation against a newer interruption.
|
|
352
|
+
*/
|
|
353
|
+
export const SessionConfirmStoppedParamsSchema = z.object({
|
|
354
|
+
sessionId: z.string(),
|
|
355
|
+
expectedHeadSeq: z.number().int().nonnegative(),
|
|
356
|
+
confirmedStopped: z.literal(true),
|
|
357
|
+
});
|
|
358
|
+
export type SessionConfirmStoppedParams = z.infer<typeof SessionConfirmStoppedParamsSchema>;
|
|
359
|
+
/** `recovered: false` when nothing awaited confirmation. */
|
|
360
|
+
export const SessionConfirmStoppedResultSchema = z.object({ recovered: z.boolean() });
|
|
361
|
+
export type SessionConfirmStoppedResult = z.infer<typeof SessionConfirmStoppedResultSchema>;
|
|
362
|
+
|
|
282
363
|
export const ShutdownParamsSchema = z.object({}).optional();
|
|
283
364
|
export const ShutdownResultSchema = z.object({});
|
|
284
365
|
|