@qlairoslabs/acp-client 0.6.0 → 0.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CONSUMER_GUIDE.md +618 -291
- package/README.md +25 -0
- package/package.json +1 -1
- package/src/agent-session.ts +2188 -96
- package/src/cli/index.ts +33 -5
- package/src/cli/managed.ts +220 -0
- package/src/command-descriptors.ts +22 -0
- package/src/controller.ts +87 -37
- package/src/index.ts +229 -3
- package/src/metering/engine.ts +9 -1
- package/src/metering/record.ts +2 -1
- package/src/persistence/activity-projection.ts +71 -0
- package/src/persistence/audit-log-reader.ts +506 -0
- package/src/persistence/audit-runtime.ts +162 -0
- package/src/persistence/checkpoint.ts +304 -0
- package/src/persistence/config.ts +538 -0
- package/src/persistence/configuration-state.ts +191 -0
- package/src/persistence/deletion.ts +227 -0
- package/src/persistence/file-registry-store.ts +740 -0
- package/src/persistence/integrity.ts +147 -0
- package/src/persistence/legacy-registry-import.ts +240 -0
- package/src/persistence/managed-checkpoint.ts +81 -0
- package/src/persistence/managed-creation.ts +456 -0
- package/src/persistence/managed-load.ts +172 -0
- package/src/persistence/managed-registry.ts +57 -0
- package/src/persistence/migration.ts +298 -0
- package/src/persistence/paths.ts +172 -0
- package/src/persistence/projection.ts +373 -0
- package/src/persistence/reconfiguration.ts +453 -0
- package/src/persistence/records.ts +873 -0
- package/src/persistence/reducer.ts +498 -0
- package/src/persistence/registry.ts +446 -0
- package/src/persistence/restoration.ts +689 -0
- package/src/persistence/session-log-writer.ts +480 -0
- package/src/persistence/state-runtime.ts +176 -0
- package/src/persistence/transcript-reader.ts +980 -0
- package/src/persistence/transcript-runtime.ts +667 -0
- package/src/persistence/transcript-scanner.ts +385 -0
- package/src/persistence/truncation.ts +276 -0
- package/src/repl/agent-session-commands.ts +74 -1
- package/src/repl/commands.ts +1 -1
- package/src/repl/index.ts +7 -1
- package/src/session-manager.ts +257 -7
- package/src/transcript.ts +3 -3
|
@@ -0,0 +1,740 @@
|
|
|
1
|
+
import {
|
|
2
|
+
chmod,
|
|
3
|
+
copyFile,
|
|
4
|
+
mkdir,
|
|
5
|
+
open,
|
|
6
|
+
readFile,
|
|
7
|
+
rename,
|
|
8
|
+
stat,
|
|
9
|
+
unlink,
|
|
10
|
+
} from "node:fs/promises";
|
|
11
|
+
import { isAbsolute, join } from "node:path";
|
|
12
|
+
import { randomUUID } from "node:crypto";
|
|
13
|
+
import { resolvePersistenceRoot } from "./config.ts";
|
|
14
|
+
import { validateSessionConfigurationCheckpoint } from "./checkpoint.ts";
|
|
15
|
+
import {
|
|
16
|
+
AgentSessionStoreConflictError,
|
|
17
|
+
SessionMaintenanceInProgressError,
|
|
18
|
+
summarizeAgentSessionRecord,
|
|
19
|
+
validateAgentSessionRecord,
|
|
20
|
+
type AgentSessionListPage,
|
|
21
|
+
type AgentSessionRecord,
|
|
22
|
+
type AgentSessionStore,
|
|
23
|
+
type AgentSessionsRegistryFile,
|
|
24
|
+
type ListAgentSessionsOptions,
|
|
25
|
+
type ListSessionMaintenanceOptions,
|
|
26
|
+
type MaintenanceCompletionReceipt,
|
|
27
|
+
type PrepareMaintenanceResult,
|
|
28
|
+
type SessionMaintenance,
|
|
29
|
+
type SessionMaintenancePage,
|
|
30
|
+
} from "./registry.ts";
|
|
31
|
+
import { canonicalizeJson } from "./integrity.ts";
|
|
32
|
+
|
|
33
|
+
const REGISTRY_FILENAME = "agent-sessions.json";
|
|
34
|
+
const MAX_RECEIPTS_PER_SESSION = 32;
|
|
35
|
+
const MAX_RECEIPTS_GLOBAL = 4_096;
|
|
36
|
+
|
|
37
|
+
export interface RegistryRecoveryNotice {
|
|
38
|
+
readonly source: "backup";
|
|
39
|
+
readonly primaryError: Error;
|
|
40
|
+
readonly recoveredRevision: number;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface FileAgentSessionStoreOptions {
|
|
44
|
+
readonly root?: string;
|
|
45
|
+
readonly lockTimeoutMs?: number;
|
|
46
|
+
readonly lockRetryMs?: number;
|
|
47
|
+
readonly onRecovery?: (notice: RegistryRecoveryNotice) => void;
|
|
48
|
+
/** Test/embedding clock; it must return canonical ISO-8601. */
|
|
49
|
+
readonly now?: () => string;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export class AgentSessionRegistryError extends Error {
|
|
53
|
+
constructor(message: string, options?: ErrorOptions) {
|
|
54
|
+
super(message, options);
|
|
55
|
+
this.name = "AgentSessionRegistryError";
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export class AgentSessionRegistryLockError extends AgentSessionRegistryError {
|
|
60
|
+
constructor(message: string, options?: ErrorOptions) {
|
|
61
|
+
super(message, options);
|
|
62
|
+
this.name = "AgentSessionRegistryLockError";
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export class AgentSessionRegistryCursorError extends AgentSessionRegistryError {
|
|
67
|
+
constructor(message: string) {
|
|
68
|
+
super(message);
|
|
69
|
+
this.name = "AgentSessionRegistryCursorError";
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export class MaintenanceOutcomeUnknownError extends AgentSessionRegistryError {
|
|
74
|
+
constructor(readonly agentSessionId: string, readonly operationId: string) {
|
|
75
|
+
super(`maintenance outcome is unknown for ${agentSessionId}/${operationId}`);
|
|
76
|
+
this.name = "MaintenanceOutcomeUnknownError";
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Atomic full-JSON implementation of the strict AgentSessionStore contract. */
|
|
81
|
+
export class FileAgentSessionStore implements AgentSessionStore {
|
|
82
|
+
readonly root: string;
|
|
83
|
+
readonly path: string;
|
|
84
|
+
readonly backupPath: string;
|
|
85
|
+
private readonly lockPath: string;
|
|
86
|
+
private readonly lockTimeoutMs: number;
|
|
87
|
+
private readonly lockRetryMs: number;
|
|
88
|
+
private readonly onRecovery?: (notice: RegistryRecoveryNotice) => void;
|
|
89
|
+
private readonly now: () => string;
|
|
90
|
+
|
|
91
|
+
constructor(options: FileAgentSessionStoreOptions = {}) {
|
|
92
|
+
this.root = resolvePersistenceRoot(options.root);
|
|
93
|
+
this.path = join(this.root, REGISTRY_FILENAME);
|
|
94
|
+
this.backupPath = `${this.path}.bak`;
|
|
95
|
+
this.lockPath = `${this.path}.lock`;
|
|
96
|
+
this.lockTimeoutMs = boundedInteger(options.lockTimeoutMs ?? 5_000, 100, 120_000, "lockTimeoutMs");
|
|
97
|
+
this.lockRetryMs = boundedInteger(options.lockRetryMs ?? 20, 1, 1_000, "lockRetryMs");
|
|
98
|
+
this.onRecovery = options.onRecovery;
|
|
99
|
+
this.now = options.now ?? (() => new Date().toISOString());
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
async getAgentSessionRecord(agentSessionId: string): Promise<AgentSessionRecord | null> {
|
|
103
|
+
const file = await this.readRegistry();
|
|
104
|
+
const record = file.sessions[agentSessionId];
|
|
105
|
+
return record ? structuredClone(record) : null;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
async getMaintenance(agentSessionId: string): Promise<SessionMaintenance | null> {
|
|
109
|
+
const value = (await this.readRegistry()).maintenance[agentSessionId];
|
|
110
|
+
return value ? structuredClone(value) : null;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
async saveAgentSessionRecord(
|
|
114
|
+
record: AgentSessionRecord,
|
|
115
|
+
options:
|
|
116
|
+
| { readonly expectedRecordRevision: null; readonly expectedIncarnationId: null }
|
|
117
|
+
| { readonly expectedRecordRevision: number; readonly expectedIncarnationId: string },
|
|
118
|
+
): Promise<AgentSessionRecord> {
|
|
119
|
+
validateAgentSessionRecord(record);
|
|
120
|
+
return this.mutate(async (file) => {
|
|
121
|
+
rejectMaintenance(file, record.agentSessionId);
|
|
122
|
+
const current = file.sessions[record.agentSessionId] ?? null;
|
|
123
|
+
validateRecordCas(current, record, options);
|
|
124
|
+
file.sessions[record.agentSessionId] = structuredClone(record);
|
|
125
|
+
return structuredClone(record);
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
async deleteAgentSessionRecord(
|
|
130
|
+
agentSessionId: string,
|
|
131
|
+
options: { readonly expectedRecordRevision: number; readonly expectedIncarnationId: string },
|
|
132
|
+
): Promise<void> {
|
|
133
|
+
await this.mutate(async (file) => {
|
|
134
|
+
rejectMaintenance(file, agentSessionId);
|
|
135
|
+
const current = file.sessions[agentSessionId];
|
|
136
|
+
if (!current) throw new AgentSessionStoreConflictError("agent-session record does not exist");
|
|
137
|
+
assertExistingCas(current, options.expectedRecordRevision, options.expectedIncarnationId);
|
|
138
|
+
delete file.sessions[agentSessionId];
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
async listAgentSessions(options: ListAgentSessionsOptions = {}): Promise<AgentSessionListPage> {
|
|
143
|
+
const file = await this.readRegistry();
|
|
144
|
+
const limit = listLimit(options.limit);
|
|
145
|
+
const order = options.order ?? "updated_desc";
|
|
146
|
+
const includeDeleted = options.includeDeleted ?? false;
|
|
147
|
+
const offset = decodeCursor(options.cursor, "sessions", file.revision, { order, includeDeleted });
|
|
148
|
+
const rows = Object.values(file.sessions)
|
|
149
|
+
.filter((record) => {
|
|
150
|
+
const maintenance = file.maintenance[record.agentSessionId];
|
|
151
|
+
if (!includeDeleted && (record.deletion || maintenance?.kind === "deletion")) return false;
|
|
152
|
+
return true;
|
|
153
|
+
})
|
|
154
|
+
.sort(sessionComparator(order))
|
|
155
|
+
.map((record) => summarizeAgentSessionRecord(record, file.maintenance[record.agentSessionId]));
|
|
156
|
+
const sessions = rows.slice(offset, offset + limit);
|
|
157
|
+
const nextOffset = offset + sessions.length;
|
|
158
|
+
const hasMore = nextOffset < rows.length;
|
|
159
|
+
return {
|
|
160
|
+
sessions,
|
|
161
|
+
nextCursor: hasMore
|
|
162
|
+
? encodeCursor({ v: 1, kind: "sessions", revision: file.revision, offset: nextOffset, filter: { order, includeDeleted } }) as never
|
|
163
|
+
: null,
|
|
164
|
+
hasMore,
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
async listMaintenance(options: ListSessionMaintenanceOptions = {}): Promise<SessionMaintenancePage> {
|
|
169
|
+
const file = await this.readRegistry();
|
|
170
|
+
const limit = listLimit(options.limit);
|
|
171
|
+
const offset = decodeCursor(options.cursor, "maintenance", file.revision, {});
|
|
172
|
+
const rows = Object.entries(file.maintenance)
|
|
173
|
+
.map(([agentSessionId, value]) => ({
|
|
174
|
+
agentSessionId,
|
|
175
|
+
incarnationId: value.incarnationId,
|
|
176
|
+
kind: value.kind,
|
|
177
|
+
operationId: value.operationId,
|
|
178
|
+
startedAt: value.startedAt,
|
|
179
|
+
}))
|
|
180
|
+
.sort((a, b) => a.startedAt.localeCompare(b.startedAt) || a.agentSessionId.localeCompare(b.agentSessionId));
|
|
181
|
+
const maintenance = rows.slice(offset, offset + limit);
|
|
182
|
+
const nextOffset = offset + maintenance.length;
|
|
183
|
+
const hasMore = nextOffset < rows.length;
|
|
184
|
+
return {
|
|
185
|
+
maintenance,
|
|
186
|
+
nextCursor: hasMore
|
|
187
|
+
? encodeCursor({ v: 1, kind: "maintenance", revision: file.revision, offset: nextOffset, filter: {} }) as never
|
|
188
|
+
: null,
|
|
189
|
+
hasMore,
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
async prepareMaintenance(
|
|
194
|
+
agentSessionId: string,
|
|
195
|
+
maintenance: SessionMaintenance,
|
|
196
|
+
options: { readonly expectedRecordRevision: number | null },
|
|
197
|
+
): Promise<PrepareMaintenanceResult> {
|
|
198
|
+
validateMaintenance(agentSessionId, maintenance);
|
|
199
|
+
return this.mutate(async (file, mutation) => {
|
|
200
|
+
const receipt = findReceipt(file, agentSessionId, maintenance.incarnationId, maintenance.operationId);
|
|
201
|
+
if (receipt) {
|
|
202
|
+
if (receipt.requestDigest !== maintenance.requestDigest) {
|
|
203
|
+
throw new AgentSessionStoreConflictError("maintenance operationId was completed with another request digest");
|
|
204
|
+
}
|
|
205
|
+
mutation.changed = false;
|
|
206
|
+
return { status: "already_completed", receipt: structuredClone(receipt) };
|
|
207
|
+
}
|
|
208
|
+
const prepared = file.maintenance[agentSessionId];
|
|
209
|
+
if (prepared) {
|
|
210
|
+
if (sameMaintenanceIdentity(prepared, maintenance)) {
|
|
211
|
+
if (maintenance.baseRecordRevision !== options.expectedRecordRevision) {
|
|
212
|
+
throw new AgentSessionStoreConflictError("maintenance base revision disagrees with expected revision");
|
|
213
|
+
}
|
|
214
|
+
mutation.changed = false;
|
|
215
|
+
return { status: "already_prepared", maintenance: structuredClone(prepared) };
|
|
216
|
+
}
|
|
217
|
+
throw new SessionMaintenanceInProgressError(agentSessionId);
|
|
218
|
+
}
|
|
219
|
+
if (maintenance.baseRecordRevision !== options.expectedRecordRevision) {
|
|
220
|
+
throw new AgentSessionStoreConflictError("maintenance base revision disagrees with expected revision");
|
|
221
|
+
}
|
|
222
|
+
const current = file.sessions[agentSessionId] ?? null;
|
|
223
|
+
if (maintenance.kind === "creation") {
|
|
224
|
+
if (current || options.expectedRecordRevision !== null) {
|
|
225
|
+
throw new AgentSessionStoreConflictError("creation requires an unused logical identity");
|
|
226
|
+
}
|
|
227
|
+
} else {
|
|
228
|
+
if (!current || options.expectedRecordRevision === null) {
|
|
229
|
+
throw new AgentSessionStoreConflictError("existing-session maintenance requires a record");
|
|
230
|
+
}
|
|
231
|
+
assertExistingCas(current, options.expectedRecordRevision, maintenance.incarnationId);
|
|
232
|
+
}
|
|
233
|
+
file.maintenance[agentSessionId] = structuredClone(maintenance);
|
|
234
|
+
return { status: "prepared", maintenance: structuredClone(maintenance) };
|
|
235
|
+
});
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
async updateMaintenance(
|
|
239
|
+
agentSessionId: string,
|
|
240
|
+
expectedIncarnationId: string,
|
|
241
|
+
operationId: string,
|
|
242
|
+
update: SessionMaintenance,
|
|
243
|
+
): Promise<void> {
|
|
244
|
+
validateMaintenance(agentSessionId, update);
|
|
245
|
+
await this.mutate(async (file) => {
|
|
246
|
+
const current = file.maintenance[agentSessionId];
|
|
247
|
+
if (!current) throw new AgentSessionStoreConflictError("maintenance reservation does not exist");
|
|
248
|
+
assertMaintenanceIdentity(current, expectedIncarnationId, operationId, update.requestDigest);
|
|
249
|
+
validateMaintenanceAdvance(current, update);
|
|
250
|
+
file.maintenance[agentSessionId] = structuredClone(update);
|
|
251
|
+
});
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
async finalizeMaintenance(
|
|
255
|
+
agentSessionId: string,
|
|
256
|
+
expectedIncarnationId: string,
|
|
257
|
+
operationId: string,
|
|
258
|
+
requestDigest: string,
|
|
259
|
+
mutation:
|
|
260
|
+
| { readonly save: AgentSessionRecord; readonly deleteRecord?: never }
|
|
261
|
+
| { readonly save?: never; readonly deleteRecord: true },
|
|
262
|
+
): Promise<void> {
|
|
263
|
+
await this.mutate(async (file, state) => {
|
|
264
|
+
const currentMaintenance = file.maintenance[agentSessionId];
|
|
265
|
+
if (!currentMaintenance) {
|
|
266
|
+
const receipt = findReceipt(file, agentSessionId, expectedIncarnationId, operationId);
|
|
267
|
+
if (receipt?.requestDigest === requestDigest) {
|
|
268
|
+
state.changed = false;
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
271
|
+
if (receipt) throw new AgentSessionStoreConflictError("completed maintenance request digest mismatch");
|
|
272
|
+
throw new MaintenanceOutcomeUnknownError(agentSessionId, operationId);
|
|
273
|
+
}
|
|
274
|
+
assertMaintenanceIdentity(currentMaintenance, expectedIncarnationId, operationId, requestDigest);
|
|
275
|
+
const currentRecord = file.sessions[agentSessionId] ?? null;
|
|
276
|
+
if (currentMaintenance.kind === "creation") {
|
|
277
|
+
if (currentRecord) throw new AgentSessionStoreConflictError("creation finalization found an existing record");
|
|
278
|
+
} else {
|
|
279
|
+
if (!currentRecord) throw new AgentSessionStoreConflictError("maintenance finalization lost its record");
|
|
280
|
+
assertExistingCas(currentRecord, currentMaintenance.baseRecordRevision, expectedIncarnationId);
|
|
281
|
+
}
|
|
282
|
+
if ("save" in mutation && mutation.save !== undefined) {
|
|
283
|
+
validateAgentSessionRecord(mutation.save);
|
|
284
|
+
if (mutation.save.agentSessionId !== agentSessionId || mutation.save.incarnationId !== expectedIncarnationId) {
|
|
285
|
+
throw new AgentSessionStoreConflictError("finalized record identity mismatch");
|
|
286
|
+
}
|
|
287
|
+
const expectedRevision = currentMaintenance.kind === "creation" ? 1 : currentMaintenance.baseRecordRevision + 1;
|
|
288
|
+
if (mutation.save.recordRevision !== expectedRevision) {
|
|
289
|
+
throw new AgentSessionStoreConflictError("finalized recordRevision is invalid");
|
|
290
|
+
}
|
|
291
|
+
if (currentMaintenance.kind === "creation" || currentMaintenance.kind === "restoration") {
|
|
292
|
+
const staged = currentMaintenance.details.stagedRecord;
|
|
293
|
+
if (!staged || canonicalizeJson(staged) !== canonicalizeJson(mutation.save)) {
|
|
294
|
+
throw new AgentSessionStoreConflictError("finalization must publish the exact stagedRecord");
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
file.sessions[agentSessionId] = structuredClone(mutation.save);
|
|
298
|
+
} else {
|
|
299
|
+
if (currentMaintenance.kind !== "deletion") {
|
|
300
|
+
throw new AgentSessionStoreConflictError("only deletion maintenance may remove a registry record");
|
|
301
|
+
}
|
|
302
|
+
delete file.sessions[agentSessionId];
|
|
303
|
+
}
|
|
304
|
+
delete file.maintenance[agentSessionId];
|
|
305
|
+
addReceipt(file, {
|
|
306
|
+
agentSessionId,
|
|
307
|
+
incarnationId: expectedIncarnationId,
|
|
308
|
+
kind: currentMaintenance.kind,
|
|
309
|
+
operationId,
|
|
310
|
+
requestDigest,
|
|
311
|
+
outcome: "completed",
|
|
312
|
+
completedAt: this.checkedNow(),
|
|
313
|
+
});
|
|
314
|
+
});
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
private async mutate<T>(
|
|
318
|
+
apply: (file: MutableRegistry, state: { changed: boolean }) => Promise<T>,
|
|
319
|
+
): Promise<T> {
|
|
320
|
+
const lock = await this.acquireLock();
|
|
321
|
+
try {
|
|
322
|
+
const loaded = await this.loadRegistry();
|
|
323
|
+
const existing = loaded.file;
|
|
324
|
+
const file = structuredClone(existing) as MutableRegistry;
|
|
325
|
+
const state = { changed: true };
|
|
326
|
+
const result = await apply(file, state);
|
|
327
|
+
if (state.changed) {
|
|
328
|
+
file.revision = existing.revision + 1;
|
|
329
|
+
file.updatedAt = this.checkedNow();
|
|
330
|
+
validateRegistry(file);
|
|
331
|
+
await this.writeRegistry(file, loaded.primaryValid && existing.revision > 0);
|
|
332
|
+
}
|
|
333
|
+
return result;
|
|
334
|
+
} finally {
|
|
335
|
+
await lock.release();
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
private async readRegistry(): Promise<AgentSessionsRegistryFile> {
|
|
340
|
+
return (await this.loadRegistry()).file;
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
private async loadRegistry(): Promise<{ file: AgentSessionsRegistryFile; primaryValid: boolean }> {
|
|
344
|
+
let primaryError: Error | null = null;
|
|
345
|
+
try {
|
|
346
|
+
return { file: await readAndValidate(this.path), primaryValid: true };
|
|
347
|
+
} catch (error) {
|
|
348
|
+
if (isMissing(error)) {
|
|
349
|
+
try {
|
|
350
|
+
await stat(this.backupPath);
|
|
351
|
+
} catch (backupError) {
|
|
352
|
+
if (isMissing(backupError)) return { file: emptyRegistry(), primaryValid: false };
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
primaryError = asError(error);
|
|
356
|
+
}
|
|
357
|
+
try {
|
|
358
|
+
const recovered = await readAndValidate(this.backupPath);
|
|
359
|
+
try {
|
|
360
|
+
this.onRecovery?.({ source: "backup", primaryError, recoveredRevision: recovered.revision });
|
|
361
|
+
} catch {
|
|
362
|
+
// Observation must not turn a successful, validated recovery into data loss.
|
|
363
|
+
}
|
|
364
|
+
return { file: recovered, primaryValid: false };
|
|
365
|
+
} catch (backupError) {
|
|
366
|
+
throw new AgentSessionRegistryError("primary and backup registries are unavailable or invalid", {
|
|
367
|
+
cause: new AggregateError([primaryError, asError(backupError)]),
|
|
368
|
+
});
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
private async writeRegistry(file: AgentSessionsRegistryFile, hadPrimary: boolean): Promise<void> {
|
|
373
|
+
await mkdir(this.root, { recursive: true, mode: 0o700 });
|
|
374
|
+
await chmod(this.root, 0o700).catch(() => undefined);
|
|
375
|
+
const token = `${process.pid}-${randomUUID()}`;
|
|
376
|
+
const nextPath = join(this.root, `.${REGISTRY_FILENAME}.${token}.tmp`);
|
|
377
|
+
const backupTemp = `${this.backupPath}.${token}.tmp`;
|
|
378
|
+
try {
|
|
379
|
+
await writeSynced(nextPath, `${JSON.stringify(file, null, 2)}\n`);
|
|
380
|
+
if (hadPrimary) {
|
|
381
|
+
await copyFile(this.path, backupTemp);
|
|
382
|
+
await chmod(backupTemp, 0o600).catch(() => undefined);
|
|
383
|
+
await syncFile(backupTemp);
|
|
384
|
+
await rename(backupTemp, this.backupPath);
|
|
385
|
+
await syncDirectory(this.root);
|
|
386
|
+
}
|
|
387
|
+
await rename(nextPath, this.path);
|
|
388
|
+
await syncDirectory(this.root);
|
|
389
|
+
} finally {
|
|
390
|
+
await unlink(nextPath).catch(() => undefined);
|
|
391
|
+
await unlink(backupTemp).catch(() => undefined);
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
private async acquireLock(): Promise<{ release(): Promise<void> }> {
|
|
396
|
+
await mkdir(this.root, { recursive: true, mode: 0o700 });
|
|
397
|
+
const deadline = Date.now() + this.lockTimeoutMs;
|
|
398
|
+
const token = randomUUID();
|
|
399
|
+
for (;;) {
|
|
400
|
+
let handle;
|
|
401
|
+
try {
|
|
402
|
+
handle = await open(this.lockPath, "wx", 0o600);
|
|
403
|
+
} catch (error) {
|
|
404
|
+
if (!isExists(error)) throw new AgentSessionRegistryLockError("cannot acquire registry lock", { cause: error });
|
|
405
|
+
if (await this.removeProvablyDeadLock()) continue;
|
|
406
|
+
if (Date.now() >= deadline) throw new AgentSessionRegistryLockError("timed out waiting for registry lock");
|
|
407
|
+
await delay(this.lockRetryMs);
|
|
408
|
+
continue;
|
|
409
|
+
}
|
|
410
|
+
try {
|
|
411
|
+
await handle.writeFile(JSON.stringify({ pid: process.pid, token, createdAt: this.checkedNow() }), "utf8");
|
|
412
|
+
await handle.sync();
|
|
413
|
+
} catch (error) {
|
|
414
|
+
await handle.close().catch(() => undefined);
|
|
415
|
+
await unlink(this.lockPath).catch(() => undefined);
|
|
416
|
+
throw new AgentSessionRegistryLockError("cannot initialize registry lock", { cause: error });
|
|
417
|
+
}
|
|
418
|
+
return {
|
|
419
|
+
release: async () => {
|
|
420
|
+
await handle.close();
|
|
421
|
+
try {
|
|
422
|
+
const current = JSON.parse(await readFile(this.lockPath, "utf8")) as { token?: unknown };
|
|
423
|
+
if (current.token === token) await unlink(this.lockPath);
|
|
424
|
+
} catch {
|
|
425
|
+
// Already released/replaced; never remove a lock whose token is not ours.
|
|
426
|
+
}
|
|
427
|
+
},
|
|
428
|
+
};
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
private async removeProvablyDeadLock(): Promise<boolean> {
|
|
433
|
+
try {
|
|
434
|
+
const raw = await readFile(this.lockPath, "utf8");
|
|
435
|
+
const parsed = JSON.parse(raw) as { pid?: unknown; token?: unknown };
|
|
436
|
+
if (!Number.isSafeInteger(parsed.pid) || (parsed.pid as number) < 1 || typeof parsed.token !== "string") return false;
|
|
437
|
+
try {
|
|
438
|
+
process.kill(parsed.pid as number, 0);
|
|
439
|
+
return false;
|
|
440
|
+
} catch (error) {
|
|
441
|
+
const code = (error as NodeJS.ErrnoException).code;
|
|
442
|
+
if (code !== "ESRCH") return false;
|
|
443
|
+
}
|
|
444
|
+
// Re-read before unlinking so a replaced lock cannot be removed using stale evidence.
|
|
445
|
+
if (await readFile(this.lockPath, "utf8") !== raw) return false;
|
|
446
|
+
await unlink(this.lockPath);
|
|
447
|
+
return true;
|
|
448
|
+
} catch {
|
|
449
|
+
return false;
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
private checkedNow(): string {
|
|
454
|
+
const value = this.now();
|
|
455
|
+
if (!Number.isFinite(Date.parse(value)) || new Date(value).toISOString() !== value) {
|
|
456
|
+
throw new AgentSessionRegistryError("registry clock returned a noncanonical timestamp");
|
|
457
|
+
}
|
|
458
|
+
return value;
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
interface MutableRegistry {
|
|
463
|
+
version: 1;
|
|
464
|
+
revision: number;
|
|
465
|
+
updatedAt: string;
|
|
466
|
+
sessions: Record<string, AgentSessionRecord>;
|
|
467
|
+
maintenance: Record<string, SessionMaintenance>;
|
|
468
|
+
maintenanceReceipts: Record<string, MaintenanceCompletionReceipt[]>;
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
function emptyRegistry(): MutableRegistry {
|
|
472
|
+
return { version: 1, revision: 0, updatedAt: "1970-01-01T00:00:00.000Z", sessions: {}, maintenance: {}, maintenanceReceipts: {} };
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
async function readAndValidate(path: string): Promise<AgentSessionsRegistryFile> {
|
|
476
|
+
const value = JSON.parse(await readFile(path, "utf8")) as unknown;
|
|
477
|
+
validateRegistry(value);
|
|
478
|
+
return value;
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
function validateRegistry(value: unknown): asserts value is AgentSessionsRegistryFile {
|
|
482
|
+
if (!isRecord(value) || value.version !== 1) throw new AgentSessionRegistryError("unsupported or malformed registry version");
|
|
483
|
+
nonnegativeInteger(value.revision, "registry revision");
|
|
484
|
+
canonicalIso(value.updatedAt, "registry updatedAt");
|
|
485
|
+
if (!isRecord(value.sessions) || !isRecord(value.maintenance) || !isRecord(value.maintenanceReceipts)) {
|
|
486
|
+
throw new AgentSessionRegistryError("registry maps are malformed");
|
|
487
|
+
}
|
|
488
|
+
for (const [id, record] of Object.entries(value.sessions)) {
|
|
489
|
+
try { validateAgentSessionRecord(record); } catch (error) {
|
|
490
|
+
throw new AgentSessionRegistryError(`invalid session record ${id}`, { cause: error });
|
|
491
|
+
}
|
|
492
|
+
if (record.agentSessionId !== id) throw new AgentSessionRegistryError(`session key mismatch for ${id}`);
|
|
493
|
+
}
|
|
494
|
+
for (const [id, maintenance] of Object.entries(value.maintenance)) validateMaintenance(id, maintenance);
|
|
495
|
+
let receiptCount = 0;
|
|
496
|
+
for (const [id, receipts] of Object.entries(value.maintenanceReceipts)) {
|
|
497
|
+
if (!Array.isArray(receipts) || receipts.length > MAX_RECEIPTS_PER_SESSION) throw new AgentSessionRegistryError(`invalid receipt list for ${id}`);
|
|
498
|
+
receiptCount += receipts.length;
|
|
499
|
+
for (const receipt of receipts) validateReceipt(id, receipt);
|
|
500
|
+
}
|
|
501
|
+
if (receiptCount > MAX_RECEIPTS_GLOBAL) throw new AgentSessionRegistryError("global maintenance receipt limit exceeded");
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
function validateRecordCas(
|
|
505
|
+
current: AgentSessionRecord | null,
|
|
506
|
+
next: AgentSessionRecord,
|
|
507
|
+
options:
|
|
508
|
+
| { readonly expectedRecordRevision: null; readonly expectedIncarnationId: null }
|
|
509
|
+
| { readonly expectedRecordRevision: number; readonly expectedIncarnationId: string },
|
|
510
|
+
): void {
|
|
511
|
+
if (options.expectedRecordRevision === null) {
|
|
512
|
+
if (current) throw new AgentSessionStoreConflictError("agent-session record already exists");
|
|
513
|
+
if (next.recordRevision !== 1) throw new AgentSessionStoreConflictError("new recordRevision must be 1");
|
|
514
|
+
return;
|
|
515
|
+
}
|
|
516
|
+
if (!current) throw new AgentSessionStoreConflictError("agent-session record does not exist");
|
|
517
|
+
assertExistingCas(current, options.expectedRecordRevision, options.expectedIncarnationId);
|
|
518
|
+
if (next.incarnationId !== current.incarnationId || next.recordRevision !== current.recordRevision + 1) {
|
|
519
|
+
throw new AgentSessionStoreConflictError("next agent-session record incarnation/revision is invalid");
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
function assertExistingCas(record: AgentSessionRecord, revision: number, incarnationId: string): void {
|
|
524
|
+
if (record.recordRevision !== revision || record.incarnationId !== incarnationId) {
|
|
525
|
+
throw new AgentSessionStoreConflictError("agent-session record compare-and-swap failed");
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
function rejectMaintenance(file: AgentSessionsRegistryFile, id: string): void {
|
|
530
|
+
if (file.maintenance[id]) throw new SessionMaintenanceInProgressError(id);
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
function validateMaintenance(agentSessionId: string, value: unknown): asserts value is SessionMaintenance {
|
|
534
|
+
if (!isRecord(value)) throw new AgentSessionRegistryError("maintenance must be an object");
|
|
535
|
+
canonicalizeJson(value);
|
|
536
|
+
requiredString(agentSessionId, "maintenance agentSessionId");
|
|
537
|
+
requiredString(value.incarnationId, "maintenance incarnationId");
|
|
538
|
+
requiredString(value.operationId, "maintenance operationId");
|
|
539
|
+
sha256(value.requestDigest, "maintenance requestDigest");
|
|
540
|
+
if (value.status !== "prepared") throw new AgentSessionRegistryError("maintenance status must be prepared");
|
|
541
|
+
canonicalIso(value.startedAt, "maintenance startedAt");
|
|
542
|
+
if (!isRecord(value.details)) throw new AgentSessionRegistryError("maintenance details must be an object");
|
|
543
|
+
if (value.kind === "creation") {
|
|
544
|
+
if (value.baseRecordRevision !== null) throw new AgentSessionRegistryError("creation baseRecordRevision must be null");
|
|
545
|
+
validateCreationOrRestorationStages(agentSessionId, {
|
|
546
|
+
kind: "creation",
|
|
547
|
+
incarnationId: value.incarnationId as string,
|
|
548
|
+
baseRecordRevision: null,
|
|
549
|
+
}, value.details);
|
|
550
|
+
nullableAbsolutePath(value.details.transcriptPath, "maintenance transcriptPath");
|
|
551
|
+
nullableAbsolutePath(value.details.auditLogPath, "maintenance auditLogPath");
|
|
552
|
+
} else if (value.kind === "restoration") {
|
|
553
|
+
positiveInteger(value.baseRecordRevision, "maintenance baseRecordRevision");
|
|
554
|
+
validateCreationOrRestorationStages(agentSessionId, {
|
|
555
|
+
kind: "restoration",
|
|
556
|
+
incarnationId: value.incarnationId as string,
|
|
557
|
+
baseRecordRevision: value.baseRecordRevision as number,
|
|
558
|
+
}, value.details);
|
|
559
|
+
validateRestorationTarget(value.details.transcript, "maintenance transcript");
|
|
560
|
+
validateRestorationTarget(value.details.auditLog, "maintenance auditLog");
|
|
561
|
+
} else if (value.kind === "persistence_reconfiguration") {
|
|
562
|
+
positiveInteger(value.baseRecordRevision, "maintenance baseRecordRevision");
|
|
563
|
+
validateReconfigurationTarget(value.details.transcript, "maintenance transcript");
|
|
564
|
+
validateReconfigurationTarget(value.details.auditLog, "maintenance auditLog");
|
|
565
|
+
} else if (value.kind === "deletion") {
|
|
566
|
+
positiveInteger(value.baseRecordRevision, "maintenance baseRecordRevision");
|
|
567
|
+
for (const field of ["deleteTranscript", "deleteAuditLog", "removeRegistryEntry"] as const) {
|
|
568
|
+
if (typeof value.details[field] !== "boolean") throw new AgentSessionRegistryError(`maintenance ${field} must be boolean`);
|
|
569
|
+
}
|
|
570
|
+
nullableAbsolutePath(value.details.transcriptPath, "maintenance transcriptPath");
|
|
571
|
+
nullableAbsolutePath(value.details.auditLogPath, "maintenance auditLogPath");
|
|
572
|
+
} else {
|
|
573
|
+
throw new AgentSessionRegistryError("maintenance kind is invalid");
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
function validateCreationOrRestorationStages(
|
|
578
|
+
agentSessionId: string,
|
|
579
|
+
maintenance: {
|
|
580
|
+
kind: "creation" | "restoration";
|
|
581
|
+
incarnationId: string;
|
|
582
|
+
baseRecordRevision: number | null;
|
|
583
|
+
},
|
|
584
|
+
details: Record<string, unknown>,
|
|
585
|
+
): void {
|
|
586
|
+
const stagedContinuation = details.stagedContinuation;
|
|
587
|
+
const stagedRecord = details.stagedRecord;
|
|
588
|
+
if (stagedRecord !== undefined && stagedContinuation === undefined) {
|
|
589
|
+
throw new AgentSessionRegistryError("stagedRecord requires stagedContinuation");
|
|
590
|
+
}
|
|
591
|
+
if (stagedContinuation !== undefined) validateStagedContinuation(stagedContinuation);
|
|
592
|
+
if (stagedRecord !== undefined) {
|
|
593
|
+
validateAgentSessionRecord(stagedRecord);
|
|
594
|
+
if (stagedRecord.agentSessionId !== agentSessionId || stagedRecord.incarnationId !== maintenance.incarnationId) {
|
|
595
|
+
throw new AgentSessionRegistryError("stagedRecord identity mismatch");
|
|
596
|
+
}
|
|
597
|
+
const expectedRevision = maintenance.baseRecordRevision === null ? 1 : maintenance.baseRecordRevision + 1;
|
|
598
|
+
if (stagedRecord.recordRevision !== expectedRevision) throw new AgentSessionRegistryError("stagedRecord revision mismatch");
|
|
599
|
+
const matchingFields = maintenance.kind === "creation"
|
|
600
|
+
? ["adapterId", "mode", "internalSessionId", "internalSessionActivatedAt", "model", "sessionConfiguration", "protocol"] as const
|
|
601
|
+
: ["adapterId", "mode", "internalSessionId", "internalSessionActivatedAt", "protocol"] as const;
|
|
602
|
+
for (const field of matchingFields) {
|
|
603
|
+
if (canonicalizeJson(stagedRecord[field]) !== canonicalizeJson((stagedContinuation as Record<string, unknown>)[field])) {
|
|
604
|
+
throw new AgentSessionRegistryError(`stagedRecord ${field} disagrees with stagedContinuation`);
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
function validateStagedContinuation(value: unknown): void {
|
|
611
|
+
if (!isRecord(value)) throw new AgentSessionRegistryError("stagedContinuation must be an object");
|
|
612
|
+
requiredString(value.adapterId, "stagedContinuation adapterId");
|
|
613
|
+
if (value.mode !== "normal" && value.mode !== "degraded") throw new AgentSessionRegistryError("stagedContinuation mode is invalid");
|
|
614
|
+
if (value.internalSessionId !== null) requiredString(value.internalSessionId, "stagedContinuation internalSessionId");
|
|
615
|
+
if (value.internalSessionActivatedAt !== null) canonicalIso(value.internalSessionActivatedAt, "stagedContinuation internalSessionActivatedAt");
|
|
616
|
+
if ((value.internalSessionId === null) !== (value.internalSessionActivatedAt === null)) throw new AgentSessionRegistryError("stagedContinuation internal identity/time mismatch");
|
|
617
|
+
if (value.model !== null) requiredString(value.model, "stagedContinuation model");
|
|
618
|
+
if (!isRecord(value.protocol) || (value.protocol.name !== "pty" && value.protocol.name !== "acp")) throw new AgentSessionRegistryError("stagedContinuation protocol is invalid");
|
|
619
|
+
if (value.protocol.name === "acp") positiveInteger(value.protocol.version, "stagedContinuation protocol version");
|
|
620
|
+
try { validateSessionConfigurationCheckpoint(value.sessionConfiguration, value.adapterId as string); } catch (error) {
|
|
621
|
+
throw new AgentSessionRegistryError("stagedContinuation configuration is invalid", { cause: error });
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
function validateRestorationTarget(value: unknown, label: string): void {
|
|
626
|
+
if (!isRecord(value) || !["retain", "disable", "replace"].includes(value.action as string)) throw new AgentSessionRegistryError(`${label} target is invalid`);
|
|
627
|
+
if (value.action === "retain" || value.action === "replace") absolutePath(value.path, `${label} path`);
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
function validateReconfigurationTarget(value: unknown, label: string): void {
|
|
631
|
+
if (value === null) return;
|
|
632
|
+
if (!isRecord(value) || !["disable", "replace"].includes(value.action as string)) throw new AgentSessionRegistryError(`${label} target is invalid`);
|
|
633
|
+
absolutePath(value.previousPath, `${label} previousPath`);
|
|
634
|
+
if (value.action === "replace") absolutePath(value.replacementPath, `${label} replacementPath`);
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
function validateMaintenanceAdvance(current: SessionMaintenance, next: SessionMaintenance): void {
|
|
638
|
+
if (!sameMaintenanceIdentity(current, next) || current.startedAt !== next.startedAt || current.baseRecordRevision !== next.baseRecordRevision || current.kind !== next.kind) {
|
|
639
|
+
throw new AgentSessionStoreConflictError("maintenance update changed immutable transaction identity");
|
|
640
|
+
}
|
|
641
|
+
if (current.kind !== "creation" && current.kind !== "restoration") {
|
|
642
|
+
if (canonicalizeJson(current) !== canonicalizeJson(next)) throw new AgentSessionStoreConflictError("this maintenance kind has no staged update");
|
|
643
|
+
return;
|
|
644
|
+
}
|
|
645
|
+
const currentDetails = current.details as { stagedContinuation?: unknown; stagedRecord?: unknown };
|
|
646
|
+
const nextDetails = next.details as { stagedContinuation?: unknown; stagedRecord?: unknown };
|
|
647
|
+
if (currentDetails.stagedContinuation === undefined && nextDetails.stagedRecord !== undefined) {
|
|
648
|
+
throw new AgentSessionStoreConflictError("stagedContinuation must be committed before stagedRecord");
|
|
649
|
+
}
|
|
650
|
+
for (const field of ["stagedContinuation", "stagedRecord"] as const) {
|
|
651
|
+
if (currentDetails[field] !== undefined && canonicalizeJson(currentDetails[field]) !== canonicalizeJson(nextDetails[field])) {
|
|
652
|
+
throw new AgentSessionStoreConflictError(`maintenance update changed ${field}`);
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
const stripStaged = (details: Record<string, unknown>) => Object.fromEntries(Object.entries(details).filter(([key]) => key !== "stagedContinuation" && key !== "stagedRecord"));
|
|
656
|
+
if (canonicalizeJson(stripStaged(current.details)) !== canonicalizeJson(stripStaged(next.details))) {
|
|
657
|
+
throw new AgentSessionStoreConflictError("maintenance update changed normalized targets");
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
function sameMaintenanceIdentity(a: SessionMaintenance, b: SessionMaintenance): boolean {
|
|
662
|
+
return a.incarnationId === b.incarnationId && a.operationId === b.operationId && a.requestDigest === b.requestDigest && a.kind === b.kind;
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
function assertMaintenanceIdentity(value: SessionMaintenance, incarnationId: string, operationId: string, requestDigest: string): void {
|
|
666
|
+
if (value.incarnationId !== incarnationId || value.operationId !== operationId || value.requestDigest !== requestDigest) {
|
|
667
|
+
throw new AgentSessionStoreConflictError("maintenance identity mismatch");
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
function findReceipt(file: AgentSessionsRegistryFile, id: string, incarnationId: string, operationId: string): MaintenanceCompletionReceipt | undefined {
|
|
672
|
+
return file.maintenanceReceipts[id]?.find((receipt) => receipt.incarnationId === incarnationId && receipt.operationId === operationId);
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
function addReceipt(file: MutableRegistry, receipt: MaintenanceCompletionReceipt): void {
|
|
676
|
+
const list = [...(file.maintenanceReceipts[receipt.agentSessionId] ?? []), receipt]
|
|
677
|
+
.sort(receiptComparator)
|
|
678
|
+
.slice(-MAX_RECEIPTS_PER_SESSION);
|
|
679
|
+
file.maintenanceReceipts[receipt.agentSessionId] = list;
|
|
680
|
+
const all = Object.values(file.maintenanceReceipts).flat().sort(receiptComparator);
|
|
681
|
+
while (all.length > MAX_RECEIPTS_GLOBAL) {
|
|
682
|
+
const evicted = all.shift()!;
|
|
683
|
+
file.maintenanceReceipts[evicted.agentSessionId] = file.maintenanceReceipts[evicted.agentSessionId]!.filter((item) => item !== evicted);
|
|
684
|
+
if (file.maintenanceReceipts[evicted.agentSessionId]!.length === 0) delete file.maintenanceReceipts[evicted.agentSessionId];
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
function receiptComparator(a: MaintenanceCompletionReceipt, b: MaintenanceCompletionReceipt): number {
|
|
689
|
+
return a.completedAt.localeCompare(b.completedAt) || a.agentSessionId.localeCompare(b.agentSessionId) || a.operationId.localeCompare(b.operationId);
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
function validateReceipt(id: string, value: unknown): asserts value is MaintenanceCompletionReceipt {
|
|
693
|
+
if (!isRecord(value) || value.agentSessionId !== id || value.outcome !== "completed") throw new AgentSessionRegistryError(`invalid receipt for ${id}`);
|
|
694
|
+
requiredString(value.incarnationId, "receipt incarnationId");
|
|
695
|
+
requiredString(value.operationId, "receipt operationId");
|
|
696
|
+
sha256(value.requestDigest, "receipt requestDigest");
|
|
697
|
+
canonicalIso(value.completedAt, "receipt completedAt");
|
|
698
|
+
if (!["creation", "restoration", "persistence_reconfiguration", "deletion"].includes(value.kind as string)) throw new AgentSessionRegistryError("receipt kind is invalid");
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
function sessionComparator(order: NonNullable<ListAgentSessionsOptions["order"]>) {
|
|
702
|
+
const field = order.startsWith("created") ? "createdAt" : "updatedAt";
|
|
703
|
+
const direction = order.endsWith("desc") ? -1 : 1;
|
|
704
|
+
return (a: AgentSessionRecord, b: AgentSessionRecord) => direction * (a[field].localeCompare(b[field]) || a.agentSessionId.localeCompare(b.agentSessionId));
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
interface CursorPayload { v: 1; kind: "sessions" | "maintenance"; revision: number; offset: number; filter: unknown }
|
|
708
|
+
function encodeCursor(value: CursorPayload): string { return Buffer.from(JSON.stringify(value)).toString("base64url"); }
|
|
709
|
+
function decodeCursor(cursor: string | undefined, kind: CursorPayload["kind"], revision: number, filter: unknown): number {
|
|
710
|
+
if (!cursor) return 0;
|
|
711
|
+
try {
|
|
712
|
+
if (Buffer.byteLength(cursor, "utf8") > 16_384) throw new Error("too large");
|
|
713
|
+
const value = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8")) as CursorPayload;
|
|
714
|
+
if (value.v !== 1 || value.kind !== kind || value.revision !== revision || !Number.isSafeInteger(value.offset) || value.offset < 0 || canonicalizeJson(value.filter) !== canonicalizeJson(filter)) throw new Error("mismatch");
|
|
715
|
+
return value.offset;
|
|
716
|
+
} catch {
|
|
717
|
+
throw new AgentSessionRegistryCursorError("registry cursor is invalid or stale");
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
async function writeSynced(path: string, content: string): Promise<void> {
|
|
722
|
+
const handle = await open(path, "wx", 0o600);
|
|
723
|
+
try { await handle.writeFile(content, "utf8"); await handle.sync(); } finally { await handle.close(); }
|
|
724
|
+
}
|
|
725
|
+
async function syncFile(path: string): Promise<void> { const handle = await open(path, "r"); try { await handle.sync(); } finally { await handle.close(); } }
|
|
726
|
+
async function syncDirectory(path: string): Promise<void> { const handle = await open(path, "r"); try { await handle.sync(); } finally { await handle.close(); } }
|
|
727
|
+
function delay(ms: number): Promise<void> { return new Promise((resolve) => setTimeout(resolve, ms)); }
|
|
728
|
+
function isMissing(error: unknown): boolean { return (error as NodeJS.ErrnoException)?.code === "ENOENT"; }
|
|
729
|
+
function isExists(error: unknown): boolean { return (error as NodeJS.ErrnoException)?.code === "EEXIST"; }
|
|
730
|
+
function asError(error: unknown): Error { return error instanceof Error ? error : new Error(String(error)); }
|
|
731
|
+
function boundedInteger(value: number, min: number, max: number, name: string): number { if (!Number.isSafeInteger(value) || value < min || value > max) throw new AgentSessionRegistryError(`${name} must be ${min}..${max}`); return value; }
|
|
732
|
+
function listLimit(value: number | undefined): number { return boundedInteger(value ?? 50, 1, 500, "list limit"); }
|
|
733
|
+
function nonnegativeInteger(value: unknown, label: string): void { if (!Number.isSafeInteger(value) || (value as number) < 0) throw new AgentSessionRegistryError(`${label} is invalid`); }
|
|
734
|
+
function positiveInteger(value: unknown, label: string): void { if (!Number.isSafeInteger(value) || (value as number) < 1) throw new AgentSessionRegistryError(`${label} is invalid`); }
|
|
735
|
+
function requiredString(value: unknown, label: string): string { if (typeof value !== "string" || !value.trim()) throw new AgentSessionRegistryError(`${label} is invalid`); return value; }
|
|
736
|
+
function sha256(value: unknown, label: string): void { if (typeof value !== "string" || !/^[0-9a-f]{64}$/.test(value)) throw new AgentSessionRegistryError(`${label} is invalid`); }
|
|
737
|
+
function canonicalIso(value: unknown, label: string): void { if (typeof value !== "string" || !Number.isFinite(Date.parse(value)) || new Date(value).toISOString() !== value) throw new AgentSessionRegistryError(`${label} is invalid`); }
|
|
738
|
+
function absolutePath(value: unknown, label: string): void { if (typeof value !== "string" || !isAbsolute(value)) throw new AgentSessionRegistryError(`${label} must be absolute`); }
|
|
739
|
+
function nullableAbsolutePath(value: unknown, label: string): void { if (value !== null) absolutePath(value, label); }
|
|
740
|
+
function isRecord(value: unknown): value is Record<string, unknown> { return typeof value === "object" && value !== null && !Array.isArray(value); }
|