@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.
Files changed (40) hide show
  1. package/CONSUMER_GUIDE.md +579 -292
  2. package/README.md +25 -0
  3. package/package.json +1 -1
  4. package/src/agent-session.ts +2188 -96
  5. package/src/cli/index.ts +33 -5
  6. package/src/cli/managed.ts +220 -0
  7. package/src/controller.ts +13 -0
  8. package/src/index.ts +228 -3
  9. package/src/metering/engine.ts +9 -1
  10. package/src/metering/record.ts +2 -1
  11. package/src/persistence/activity-projection.ts +71 -0
  12. package/src/persistence/audit-log-reader.ts +506 -0
  13. package/src/persistence/audit-runtime.ts +162 -0
  14. package/src/persistence/checkpoint.ts +304 -0
  15. package/src/persistence/config.ts +538 -0
  16. package/src/persistence/configuration-state.ts +191 -0
  17. package/src/persistence/deletion.ts +227 -0
  18. package/src/persistence/file-registry-store.ts +740 -0
  19. package/src/persistence/integrity.ts +147 -0
  20. package/src/persistence/legacy-registry-import.ts +240 -0
  21. package/src/persistence/managed-checkpoint.ts +81 -0
  22. package/src/persistence/managed-creation.ts +456 -0
  23. package/src/persistence/managed-load.ts +172 -0
  24. package/src/persistence/managed-registry.ts +57 -0
  25. package/src/persistence/migration.ts +298 -0
  26. package/src/persistence/paths.ts +172 -0
  27. package/src/persistence/projection.ts +373 -0
  28. package/src/persistence/reconfiguration.ts +453 -0
  29. package/src/persistence/records.ts +873 -0
  30. package/src/persistence/reducer.ts +498 -0
  31. package/src/persistence/registry.ts +446 -0
  32. package/src/persistence/restoration.ts +689 -0
  33. package/src/persistence/session-log-writer.ts +480 -0
  34. package/src/persistence/state-runtime.ts +176 -0
  35. package/src/persistence/transcript-reader.ts +980 -0
  36. package/src/persistence/transcript-runtime.ts +667 -0
  37. package/src/persistence/transcript-scanner.ts +385 -0
  38. package/src/persistence/truncation.ts +276 -0
  39. package/src/session-manager.ts +257 -7
  40. package/src/transcript.ts +3 -3
