@qlairoslabs/acp-client 0.6.0 → 0.7.0
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 +579 -292
- 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/controller.ts +13 -0
- package/src/index.ts +228 -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/session-manager.ts +257 -7
- package/src/transcript.ts +3 -3
|
@@ -0,0 +1,480 @@
|
|
|
1
|
+
import { chmod, lstat, mkdir, open, readFile, unlink } from "node:fs/promises";
|
|
2
|
+
import { dirname, isAbsolute } from "node:path";
|
|
3
|
+
import { randomUUID } from "node:crypto";
|
|
4
|
+
import type { FileHandle } from "node:fs/promises";
|
|
5
|
+
import {
|
|
6
|
+
validateAuditLogRecord,
|
|
7
|
+
validateTranscriptRecord,
|
|
8
|
+
type AuditLogHeaderRecord,
|
|
9
|
+
type KnownAuditLogRecord,
|
|
10
|
+
type KnownTranscriptRecord,
|
|
11
|
+
type SessionLogRecordExpectation,
|
|
12
|
+
type TranscriptHeaderRecord,
|
|
13
|
+
} from "./records.ts";
|
|
14
|
+
import { truncateSessionLogRecord } from "./truncation.ts";
|
|
15
|
+
import type { PersistenceLimits } from "./config.ts";
|
|
16
|
+
import {
|
|
17
|
+
scanTranscriptContinuation,
|
|
18
|
+
TranscriptNotFoundError,
|
|
19
|
+
TranscriptUnavailableError,
|
|
20
|
+
type TranscriptContinuationScan,
|
|
21
|
+
type TranscriptScanExpectation,
|
|
22
|
+
} from "./transcript-scanner.ts";
|
|
23
|
+
|
|
24
|
+
export type SessionLogKind = "transcript" | "audit";
|
|
25
|
+
|
|
26
|
+
export interface FileSessionLogWriterOptions<K extends SessionLogKind> {
|
|
27
|
+
readonly kind: K;
|
|
28
|
+
readonly path: string;
|
|
29
|
+
readonly header: K extends "transcript" ? TranscriptHeaderRecord : AuditLogHeaderRecord;
|
|
30
|
+
readonly maxRecordBytes: number;
|
|
31
|
+
readonly lockTimeoutMs?: number;
|
|
32
|
+
readonly lockRetryMs?: number;
|
|
33
|
+
/** @internal Pre-acquired ownership transferred by a managed transaction coordinator. */
|
|
34
|
+
readonly writerLock?: SessionLogWriterLock;
|
|
35
|
+
/** @internal Final logical destination when building an atomic sibling replacement. */
|
|
36
|
+
readonly logicalPath?: string;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface ResumeTranscriptWriterOptions {
|
|
40
|
+
readonly path: string;
|
|
41
|
+
readonly expected?: TranscriptScanExpectation;
|
|
42
|
+
readonly lockTimeoutMs?: number;
|
|
43
|
+
readonly lockRetryMs?: number;
|
|
44
|
+
/** @internal Pre-acquired ownership transferred by managed loading/restoration. */
|
|
45
|
+
readonly writerLock?: SessionLogWriterLock;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export interface ResumedTranscriptWriter {
|
|
49
|
+
readonly writer: FileSessionLogWriter<"transcript">;
|
|
50
|
+
readonly scan: TranscriptContinuationScan;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export interface ResumeAuditLogWriterOptions {
|
|
54
|
+
readonly path: string;
|
|
55
|
+
readonly expected: { readonly agentSessionId: string; readonly auditLogId: string; readonly generation: number };
|
|
56
|
+
readonly writerLock?: SessionLogWriterLock;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export class SessionLogWriteError extends Error {
|
|
60
|
+
constructor(message: string, options?: ErrorOptions) {
|
|
61
|
+
super(message, options);
|
|
62
|
+
this.name = "SessionLogWriteError";
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export class SessionLogAlreadyExistsError extends SessionLogWriteError {
|
|
67
|
+
constructor(readonly path: string) {
|
|
68
|
+
super(`session log is already initialized: ${path}`);
|
|
69
|
+
this.name = "SessionLogAlreadyExistsError";
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export class SessionLogInUseError extends SessionLogWriteError {
|
|
74
|
+
constructor(readonly path: string) {
|
|
75
|
+
super(`session log is already owned by another writer: ${path}`);
|
|
76
|
+
this.name = "SessionLogInUseError";
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export class SessionLogRecordTooLargeError extends SessionLogWriteError {
|
|
81
|
+
constructor(readonly bytes: number, readonly limit: number) {
|
|
82
|
+
super(`session-log record is ${bytes} bytes; limit is ${limit}`);
|
|
83
|
+
this.name = "SessionLogRecordTooLargeError";
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** @internal Exclusive session-log ownership which may be transferred into a writer. */
|
|
88
|
+
export interface SessionLogWriterLock {
|
|
89
|
+
readonly path: string;
|
|
90
|
+
release(): Promise<void>;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** @internal Acquire ownership without opening or initializing the target file. */
|
|
94
|
+
export async function acquireSessionLogWriterLock(
|
|
95
|
+
path: string,
|
|
96
|
+
options: { readonly lockTimeoutMs?: number; readonly lockRetryMs?: number } = {},
|
|
97
|
+
): Promise<SessionLogWriterLock> {
|
|
98
|
+
if (!isAbsolute(path)) throw new SessionLogWriteError("session-log path must be absolute");
|
|
99
|
+
return await acquireLogLock(
|
|
100
|
+
`${path}.lock`,
|
|
101
|
+
path,
|
|
102
|
+
options.lockTimeoutMs ?? 5_000,
|
|
103
|
+
options.lockRetryMs ?? 20,
|
|
104
|
+
);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** @internal Execute maintenance while holding the same ownership lock as live writers. */
|
|
108
|
+
export async function withSessionLogWriterLock<T>(
|
|
109
|
+
path: string,
|
|
110
|
+
operation: () => Promise<T>,
|
|
111
|
+
options: { readonly lockTimeoutMs?: number; readonly lockRetryMs?: number } = {},
|
|
112
|
+
): Promise<T> {
|
|
113
|
+
if (!isAbsolute(path)) throw new SessionLogWriteError("session-log path must be absolute");
|
|
114
|
+
const lock = await acquireSessionLogWriterLock(path, options);
|
|
115
|
+
try {
|
|
116
|
+
return await operation();
|
|
117
|
+
} finally {
|
|
118
|
+
await lock.release();
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** One lifetime-owned append-only transcript or audit-log generation. */
|
|
123
|
+
export class FileSessionLogWriter<K extends SessionLogKind> {
|
|
124
|
+
readonly kind: K;
|
|
125
|
+
readonly path: string;
|
|
126
|
+
readonly maxRecordBytes: number;
|
|
127
|
+
private readonly limits: PersistenceLimits;
|
|
128
|
+
private readonly includeTruncationDigests: boolean;
|
|
129
|
+
private readonly handle: FileHandle;
|
|
130
|
+
private readonly lock: SessionLogWriterLock;
|
|
131
|
+
private readonly expected: SessionLogRecordExpectation;
|
|
132
|
+
private sequence: number;
|
|
133
|
+
private closed = false;
|
|
134
|
+
private failure: SessionLogWriteError | null = null;
|
|
135
|
+
private queue: Promise<void> = Promise.resolve();
|
|
136
|
+
|
|
137
|
+
private constructor(
|
|
138
|
+
options: FileSessionLogWriterOptions<K>,
|
|
139
|
+
handle: FileHandle,
|
|
140
|
+
lock: SessionLogWriterLock,
|
|
141
|
+
initialSequence = options.header.seq,
|
|
142
|
+
) {
|
|
143
|
+
this.kind = options.kind;
|
|
144
|
+
this.path = options.path;
|
|
145
|
+
this.maxRecordBytes = options.maxRecordBytes;
|
|
146
|
+
this.limits = options.header.effectiveLimits;
|
|
147
|
+
this.includeTruncationDigests = options.header.includeTruncationDigests;
|
|
148
|
+
this.handle = handle;
|
|
149
|
+
this.lock = lock;
|
|
150
|
+
this.sequence = initialSequence;
|
|
151
|
+
this.expected = {
|
|
152
|
+
agentSessionId: options.header.agentSessionId,
|
|
153
|
+
logId: options.kind === "transcript"
|
|
154
|
+
? (options.header as TranscriptHeaderRecord).transcriptId
|
|
155
|
+
: (options.header as AuditLogHeaderRecord).auditLogId,
|
|
156
|
+
generation: options.header.generation,
|
|
157
|
+
...(options.kind === "transcript"
|
|
158
|
+
? { transcriptPath: options.logicalPath ?? options.path }
|
|
159
|
+
: {}),
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
static async create<K extends SessionLogKind>(
|
|
164
|
+
options: FileSessionLogWriterOptions<K>,
|
|
165
|
+
): Promise<FileSessionLogWriter<K>> {
|
|
166
|
+
validateWriterOptions(options);
|
|
167
|
+
const parent = dirname(options.path);
|
|
168
|
+
await mkdir(parent, { recursive: true, mode: 0o700 });
|
|
169
|
+
await chmod(parent, 0o700).catch(() => undefined);
|
|
170
|
+
const lock = options.writerLock ?? await acquireSessionLogWriterLock(options.path, options);
|
|
171
|
+
if (lock.path !== options.path) {
|
|
172
|
+
await lock.release().catch(() => undefined);
|
|
173
|
+
throw new SessionLogWriteError("pre-acquired writer lock belongs to another path");
|
|
174
|
+
}
|
|
175
|
+
let handle: FileHandle | undefined;
|
|
176
|
+
try {
|
|
177
|
+
handle = await openUninitializedFile(options.path);
|
|
178
|
+
const writer = new FileSessionLogWriter(options, handle, lock);
|
|
179
|
+
await writer.writeRecord(options.header, true);
|
|
180
|
+
return writer;
|
|
181
|
+
} catch (error) {
|
|
182
|
+
await handle?.close().catch(() => undefined);
|
|
183
|
+
await lock.release();
|
|
184
|
+
throw error;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** Own and resume one validated transcript generation, discarding only a torn suffix. */
|
|
189
|
+
static async resumeTranscript(
|
|
190
|
+
options: ResumeTranscriptWriterOptions,
|
|
191
|
+
): Promise<ResumedTranscriptWriter> {
|
|
192
|
+
if (!isAbsolute(options.path)) throw new SessionLogWriteError("session-log path must be absolute");
|
|
193
|
+
await inspectResumableTranscript(options.path);
|
|
194
|
+
const lock = options.writerLock ?? await acquireLogLock(
|
|
195
|
+
`${options.path}.lock`, options.path,
|
|
196
|
+
options.lockTimeoutMs ?? 5_000, options.lockRetryMs ?? 20,
|
|
197
|
+
);
|
|
198
|
+
if (lock.path !== options.path) {
|
|
199
|
+
await lock.release().catch(() => undefined);
|
|
200
|
+
throw new SessionLogWriteError("pre-acquired writer lock belongs to another path");
|
|
201
|
+
}
|
|
202
|
+
let handle: FileHandle | undefined;
|
|
203
|
+
try {
|
|
204
|
+
const before = await inspectResumableTranscript(options.path);
|
|
205
|
+
const scan = await scanTranscriptContinuation(options.path, options.expected);
|
|
206
|
+
handle = await open(options.path, "a+");
|
|
207
|
+
const owned = await handle.stat();
|
|
208
|
+
if (owned.dev !== before.dev || owned.ino !== before.ino || owned.size !== scan.snapshotBytes) {
|
|
209
|
+
throw new TranscriptUnavailableError("transcript changed while append ownership was being acquired");
|
|
210
|
+
}
|
|
211
|
+
if (scan.ignoredTrailingBytes > 0) {
|
|
212
|
+
await handle.truncate(scan.lastCompleteOffset);
|
|
213
|
+
await handle.sync();
|
|
214
|
+
}
|
|
215
|
+
await chmod(options.path, 0o600).catch(() => undefined);
|
|
216
|
+
const writerOptions: FileSessionLogWriterOptions<"transcript"> = {
|
|
217
|
+
kind: "transcript",
|
|
218
|
+
path: options.path,
|
|
219
|
+
header: scan.header,
|
|
220
|
+
maxRecordBytes: scan.header.effectiveLimits.maxRecordBytes,
|
|
221
|
+
lockTimeoutMs: options.lockTimeoutMs,
|
|
222
|
+
lockRetryMs: options.lockRetryMs,
|
|
223
|
+
};
|
|
224
|
+
const writer = new FileSessionLogWriter(writerOptions, handle, lock, scan.lastCompleteSequence);
|
|
225
|
+
return { writer, scan };
|
|
226
|
+
} catch (error) {
|
|
227
|
+
await handle?.close().catch(() => undefined);
|
|
228
|
+
await lock.release();
|
|
229
|
+
throw error;
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/** Resume one audit generation after validating every complete physical record. */
|
|
234
|
+
static async resumeAuditLog(options: ResumeAuditLogWriterOptions): Promise<{
|
|
235
|
+
readonly writer: FileSessionLogWriter<"audit">;
|
|
236
|
+
readonly header: AuditLogHeaderRecord;
|
|
237
|
+
}> {
|
|
238
|
+
if (!isAbsolute(options.path)) throw new SessionLogWriteError("audit-log path must be absolute");
|
|
239
|
+
const lock = options.writerLock ?? await acquireSessionLogWriterLock(options.path);
|
|
240
|
+
if (lock.path !== options.path) {
|
|
241
|
+
await lock.release().catch(() => undefined);
|
|
242
|
+
throw new SessionLogWriteError("pre-acquired writer lock belongs to another path");
|
|
243
|
+
}
|
|
244
|
+
let handle: FileHandle | undefined;
|
|
245
|
+
try {
|
|
246
|
+
const bytes = await readFile(options.path);
|
|
247
|
+
if (bytes.length === 0 || bytes[bytes.length - 1] !== 0x0a) {
|
|
248
|
+
throw new SessionLogWriteError("audit log has an incomplete final record");
|
|
249
|
+
}
|
|
250
|
+
const lines = bytes.toString("utf8").trimEnd().split("\n");
|
|
251
|
+
let header: AuditLogHeaderRecord | undefined;
|
|
252
|
+
let expectedSeq = 1;
|
|
253
|
+
for (const line of lines) {
|
|
254
|
+
const value = JSON.parse(line) as KnownAuditLogRecord;
|
|
255
|
+
if (!header) {
|
|
256
|
+
if (value.t !== "header") throw new SessionLogWriteError("audit log does not begin with a header");
|
|
257
|
+
header = value;
|
|
258
|
+
}
|
|
259
|
+
validateAuditLogRecord(value, {
|
|
260
|
+
agentSessionId: options.expected.agentSessionId,
|
|
261
|
+
logId: options.expected.auditLogId,
|
|
262
|
+
generation: options.expected.generation,
|
|
263
|
+
});
|
|
264
|
+
if (value.seq !== expectedSeq++) throw new SessionLogWriteError("audit-log sequence is not contiguous");
|
|
265
|
+
if (Buffer.byteLength(line, "utf8") > header.effectiveLimits.maxRecordBytes) {
|
|
266
|
+
throw new SessionLogWriteError("audit-log record exceeds its engraved limit");
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
if (!header) throw new SessionLogWriteError("audit log is empty");
|
|
270
|
+
handle = await open(options.path, "a+");
|
|
271
|
+
const writer = new FileSessionLogWriter({
|
|
272
|
+
kind: "audit", path: options.path, header,
|
|
273
|
+
maxRecordBytes: header.effectiveLimits.maxRecordBytes,
|
|
274
|
+
}, handle, lock, lines.length);
|
|
275
|
+
return { writer, header };
|
|
276
|
+
} catch (error) {
|
|
277
|
+
await handle?.close().catch(() => undefined);
|
|
278
|
+
await lock.release().catch(() => undefined);
|
|
279
|
+
throw error;
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
get nextSequence(): number {
|
|
284
|
+
return this.sequence + 1;
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
append(
|
|
288
|
+
record: K extends "transcript" ? KnownTranscriptRecord : KnownAuditLogRecord,
|
|
289
|
+
options: { readonly durable?: boolean } = {},
|
|
290
|
+
): Promise<void> {
|
|
291
|
+
const run = this.queue.then(async () => {
|
|
292
|
+
this.assertOpen();
|
|
293
|
+
if (record.seq !== this.sequence + 1) {
|
|
294
|
+
throw new SessionLogWriteError(`expected session-log sequence ${this.sequence + 1}, received ${record.seq}`);
|
|
295
|
+
}
|
|
296
|
+
await this.writeRecord(record, options.durable ?? false);
|
|
297
|
+
this.sequence = record.seq;
|
|
298
|
+
});
|
|
299
|
+
// Keep the serialization chain usable after a rejected caller operation.
|
|
300
|
+
this.queue = run.catch(() => undefined);
|
|
301
|
+
return run;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
async sync(): Promise<void> {
|
|
305
|
+
await this.queue;
|
|
306
|
+
this.assertOpen();
|
|
307
|
+
try {
|
|
308
|
+
await this.handle.sync();
|
|
309
|
+
} catch (error) {
|
|
310
|
+
this.failure = new SessionLogWriteError("session-log synchronization failed", { cause: error });
|
|
311
|
+
throw this.failure;
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
async close(): Promise<void> {
|
|
316
|
+
await this.queue;
|
|
317
|
+
if (this.closed) return;
|
|
318
|
+
this.closed = true;
|
|
319
|
+
try {
|
|
320
|
+
await this.handle.sync();
|
|
321
|
+
} finally {
|
|
322
|
+
await this.handle.close().catch(() => undefined);
|
|
323
|
+
await this.lock.release();
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
private async writeRecord(record: KnownTranscriptRecord | KnownAuditLogRecord, durable: boolean): Promise<void> {
|
|
328
|
+
const bounded = truncateSessionLogRecord(record, {
|
|
329
|
+
limits: this.limits,
|
|
330
|
+
includeTruncationDigests: this.includeTruncationDigests,
|
|
331
|
+
});
|
|
332
|
+
try {
|
|
333
|
+
if (this.kind === "transcript") validateTranscriptRecord(bounded, this.expected);
|
|
334
|
+
else validateAuditLogRecord(bounded, this.expected);
|
|
335
|
+
} catch (error) {
|
|
336
|
+
throw new SessionLogWriteError("session-log record validation failed", { cause: error });
|
|
337
|
+
}
|
|
338
|
+
const line = `${JSON.stringify(bounded)}\n`;
|
|
339
|
+
const bytes = Buffer.byteLength(line, "utf8") - 1;
|
|
340
|
+
if (bytes > this.maxRecordBytes) throw new SessionLogRecordTooLargeError(bytes, this.maxRecordBytes);
|
|
341
|
+
try {
|
|
342
|
+
const result = await this.handle.write(line);
|
|
343
|
+
if (result.bytesWritten !== Buffer.byteLength(line, "utf8")) {
|
|
344
|
+
throw new Error(`short append: ${result.bytesWritten} bytes`);
|
|
345
|
+
}
|
|
346
|
+
if (durable) await this.handle.sync();
|
|
347
|
+
} catch (error) {
|
|
348
|
+
this.failure = new SessionLogWriteError("session-log append or synchronization failed", { cause: error });
|
|
349
|
+
throw this.failure;
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
private assertOpen(): void {
|
|
354
|
+
if (this.closed) throw new SessionLogWriteError("session-log writer is closed");
|
|
355
|
+
if (this.failure) throw this.failure;
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
async function inspectResumableTranscript(path: string) {
|
|
360
|
+
let info;
|
|
361
|
+
try {
|
|
362
|
+
info = await lstat(path);
|
|
363
|
+
} catch (error) {
|
|
364
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") throw new TranscriptNotFoundError(path);
|
|
365
|
+
throw new TranscriptUnavailableError(`cannot inspect transcript before resume: ${path}`, { cause: error });
|
|
366
|
+
}
|
|
367
|
+
if (!info.isFile() || info.isSymbolicLink()) {
|
|
368
|
+
throw new TranscriptUnavailableError(`transcript is not a regular non-symbolic file: ${path}`);
|
|
369
|
+
}
|
|
370
|
+
return info;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
function validateWriterOptions(options: FileSessionLogWriterOptions<SessionLogKind>): void {
|
|
374
|
+
if (!isAbsolute(options.path)) throw new SessionLogWriteError("session-log path must be absolute");
|
|
375
|
+
if (!Number.isSafeInteger(options.maxRecordBytes) || options.maxRecordBytes < 4_096 || options.maxRecordBytes > 16_777_216) {
|
|
376
|
+
throw new SessionLogWriteError("maxRecordBytes is outside the supported range");
|
|
377
|
+
}
|
|
378
|
+
if (options.header.seq !== 1) throw new SessionLogWriteError("a new session-log header must use sequence 1");
|
|
379
|
+
if (options.header.generation < 1) throw new SessionLogWriteError("session-log generation must be positive");
|
|
380
|
+
if (options.header.effectiveLimits.maxRecordBytes !== options.maxRecordBytes) {
|
|
381
|
+
throw new SessionLogWriteError("writer maxRecordBytes must equal the limit engraved in its header");
|
|
382
|
+
}
|
|
383
|
+
if (options.kind === "transcript") {
|
|
384
|
+
const header = options.header as TranscriptHeaderRecord;
|
|
385
|
+
validateTranscriptRecord(header, {
|
|
386
|
+
agentSessionId: header.agentSessionId,
|
|
387
|
+
logId: header.transcriptId,
|
|
388
|
+
generation: header.generation,
|
|
389
|
+
});
|
|
390
|
+
} else {
|
|
391
|
+
const header = options.header as AuditLogHeaderRecord;
|
|
392
|
+
validateAuditLogRecord(header, {
|
|
393
|
+
agentSessionId: header.agentSessionId,
|
|
394
|
+
logId: header.auditLogId,
|
|
395
|
+
generation: header.generation,
|
|
396
|
+
});
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
async function openUninitializedFile(path: string): Promise<FileHandle> {
|
|
401
|
+
try {
|
|
402
|
+
return await open(path, "wx", 0o600);
|
|
403
|
+
} catch (error) {
|
|
404
|
+
if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw new SessionLogWriteError(`cannot create session log: ${path}`, { cause: error });
|
|
405
|
+
}
|
|
406
|
+
const info = await lstat(path);
|
|
407
|
+
if (!info.isFile() || info.isSymbolicLink() || info.size !== 0) throw new SessionLogAlreadyExistsError(path);
|
|
408
|
+
const handle = await open(path, "r+");
|
|
409
|
+
await chmod(path, 0o600).catch(() => undefined);
|
|
410
|
+
// Recheck through the owned descriptor to close the stat/open race.
|
|
411
|
+
if ((await handle.stat()).size !== 0) {
|
|
412
|
+
await handle.close();
|
|
413
|
+
throw new SessionLogAlreadyExistsError(path);
|
|
414
|
+
}
|
|
415
|
+
return handle;
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
async function acquireLogLock(
|
|
419
|
+
lockPath: string,
|
|
420
|
+
targetPath: string,
|
|
421
|
+
timeoutMs: number,
|
|
422
|
+
retryMs: number,
|
|
423
|
+
): Promise<SessionLogWriterLock> {
|
|
424
|
+
if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 100 || !Number.isSafeInteger(retryMs) || retryMs < 1) {
|
|
425
|
+
throw new SessionLogWriteError("session-log lock timing is invalid");
|
|
426
|
+
}
|
|
427
|
+
const deadline = Date.now() + timeoutMs;
|
|
428
|
+
const token = randomUUID();
|
|
429
|
+
for (;;) {
|
|
430
|
+
let handle: FileHandle;
|
|
431
|
+
try {
|
|
432
|
+
handle = await open(lockPath, "wx", 0o600);
|
|
433
|
+
} catch (error) {
|
|
434
|
+
if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw new SessionLogWriteError("cannot acquire session-log lock", { cause: error });
|
|
435
|
+
if (await removeDeadLock(lockPath)) continue;
|
|
436
|
+
if (Date.now() >= deadline) throw new SessionLogInUseError(targetPath);
|
|
437
|
+
await new Promise((resolve) => setTimeout(resolve, retryMs));
|
|
438
|
+
continue;
|
|
439
|
+
}
|
|
440
|
+
try {
|
|
441
|
+
await handle.writeFile(JSON.stringify({ pid: process.pid, token, createdAt: new Date().toISOString() }), "utf8");
|
|
442
|
+
await handle.sync();
|
|
443
|
+
} catch (error) {
|
|
444
|
+
await handle.close().catch(() => undefined);
|
|
445
|
+
await unlink(lockPath).catch(() => undefined);
|
|
446
|
+
throw new SessionLogWriteError("cannot initialize session-log lock", { cause: error });
|
|
447
|
+
}
|
|
448
|
+
let released = false;
|
|
449
|
+
return {
|
|
450
|
+
path: targetPath,
|
|
451
|
+
release: async () => {
|
|
452
|
+
if (released) return;
|
|
453
|
+
released = true;
|
|
454
|
+
await handle.close().catch(() => undefined);
|
|
455
|
+
try {
|
|
456
|
+
const current = JSON.parse(await readFile(lockPath, "utf8")) as { token?: unknown };
|
|
457
|
+
if (current.token === token) await unlink(lockPath);
|
|
458
|
+
} catch {
|
|
459
|
+
// Never remove a replacement lock.
|
|
460
|
+
}
|
|
461
|
+
},
|
|
462
|
+
};
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
async function removeDeadLock(path: string): Promise<boolean> {
|
|
467
|
+
try {
|
|
468
|
+
const raw = await readFile(path, "utf8");
|
|
469
|
+
const value = JSON.parse(raw) as { pid?: unknown; token?: unknown };
|
|
470
|
+
if (!Number.isSafeInteger(value.pid) || (value.pid as number) < 1 || typeof value.token !== "string") return false;
|
|
471
|
+
try { process.kill(value.pid as number, 0); return false; } catch (error) {
|
|
472
|
+
if ((error as NodeJS.ErrnoException).code !== "ESRCH") return false;
|
|
473
|
+
}
|
|
474
|
+
if (await readFile(path, "utf8") !== raw) return false;
|
|
475
|
+
await unlink(path);
|
|
476
|
+
return true;
|
|
477
|
+
} catch {
|
|
478
|
+
return false;
|
|
479
|
+
}
|
|
480
|
+
}
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
import { createAgentSessionCheckpoint, type AgentSessionCheckpoint } from "./checkpoint.ts";
|
|
2
|
+
import type { NormalizedPersistenceEvent } from "./projection.ts";
|
|
3
|
+
import type { InternalSessionHistoryEntry, OperationKind } from "./records.ts";
|
|
4
|
+
import type { OperationAbortReason } from "./records.ts";
|
|
5
|
+
import { sha256CanonicalJson } from "./integrity.ts";
|
|
6
|
+
import type { PersistenceRepair, SessionRecoveryStatus } from "./reducer.ts";
|
|
7
|
+
import type { TranscriptTerminalCheckpointChanges } from "./transcript-runtime.ts";
|
|
8
|
+
import type { PersistedMachineCode } from "./integrity.ts";
|
|
9
|
+
|
|
10
|
+
type TransitionEvent = Extract<NormalizedPersistenceEvent, { kind: "transition" }>;
|
|
11
|
+
|
|
12
|
+
export interface PersistenceStateRuntime {
|
|
13
|
+
readonly checkpoint: AgentSessionCheckpoint;
|
|
14
|
+
readonly recovery: SessionRecoveryStatus;
|
|
15
|
+
readonly openingRepairs: readonly PersistenceRepair[];
|
|
16
|
+
readonly conversationAvailability: "available" | "partial" | "not_captured";
|
|
17
|
+
readonly healthy: boolean;
|
|
18
|
+
readonly internalSessionHistory: readonly InternalSessionHistoryEntry[];
|
|
19
|
+
setCheckpointPublisher(publisher: (checkpoint: AgentSessionCheckpoint, history: readonly InternalSessionHistoryEntry[]) => Promise<void>): void;
|
|
20
|
+
beginOperation(operationId: string, kind: OperationKind, ts?: number): Promise<void>;
|
|
21
|
+
appendEvent(event: NormalizedPersistenceEvent, ts?: number): Promise<boolean>;
|
|
22
|
+
appendTransitionEvent(event: Omit<TransitionEvent, "event"> & { readonly event: Exclude<TransitionEvent["event"], "target_activated"> }, options?: { readonly durable?: boolean; readonly ts?: number }): Promise<void>;
|
|
23
|
+
publishCheckpoint(changes: TranscriptTerminalCheckpointChanges, ts?: number): Promise<AgentSessionCheckpoint>;
|
|
24
|
+
activateTransition(event: Omit<TransitionEvent, "event"> & { readonly event: "target_activated" }, ts?: number): Promise<AgentSessionCheckpoint>;
|
|
25
|
+
syncBeforeDispatch(): Promise<void>;
|
|
26
|
+
finishOperation(event: "settled" | "failed" | "cancelled" | "interrupted", changes?: TranscriptTerminalCheckpointChanges, errorCode?: PersistedMachineCode, ts?: number): Promise<AgentSessionCheckpoint>;
|
|
27
|
+
abortOperation(reason: OperationAbortReason, ts?: number): Promise<AgentSessionCheckpoint>;
|
|
28
|
+
acceptHarnessRecovery(ts?: number): Promise<AgentSessionCheckpoint>;
|
|
29
|
+
close(): Promise<void>;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Registry-only checkpoint state. Publication is the durable boundary. */
|
|
33
|
+
export class RegistryPersistenceRuntime implements PersistenceStateRuntime {
|
|
34
|
+
private current: AgentSessionCheckpoint;
|
|
35
|
+
private history: readonly InternalSessionHistoryEntry[];
|
|
36
|
+
private active: { readonly operationId: string; readonly kind: OperationKind } | null = null;
|
|
37
|
+
private publisher: ((checkpoint: AgentSessionCheckpoint, history: readonly InternalSessionHistoryEntry[]) => Promise<void>) | null = null;
|
|
38
|
+
private failed = false;
|
|
39
|
+
|
|
40
|
+
constructor(checkpoint: AgentSessionCheckpoint, history: readonly InternalSessionHistoryEntry[] = []) {
|
|
41
|
+
if (checkpoint.transcript !== null) throw new Error("registry runtime requires a registry-only checkpoint");
|
|
42
|
+
this.current = structuredClone(checkpoint);
|
|
43
|
+
this.history = Object.freeze(history.map((entry) => structuredClone(entry)));
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
get checkpoint() { return structuredClone(this.current); }
|
|
47
|
+
get recovery() { return { kind: "clean" } as const; }
|
|
48
|
+
get openingRepairs() { return []; }
|
|
49
|
+
get conversationAvailability() { return "not_captured" as const; }
|
|
50
|
+
get healthy() { return !this.failed; }
|
|
51
|
+
get internalSessionHistory() { return this.history.map((entry) => structuredClone(entry)); }
|
|
52
|
+
|
|
53
|
+
setCheckpointPublisher(publisher: (checkpoint: AgentSessionCheckpoint, history: readonly InternalSessionHistoryEntry[]) => Promise<void>): void {
|
|
54
|
+
if (this.publisher) throw new Error("managed checkpoint publisher is already attached");
|
|
55
|
+
this.publisher = publisher;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
async beginOperation(operationId: string, kind: OperationKind, ts = Date.now()): Promise<void> {
|
|
59
|
+
if (this.active) throw new Error("another persistence operation is already active");
|
|
60
|
+
const previous = this.current;
|
|
61
|
+
this.active = { operationId, kind };
|
|
62
|
+
this.current = nextCheckpoint(previous, {
|
|
63
|
+
boundary: {
|
|
64
|
+
status: "in_flight",
|
|
65
|
+
lastSettledOperationId: previous.boundary.status === "settled"
|
|
66
|
+
? previous.boundary.lastSettledOperationId
|
|
67
|
+
: previous.boundary.lastSettledOperationId,
|
|
68
|
+
interruptedOperationId: operationId,
|
|
69
|
+
cause: "operation_started",
|
|
70
|
+
},
|
|
71
|
+
}, ts);
|
|
72
|
+
try { await this.publish(); } catch (error) {
|
|
73
|
+
this.active = null;
|
|
74
|
+
this.current = previous;
|
|
75
|
+
this.failed = true;
|
|
76
|
+
throw error;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
async appendEvent(): Promise<boolean> { return false; }
|
|
81
|
+
async appendTransitionEvent(): Promise<void> {}
|
|
82
|
+
async syncBeforeDispatch(): Promise<void> {}
|
|
83
|
+
|
|
84
|
+
async publishCheckpoint(changes: TranscriptTerminalCheckpointChanges, ts = Date.now()): Promise<AgentSessionCheckpoint> {
|
|
85
|
+
this.current = nextCheckpoint(this.current, changes, ts);
|
|
86
|
+
await this.publish();
|
|
87
|
+
return this.checkpoint;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
async activateTransition(event: Omit<TransitionEvent, "event"> & { readonly event: "target_activated" }): Promise<AgentSessionCheckpoint> {
|
|
91
|
+
if (!event.to || !event.activationState) throw new Error("registry transition activation requires target state");
|
|
92
|
+
if (event.historyEntry) this.history = Object.freeze([...this.history, structuredClone(event.historyEntry)]);
|
|
93
|
+
const state = event.activationState;
|
|
94
|
+
const { version: _version, digest: _digest, ...input } = this.current;
|
|
95
|
+
this.current = createAgentSessionCheckpoint({
|
|
96
|
+
...input,
|
|
97
|
+
stateRevision: state.resultingStateRevision,
|
|
98
|
+
adapterId: event.to.adapterId,
|
|
99
|
+
mode: event.to.mode,
|
|
100
|
+
internalSessionId: event.to.internalSessionId,
|
|
101
|
+
internalSessionActivatedAt: event.to.activatedAt,
|
|
102
|
+
internalSessionHistoryRevision: this.history.length,
|
|
103
|
+
internalSessionHistoryDigest: sha256CanonicalJson(this.history),
|
|
104
|
+
lastTransition: {
|
|
105
|
+
transitionId: event.transitionId,
|
|
106
|
+
kind: event.transitionKind,
|
|
107
|
+
at: state.transitionAt,
|
|
108
|
+
},
|
|
109
|
+
model: event.to.model,
|
|
110
|
+
sessionConfiguration: event.to.sessionConfiguration,
|
|
111
|
+
protocol: event.to.protocol,
|
|
112
|
+
transcript: null,
|
|
113
|
+
boundary: state.boundary,
|
|
114
|
+
updatedAt: state.updatedAt,
|
|
115
|
+
});
|
|
116
|
+
await this.publish();
|
|
117
|
+
return this.checkpoint;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
async finishOperation(
|
|
121
|
+
_event: "settled" | "failed" | "cancelled" | "interrupted",
|
|
122
|
+
changes: TranscriptTerminalCheckpointChanges = {},
|
|
123
|
+
_errorCode?: string,
|
|
124
|
+
ts = Date.now(),
|
|
125
|
+
): Promise<AgentSessionCheckpoint> {
|
|
126
|
+
const active = this.requireActive();
|
|
127
|
+
this.current = nextCheckpoint(this.current, {
|
|
128
|
+
...changes,
|
|
129
|
+
boundary: changes.boundary ?? { status: "settled", lastSettledOperationId: active.operationId },
|
|
130
|
+
}, ts);
|
|
131
|
+
this.active = null;
|
|
132
|
+
await this.publish();
|
|
133
|
+
return this.checkpoint;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
async abortOperation(_reason: OperationAbortReason, ts = Date.now()): Promise<AgentSessionCheckpoint> {
|
|
137
|
+
const active = this.requireActive();
|
|
138
|
+
this.current = nextCheckpoint(this.current, {
|
|
139
|
+
boundary: { status: "settled", lastSettledOperationId: active.operationId },
|
|
140
|
+
}, ts);
|
|
141
|
+
this.active = null;
|
|
142
|
+
await this.publish();
|
|
143
|
+
return this.checkpoint;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
async acceptHarnessRecovery(): Promise<AgentSessionCheckpoint> { return this.checkpoint; }
|
|
147
|
+
async close(): Promise<void> {}
|
|
148
|
+
|
|
149
|
+
private requireActive() {
|
|
150
|
+
if (!this.active) throw new Error("no persistence operation is active");
|
|
151
|
+
return this.active;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
private async publish(): Promise<void> {
|
|
155
|
+
if (!this.publisher) return;
|
|
156
|
+
try { await this.publisher(this.checkpoint, this.internalSessionHistory); }
|
|
157
|
+
catch (error) { this.failed = true; throw error; }
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function nextCheckpoint(
|
|
162
|
+
source: AgentSessionCheckpoint,
|
|
163
|
+
changes: TranscriptTerminalCheckpointChanges,
|
|
164
|
+
ts: number,
|
|
165
|
+
): AgentSessionCheckpoint {
|
|
166
|
+
const { version: _version, digest: _digest, ...input } = source;
|
|
167
|
+
return createAgentSessionCheckpoint({
|
|
168
|
+
...input,
|
|
169
|
+
...(changes.model === undefined ? {} : { model: changes.model }),
|
|
170
|
+
...(changes.sessionConfiguration === undefined ? {} : { sessionConfiguration: changes.sessionConfiguration }),
|
|
171
|
+
...(changes.metering === undefined ? {} : { metering: changes.metering }),
|
|
172
|
+
stateRevision: source.stateRevision + 1,
|
|
173
|
+
boundary: changes.boundary ?? source.boundary,
|
|
174
|
+
updatedAt: new Date(ts).toISOString(),
|
|
175
|
+
});
|
|
176
|
+
}
|