@@ -0,0 +1,453 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { open, rename, unlink } from "node:fs/promises";
3
+ import { dirname } from "node:path";
4
+ import type { AuditLogConfig, TranscriptConfig } from "./config.ts";
5
+ import { resolveDirectPersistence } from "./config.ts";
6
+ import {
7
+ createAgentSessionCheckpoint,
8
+ validateAgentSessionCheckpoint,
9
+ type AgentSessionCheckpoint,
10
+ } from "./checkpoint.ts";
11
+ import { sha256CanonicalJson } from "./integrity.ts";
12
+ import { resolveSessionLogPaths } from "./paths.ts";
13
+ import {
14
+ AgentSessionStoreConflictError,
15
+ MaintenanceAlreadyCompletedError,
16
+ type AgentSessionRecord,
17
+ type AgentSessionStore,
18
+ type AgentSessionSummary,
19
+ type PersistenceReconfigurationMaintenance,
20
+ } from "./registry.ts";
21
+ import { summarizeAgentSessionRecord } from "./registry.ts";
22
+ import type { TranscriptHeaderRecord } from "./records.ts";
23
+ import { FileSessionLogWriter, withSessionLogWriterLock } from "./session-log-writer.ts";
24
+
25
+ export interface ReconfigureAgentSessionPersistenceOptions {
26
+ readonly reconfigurationId: string;
27
+ readonly expectedIncarnationId: string;
28
+ readonly expectedRecordRevision: number;
29
+ readonly transcript?:
30
+ | {
31
+ readonly action: "disable";
32
+ readonly checkpoint: AgentSessionCheckpoint;
33
+ readonly deleteExistingLog: true;
34
+ readonly acknowledgeContinuationLoss: true;
35
+ }
36
+ | {
37
+ readonly action: "replace";
38
+ readonly config: TranscriptConfig & { readonly path: string };
39
+ readonly checkpoint: AgentSessionCheckpoint;
40
+ readonly acknowledgeContinuationLoss: true;
41
+ };
42
+ readonly auditLog?:
43
+ | { readonly action: "disable"; readonly deleteExistingLog: true; readonly acknowledgeAuditGap: true }
44
+ | { readonly action: "replace"; readonly config: AuditLogConfig & { readonly path: string }; readonly acknowledgeAuditGap: true };
45
+ }
46
+
47
+ export class AgentSessionPersistenceReconfigurationError extends Error {
48
+ constructor(message: string, options?: ErrorOptions) {
49
+ super(message, options);
50
+ this.name = "AgentSessionPersistenceReconfigurationError";
51
+ }
52
+ }
53
+
54
+ export async function reconfigureManagedAgentSessionPersistence(
55
+ store: AgentSessionStore,
56
+ agentSessionId: string,
57
+ options: ReconfigureAgentSessionPersistenceOptions,
58
+ ): Promise<AgentSessionSummary> {
59
+ validateRequest(agentSessionId, options);
60
+ if (options.auditLog !== undefined && options.transcript === undefined) {
61
+ return await reconfigureAuditLog(store, agentSessionId, options);
62
+ }
63
+ if (options.auditLog !== undefined) {
64
+ throw new AgentSessionPersistenceReconfigurationError(
65
+ "v0 applies transcript and audit-log reconfiguration as separate fenced operations",
66
+ );
67
+ }
68
+ const change = options.transcript!;
69
+ const requestDigest = sha256CanonicalJson({
70
+ agentSessionId,
71
+ reconfigurationId: options.reconfigurationId,
72
+ expectedIncarnationId: options.expectedIncarnationId,
73
+ expectedRecordRevision: options.expectedRecordRevision,
74
+ transcript: change.action === "disable"
75
+ ? { action: "disable", checkpointDigest: change.checkpoint.digest }
76
+ : { action: "replace", config: change.config, checkpointDigest: change.checkpoint.digest },
77
+ });
78
+ const retryPath = change.checkpoint.transcript?.path
79
+ ?? (change.action === "replace" ? change.config.path : null);
80
+ if (!retryPath) {
81
+ throw new AgentSessionPersistenceReconfigurationError("the supplied checkpoint does not identify the transcript being disabled");
82
+ }
83
+ const candidate = await store.getAgentSessionRecord(agentSessionId);
84
+ if (!candidate
85
+ || candidate.incarnationId !== options.expectedIncarnationId
86
+ || candidate.recordRevision !== options.expectedRecordRevision) {
87
+ const completed = await store.prepareMaintenance(
88
+ agentSessionId,
89
+ proposedMaintenance(options, requestDigest, retryPath),
90
+ { expectedRecordRevision: options.expectedRecordRevision },
91
+ );
92
+ if (completed.status === "already_completed") throw new MaintenanceAlreadyCompletedError(completed.receipt);
93
+ throw new AgentSessionStoreConflictError("agent-session record compare-and-swap failed");
94
+ }
95
+ const initial = candidate;
96
+ if (!initial.transcript) {
97
+ throw new AgentSessionPersistenceReconfigurationError("session has no transcript to reconfigure");
98
+ }
99
+ const path = initial.transcript.path;
100
+ if (change.action === "replace") {
101
+ const resolved = resolveDirectPersistence({
102
+ root: dirname(dirname(path)),
103
+ transcript: change.config,
104
+ auditLog: false,
105
+ sessionConfiguration: initial.sessionConfigurationPersistence,
106
+ limits: initial.transcript.effectiveLimits,
107
+ });
108
+ if (resolved === false) throw new AgentSessionPersistenceReconfigurationError("replacement transcript is disabled");
109
+ const paths = await resolveSessionLogPaths(resolved, agentSessionId);
110
+ if (paths.transcriptPath !== path) {
111
+ throw new AgentSessionPersistenceReconfigurationError("v0 replacement must retain the recorded transcript path");
112
+ }
113
+ }
114
+
115
+ return await withSessionLogWriterLock(path, async () => {
116
+ const record = await requireCurrent(store, agentSessionId, options);
117
+ validateAgentSessionCheckpoint(change.checkpoint, {
118
+ agentSessionId,
119
+ incarnationId: record.incarnationId,
120
+ });
121
+ const proposed = proposedMaintenance(options, requestDigest, path);
122
+ const prepared = await store.prepareMaintenance(agentSessionId, proposed, {
123
+ expectedRecordRevision: options.expectedRecordRevision,
124
+ });
125
+ if (prepared.status === "already_completed") throw new MaintenanceAlreadyCompletedError(prepared.receipt);
126
+ if (prepared.maintenance.kind !== "persistence_reconfiguration") {
127
+ throw new AgentSessionPersistenceReconfigurationError("prepared maintenance is not persistence reconfiguration");
128
+ }
129
+
130
+ const at = prepared.maintenance.startedAt < record.updatedAt
131
+ ? record.updatedAt
132
+ : prepared.maintenance.startedAt;
133
+ const nextCheckpoint = change.action === "disable"
134
+ ? reconfiguredCheckpoint(change.checkpoint, at, null)
135
+ : await installReplacement(record, change.config, change.checkpoint, path, requestDigest, options.reconfigurationId, at);
136
+ if (change.action === "disable") await removeAndSync(path);
137
+ const { deletion: _deletion, ...activeRecord } = record;
138
+ const next: AgentSessionRecord = {
139
+ ...activeRecord,
140
+ recordRevision: record.recordRevision + 1,
141
+ checkpoint: nextCheckpoint,
142
+ transcript: change.action === "disable" ? null : {
143
+ path,
144
+ transcriptId: nextCheckpoint.transcript!.transcriptId,
145
+ generation: nextCheckpoint.transcript!.generation,
146
+ preset: change.config.preset ?? "activity",
147
+ effectivePolicy: resolveReplacementPolicy(record, change.config),
148
+ effectiveLimits: record.transcript!.effectiveLimits,
149
+ includeTruncationDigests: change.config.includeTruncationDigests ?? false,
150
+ },
151
+ updatedAt: at,
152
+ };
153
+ await store.finalizeMaintenance(
154
+ agentSessionId,
155
+ record.incarnationId,
156
+ options.reconfigurationId,
157
+ requestDigest,
158
+ { save: next },
159
+ );
160
+ return summarizeAgentSessionRecord(next);
161
+ });
162
+ }
163
+
164
+ async function reconfigureAuditLog(
165
+ store: AgentSessionStore,
166
+ agentSessionId: string,
167
+ options: ReconfigureAgentSessionPersistenceOptions,
168
+ ): Promise<AgentSessionSummary> {
169
+ const change = options.auditLog!;
170
+ const candidate = await store.getAgentSessionRecord(agentSessionId);
171
+ const retryPath = candidate?.auditLog?.path ?? (change.action === "replace" ? change.config.path : null);
172
+ if (!retryPath) throw new AgentSessionPersistenceReconfigurationError("session has no audit log to reconfigure");
173
+ const requestDigest = sha256CanonicalJson({
174
+ agentSessionId,
175
+ reconfigurationId: options.reconfigurationId,
176
+ expectedIncarnationId: options.expectedIncarnationId,
177
+ expectedRecordRevision: options.expectedRecordRevision,
178
+ auditLog: change,
179
+ });
180
+ const proposed = auditMaintenance(options, requestDigest, retryPath);
181
+ if (!candidate
182
+ || candidate.incarnationId !== options.expectedIncarnationId
183
+ || candidate.recordRevision !== options.expectedRecordRevision) {
184
+ const completed = await store.prepareMaintenance(agentSessionId, proposed, {
185
+ expectedRecordRevision: options.expectedRecordRevision,
186
+ });
187
+ if (completed.status === "already_completed") throw new MaintenanceAlreadyCompletedError(completed.receipt);
188
+ throw new AgentSessionStoreConflictError("agent-session record compare-and-swap failed");
189
+ }
190
+ if (!candidate.auditLog) throw new AgentSessionPersistenceReconfigurationError("session has no audit log to reconfigure");
191
+ if (change.action === "replace" && change.config.path !== candidate.auditLog.path) {
192
+ throw new AgentSessionPersistenceReconfigurationError("v0 replacement must retain the recorded audit-log path");
193
+ }
194
+ return await withSessionLogWriterLock(candidate.auditLog.path, async () => {
195
+ const record = await requireCurrent(store, agentSessionId, options);
196
+ const prepared = await store.prepareMaintenance(agentSessionId, proposed, {
197
+ expectedRecordRevision: options.expectedRecordRevision,
198
+ });
199
+ if (prepared.status === "already_completed") throw new MaintenanceAlreadyCompletedError(prepared.receipt);
200
+ const at = prepared.maintenance.startedAt < record.updatedAt
201
+ ? record.updatedAt : prepared.maintenance.startedAt;
202
+ let auditLog: AgentSessionRecord["auditLog"] = null;
203
+ if (change.action === "replace") {
204
+ auditLog = await installAuditReplacement(record, change.config, requestDigest, options.reconfigurationId, at);
205
+ } else {
206
+ await removeAndSync(record.auditLog!.path);
207
+ }
208
+ const next: AgentSessionRecord = {
209
+ ...record,
210
+ recordRevision: record.recordRevision + 1,
211
+ auditLog,
212
+ updatedAt: at,
213
+ };
214
+ await store.finalizeMaintenance(
215
+ agentSessionId, record.incarnationId, options.reconfigurationId, requestDigest,
216
+ { save: next },
217
+ );
218
+ return summarizeAgentSessionRecord(next);
219
+ });
220
+ }
221
+
222
+ function auditMaintenance(
223
+ options: ReconfigureAgentSessionPersistenceOptions,
224
+ requestDigest: string,
225
+ path: string,
226
+ ): PersistenceReconfigurationMaintenance {
227
+ return {
228
+ kind: "persistence_reconfiguration",
229
+ incarnationId: options.expectedIncarnationId,
230
+ baseRecordRevision: options.expectedRecordRevision,
231
+ operationId: options.reconfigurationId,
232
+ requestDigest,
233
+ status: "prepared",
234
+ startedAt: new Date().toISOString(),
235
+ details: {
236
+ transcript: null,
237
+ auditLog: options.auditLog!.action === "disable"
238
+ ? { action: "disable", previousPath: path }
239
+ : { action: "replace", previousPath: path, replacementPath: path },
240
+ },
241
+ };
242
+ }
243
+
244
+ async function installAuditReplacement(
245
+ record: AgentSessionRecord,
246
+ config: AuditLogConfig & { readonly path: string },
247
+ requestDigest: string,
248
+ operationId: string,
249
+ createdAt: string,
250
+ ): Promise<NonNullable<AgentSessionRecord["auditLog"]>> {
251
+ const auditLogId = randomUUID();
252
+ const tempPath = `${config.path}.replacement-${randomUUID()}`;
253
+ const resolved = resolveDirectPersistence({
254
+ transcript: false,
255
+ auditLog: config,
256
+ limits: record.auditLog!.effectiveLimits,
257
+ });
258
+ if (resolved === false || resolved.auditLog === false) throw new AgentSessionPersistenceReconfigurationError("replacement audit log is disabled");
259
+ const header = {
260
+ v: 1 as const, t: "header" as const, auditLogId, generation: 1,
261
+ agentSessionId: record.agentSessionId, seq: 1, ts: Date.parse(createdAt),
262
+ event: "replaced" as const, createdAt,
263
+ effectivePolicy: resolved.auditLog.capture,
264
+ effectiveLimits: resolved.limits,
265
+ includeTruncationDigests: resolved.auditLog.includeTruncationDigests,
266
+ installation: { kind: "persistence_reconfiguration" as const, operationId, requestDigest },
267
+ };
268
+ let writer: FileSessionLogWriter<"audit"> | undefined;
269
+ try {
270
+ writer = await FileSessionLogWriter.create({
271
+ kind: "audit", path: tempPath, header,
272
+ maxRecordBytes: resolved.limits.maxRecordBytes,
273
+ });
274
+ await writer.close();
275
+ writer = undefined;
276
+ await rename(tempPath, config.path);
277
+ await syncDirectory(dirname(config.path));
278
+ } catch (error) {
279
+ await writer?.close().catch(() => undefined);
280
+ await unlink(tempPath).catch(() => undefined);
281
+ throw error;
282
+ }
283
+ return {
284
+ path: config.path, auditLogId, generation: 1,
285
+ effectivePolicy: resolved.auditLog.capture,
286
+ effectiveLimits: resolved.limits,
287
+ includeTruncationDigests: resolved.auditLog.includeTruncationDigests,
288
+ };
289
+ }
290
+
291
+ function proposedMaintenance(
292
+ options: ReconfigureAgentSessionPersistenceOptions,
293
+ requestDigest: string,
294
+ path: string,
295
+ ): PersistenceReconfigurationMaintenance {
296
+ return {
297
+ kind: "persistence_reconfiguration",
298
+ incarnationId: options.expectedIncarnationId,
299
+ baseRecordRevision: options.expectedRecordRevision,
300
+ operationId: options.reconfigurationId,
301
+ requestDigest,
302
+ status: "prepared",
303
+ startedAt: new Date().toISOString(),
304
+ details: {
305
+ transcript: options.transcript!.action === "disable"
306
+ ? { action: "disable", previousPath: path }
307
+ : { action: "replace", previousPath: path, replacementPath: path },
308
+ auditLog: null,
309
+ },
310
+ };
311
+ }
312
+
313
+ function reconfiguredCheckpoint(
314
+ source: AgentSessionCheckpoint,
315
+ updatedAt: string,
316
+ transcript: AgentSessionCheckpoint["transcript"],
317
+ ): AgentSessionCheckpoint {
318
+ const { version: _version, digest: _digest, ...input } = source;
319
+ return createAgentSessionCheckpoint({
320
+ ...input,
321
+ stateRevision: source.stateRevision + 1,
322
+ transcript,
323
+ updatedAt,
324
+ });
325
+ }
326
+
327
+ async function installReplacement(
328
+ record: AgentSessionRecord,
329
+ config: TranscriptConfig & { readonly path: string },
330
+ source: AgentSessionCheckpoint,
331
+ path: string,
332
+ requestDigest: string,
333
+ operationId: string,
334
+ updatedAt: string,
335
+ ): Promise<AgentSessionCheckpoint> {
336
+ const transcriptId = randomUUID();
337
+ const tempPath = `${path}.replacement-${randomUUID()}`;
338
+ const resolved = resolveDirectPersistence({
339
+ transcript: config,
340
+ auditLog: false,
341
+ sessionConfiguration: record.sessionConfigurationPersistence,
342
+ limits: record.transcript!.effectiveLimits,
343
+ });
344
+ if (resolved === false || resolved.transcript === false) throw new AgentSessionPersistenceReconfigurationError("replacement transcript is disabled");
345
+ const checkpoint = reconfiguredCheckpoint(source, updatedAt, {
346
+ transcriptId,
347
+ generation: 1,
348
+ path,
349
+ coveredSequence: 1,
350
+ });
351
+ const header: TranscriptHeaderRecord = {
352
+ v: 2,
353
+ t: "header",
354
+ transcriptId,
355
+ generation: 1,
356
+ agentSessionId: record.agentSessionId,
357
+ seq: 1,
358
+ ts: Date.parse(updatedAt),
359
+ event: "replaced",
360
+ createdAt: updatedAt,
361
+ preset: resolved.transcript.preset,
362
+ effectivePolicy: resolved.transcript.capture,
363
+ effectiveLimits: resolved.limits,
364
+ includeTruncationDigests: resolved.transcript.includeTruncationDigests,
365
+ installation: { kind: "persistence_reconfiguration", operationId, requestDigest },
366
+ };
367
+ let writer: FileSessionLogWriter<"transcript"> | undefined;
368
+ try {
369
+ writer = await FileSessionLogWriter.create({
370
+ kind: "transcript",
371
+ path: tempPath,
372
+ logicalPath: path,
373
+ header,
374
+ maxRecordBytes: resolved.limits.maxRecordBytes,
375
+ });
376
+ await writer.append({
377
+ v: 2, t: "checkpoint", transcriptId, generation: 1,
378
+ agentSessionId: record.agentSessionId, seq: 2, ts: Date.parse(updatedAt),
379
+ stateRevision: checkpoint.stateRevision, checkpoint,
380
+ }, { durable: true });
381
+ await writer.close();
382
+ writer = undefined;
383
+ await rename(tempPath, path);
384
+ await syncDirectory(dirname(path));
385
+ return checkpoint;
386
+ } catch (error) {
387
+ await writer?.close().catch(() => undefined);
388
+ await unlink(tempPath).catch(() => undefined);
389
+ throw error;
390
+ }
391
+ }
392
+
393
+ function resolveReplacementPolicy(record: AgentSessionRecord, config: TranscriptConfig) {
394
+ const resolved = resolveDirectPersistence({
395
+ transcript: config,
396
+ auditLog: false,
397
+ limits: record.transcript!.effectiveLimits,
398
+ });
399
+ if (resolved === false || resolved.transcript === false) throw new AgentSessionPersistenceReconfigurationError("replacement transcript is disabled");
400
+ return resolved.transcript.capture;
401
+ }
402
+
403
+ async function requireCurrent(
404
+ store: AgentSessionStore,
405
+ id: string,
406
+ options: ReconfigureAgentSessionPersistenceOptions,
407
+ ): Promise<AgentSessionRecord> {
408
+ const record = await store.getAgentSessionRecord(id);
409
+ if (!record) throw new AgentSessionStoreConflictError("agent-session record does not exist");
410
+ if (record.incarnationId !== options.expectedIncarnationId
411
+ || record.recordRevision !== options.expectedRecordRevision) {
412
+ throw new AgentSessionStoreConflictError("agent-session record compare-and-swap failed");
413
+ }
414
+ return record;
415
+ }
416
+
417
+ function validateRequest(id: string, options: ReconfigureAgentSessionPersistenceOptions): void {
418
+ if (!id.trim() || !options?.reconfigurationId?.trim() || !options?.expectedIncarnationId?.trim()) {
419
+ throw new AgentSessionPersistenceReconfigurationError("session, reconfiguration, and incarnation IDs must be nonblank");
420
+ }
421
+ if (!Number.isSafeInteger(options.expectedRecordRevision) || options.expectedRecordRevision < 1) {
422
+ throw new AgentSessionPersistenceReconfigurationError("expectedRecordRevision must be a positive safe integer");
423
+ }
424
+ if (!options.transcript && options.auditLog === undefined) {
425
+ throw new AgentSessionPersistenceReconfigurationError("at least one persistence change is required");
426
+ }
427
+ if (options.transcript?.action === "disable"
428
+ && (!options.transcript.deleteExistingLog || !options.transcript.acknowledgeContinuationLoss)) {
429
+ throw new AgentSessionPersistenceReconfigurationError("disabling a transcript requires deletion and continuation-loss acknowledgement");
430
+ }
431
+ if (options.transcript?.action === "replace" && !options.transcript.acknowledgeContinuationLoss) {
432
+ throw new AgentSessionPersistenceReconfigurationError("replacing a transcript requires continuation-loss acknowledgement");
433
+ }
434
+ if (options.auditLog?.action === "disable"
435
+ && (!options.auditLog.deleteExistingLog || !options.auditLog.acknowledgeAuditGap)) {
436
+ throw new AgentSessionPersistenceReconfigurationError("disabling an audit log requires deletion and audit-gap acknowledgement");
437
+ }
438
+ if (options.auditLog?.action === "replace" && !options.auditLog.acknowledgeAuditGap) {
439
+ throw new AgentSessionPersistenceReconfigurationError("replacing an audit log requires audit-gap acknowledgement");
440
+ }
441
+ }
442
+
443
+ async function removeAndSync(path: string): Promise<void> {
444
+ await unlink(path).catch((error) => {
445
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
446
+ });
447
+ await syncDirectory(dirname(path));
448
+ }
449
+
450
+ async function syncDirectory(path: string): Promise<void> {
451
+ const handle = await open(path, "r");
452
+ try { await handle.sync(); } finally { await handle.close(); }
453
+ }