@qlairoslabs/acp-client 0.7.3 → 0.8.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 (58) hide show
  1. package/CHANGELOG-audit.md +58 -0
  2. package/CONSUMER_GUIDE.md +474 -19
  3. package/package.json +6 -1
  4. package/src/agent-adapter-registry.ts +66 -0
  5. package/src/agent-conversation-continuation.ts +121 -0
  6. package/src/agent-conversation-contracts.ts +279 -0
  7. package/src/agent-conversation-errors.ts +31 -0
  8. package/src/agent-conversation-owner.ts +55 -0
  9. package/src/agent-conversation-presentation.ts +217 -0
  10. package/src/agent-conversation-queue.ts +44 -0
  11. package/src/agent-conversation.ts +41 -0
  12. package/src/agent-ids.ts +50 -0
  13. package/src/agent-session.ts +1022 -682
  14. package/src/agent.ts +1175 -0
  15. package/src/audit/config.ts +186 -0
  16. package/src/audit/contracts.ts +59 -0
  17. package/src/audit/index.ts +50 -0
  18. package/src/audit/projection.ts +125 -0
  19. package/src/audit/reader.ts +371 -0
  20. package/src/audit/runtime.ts +1060 -0
  21. package/src/checkpointing/config.ts +91 -0
  22. package/src/checkpointing/contracts.ts +45 -0
  23. package/src/checkpointing/coordinator.ts +100 -0
  24. package/src/checkpointing/ids.ts +5 -0
  25. package/src/checkpointing/index.ts +6 -0
  26. package/src/checkpointing/persistence/sqlite-repository.ts +159 -0
  27. package/src/checkpointing/recovery.ts +114 -0
  28. package/src/checkpointing/strategy.ts +139 -0
  29. package/src/controller.ts +37 -5
  30. package/src/identity.ts +62 -0
  31. package/src/index.ts +121 -0
  32. package/src/internal-inference/config.ts +68 -0
  33. package/src/internal-inference/contracts.ts +218 -0
  34. package/src/internal-inference/coordination/handles.ts +133 -0
  35. package/src/internal-inference/coordination/manager.ts +487 -0
  36. package/src/internal-inference/ids.ts +10 -0
  37. package/src/internal-inference/index.ts +10 -0
  38. package/src/internal-inference/persistence/records.ts +132 -0
  39. package/src/internal-inference/persistence/repository.ts +35 -0
  40. package/src/internal-inference/persistence/sqlite-repository.ts +551 -0
  41. package/src/internal-inference/runtime/harness-runtime.ts +78 -0
  42. package/src/internal-inference/strategy/registry.ts +42 -0
  43. package/src/metering/engine.ts +47 -0
  44. package/src/metering/record.ts +4 -1
  45. package/src/observation/contracts.ts +10 -0
  46. package/src/observation/index.ts +8 -0
  47. package/src/observation/subscription-hub.ts +43 -0
  48. package/src/persistence/activity-projection.ts +26 -12
  49. package/src/persistence/backend.ts +774 -0
  50. package/src/persistence/index.ts +99 -0
  51. package/src/persistence/managed-creation.ts +18 -2
  52. package/src/persistence/managed-load.ts +19 -5
  53. package/src/persistence/managed-open-progress.ts +54 -0
  54. package/src/persistence/presentation.ts +3 -0
  55. package/src/persistence/sqlite-backend.ts +1927 -0
  56. package/src/persistence/sqlite-conversation-records.ts +425 -0
  57. package/src/persistence/sqlite-owner-lock.ts +106 -0
  58. package/src/persistence/sqlite-schema.ts +561 -0
@@ -0,0 +1,774 @@
1
+ import type { AgentConversationId, AgentSessionId } from "../agent-ids.ts";
2
+ import type { OperationMeteringRecord } from "../metering/record.ts";
3
+ import type { AgentSessionMeteringState } from "../metering/state.ts";
4
+ import type { InternalInferenceRepository } from "../internal-inference/persistence/repository.ts";
5
+ import type { ConversationRecoveryCheckpointRepository } from "../checkpointing/contracts.ts";
6
+
7
+ export type PersistenceJsonPrimitive = string | number | boolean | null;
8
+ export type PersistenceJsonValue =
9
+ | PersistenceJsonPrimitive
10
+ | readonly PersistenceJsonValue[]
11
+ | { readonly [key: string]: PersistenceJsonValue };
12
+
13
+ export const PARTICIPANT_KINDS = ["agent", "user", "external"] as const;
14
+ export type ParticipantKind = (typeof PARTICIPANT_KINDS)[number];
15
+
16
+ /** Reserved continuity identity used when a caller supplies no user participant ID. */
17
+ export const IMPLICIT_USER_PARTICIPANT_ID = "user:default";
18
+
19
+ export interface ParticipantRef {
20
+ readonly id: string;
21
+ readonly kind: ParticipantKind;
22
+ readonly name?: string;
23
+ }
24
+
25
+ export const CONVERSATION_RECORD_KINDS = [
26
+ "message",
27
+ "tool_call",
28
+ "permission",
29
+ "configuration",
30
+ "protocol",
31
+ "native_action",
32
+ "agent_action",
33
+ "thinking",
34
+ "activity",
35
+ "metering",
36
+ ] as const;
37
+
38
+ export type ConversationRecordKind = (typeof CONVERSATION_RECORD_KINDS)[number];
39
+
40
+ export interface ConversationRecordEnvelope<K extends ConversationRecordKind = ConversationRecordKind> {
41
+ readonly recordId: string;
42
+ readonly agentSessionId: AgentSessionId;
43
+ readonly agentConversationId: AgentConversationId;
44
+ /** Assigned atomically by the backend and monotonic within one conversation. */
45
+ readonly sequence: number;
46
+ readonly kind: K;
47
+ /** ISO-8601 instant supplied by the producer and preserved verbatim. */
48
+ readonly timestamp: string;
49
+ /** Opaque consumer data. The library does not parse or merge this string. */
50
+ readonly metadata?: string;
51
+ }
52
+
53
+ export type PersistedContentBlock =
54
+ | { readonly type: "text"; readonly text: string }
55
+ | {
56
+ readonly type: "image";
57
+ readonly mimeType: string;
58
+ readonly uri?: string;
59
+ readonly data?: string;
60
+ readonly alt?: string;
61
+ }
62
+ | {
63
+ readonly type: "resource";
64
+ readonly uri: string;
65
+ readonly mimeType?: string;
66
+ readonly title?: string;
67
+ readonly text?: string;
68
+ }
69
+ | { readonly type: "json"; readonly value: PersistenceJsonValue };
70
+
71
+ export type PersistedContent = string | readonly PersistedContentBlock[];
72
+
73
+ export interface MessageRecord extends ConversationRecordEnvelope<"message"> {
74
+ readonly role: "assistant" | "user";
75
+ /** The local agent is implied when omitted on an assistant message. */
76
+ readonly participantId?: string;
77
+ readonly content: PersistedContent;
78
+ readonly status?: "in_progress" | "completed" | "cancelled" | "failed";
79
+ }
80
+
81
+ export interface ToolCallRecord extends ConversationRecordEnvelope<"tool_call"> {
82
+ readonly toolCallId: string;
83
+ readonly state: "announced" | "input" | "completed" | "failed";
84
+ readonly name?: string;
85
+ readonly input?: PersistenceJsonValue;
86
+ readonly output?: PersistedContent;
87
+ readonly error?: string;
88
+ }
89
+
90
+ export interface PermissionRecord extends ConversationRecordEnvelope<"permission"> {
91
+ readonly permissionId: string;
92
+ readonly state: "requested" | "resolved";
93
+ readonly request?: PersistenceJsonValue;
94
+ readonly outcome?: "approved" | "denied" | "cancelled";
95
+ }
96
+
97
+ export interface ConfigurationRecord extends ConversationRecordEnvelope<"configuration"> {
98
+ readonly operation: "set" | "restore" | "accept_effective" | "replace";
99
+ readonly configId?: string;
100
+ readonly value?: PersistenceJsonValue;
101
+ readonly status: "started" | "completed" | "failed";
102
+ readonly error?: string;
103
+ }
104
+
105
+ export interface ProtocolRecord extends ConversationRecordEnvelope<"protocol"> {
106
+ readonly direction: "in" | "out" | "error";
107
+ readonly method?: string;
108
+ readonly message?: PersistenceJsonValue;
109
+ }
110
+
111
+ export interface NativeActionRecord extends ConversationRecordEnvelope<"native_action"> {
112
+ readonly action: string;
113
+ readonly transitionId?: string;
114
+ readonly state: "started" | "checkpoint" | "completed" | "failed";
115
+ readonly input?: PersistenceJsonValue;
116
+ readonly output?: PersistenceJsonValue;
117
+ readonly error?: string;
118
+ }
119
+
120
+ export interface AgentActionRecord extends ConversationRecordEnvelope<"agent_action"> {
121
+ readonly action: string;
122
+ readonly state: "requested" | "completed" | "failed";
123
+ readonly input?: PersistenceJsonValue;
124
+ readonly output?: PersistenceJsonValue;
125
+ readonly error?: string;
126
+ }
127
+
128
+ export interface ThinkingRecord extends ConversationRecordEnvelope<"thinking"> {
129
+ readonly thinkingId: string;
130
+ readonly state: "in_progress" | "completed" | "failed";
131
+ readonly content: PersistedContent;
132
+ }
133
+
134
+ export interface ActivityRecord extends ConversationRecordEnvelope<"activity"> {
135
+ readonly activityId: string;
136
+ readonly activityType: string;
137
+ readonly state: "in_progress" | "completed" | "failed";
138
+ readonly content?: PersistedContent;
139
+ readonly data?: PersistenceJsonValue;
140
+ }
141
+
142
+ /** Ordered conversation-timeline pointer to the complete financial record. */
143
+ export interface MeteringReferenceRecord extends ConversationRecordEnvelope<"metering"> {
144
+ readonly operationId: string;
145
+ readonly meteringRecordId: string;
146
+ readonly status: "available" | "partial" | "unavailable";
147
+ }
148
+
149
+ export type ConversationRecord =
150
+ | MessageRecord
151
+ | ToolCallRecord
152
+ | PermissionRecord
153
+ | ConfigurationRecord
154
+ | ProtocolRecord
155
+ | NativeActionRecord
156
+ | AgentActionRecord
157
+ | ThinkingRecord
158
+ | ActivityRecord
159
+ | MeteringReferenceRecord;
160
+
161
+ type WithoutSequence<T> = T extends ConversationRecord ? Omit<T, "sequence"> : never;
162
+ export type NewConversationRecord = WithoutSequence<ConversationRecord>;
163
+
164
+ export type RecordCaptureLevel = "none" | "metadata" | "content" | "raw";
165
+ export type ProtocolRecordCaptureLevel = "none" | "metadata" | "raw";
166
+ export interface ProtocolRecordCaptureOptions {
167
+ readonly level: ProtocolRecordCaptureLevel;
168
+ /** Exact ACP method names. Methodless responses are always retained. */
169
+ readonly includeMethods?: readonly string[];
170
+ /** Exact ACP method names. Applied before sequence allocation. */
171
+ readonly excludeMethods?: readonly string[];
172
+ }
173
+ export type ProtocolRecordCapture = ProtocolRecordCaptureLevel | ProtocolRecordCaptureOptions;
174
+ type NonProtocolRecordKind = Exclude<ConversationRecordKind, "protocol">;
175
+ export type ConversationRecordCaptureConfig = Readonly<
176
+ Partial<Record<NonProtocolRecordKind, RecordCaptureLevel>> & {
177
+ readonly protocol?: ProtocolRecordCapture;
178
+ }
179
+ >;
180
+ export type ResolvedProtocolRecordCapturePolicy = Readonly<{
181
+ level: ProtocolRecordCaptureLevel;
182
+ includeMethods: readonly string[];
183
+ excludeMethods: readonly string[];
184
+ }>;
185
+ export type ConversationRecordCapturePolicy = Readonly<
186
+ Record<NonProtocolRecordKind, RecordCaptureLevel> & {
187
+ readonly protocol: ResolvedProtocolRecordCapturePolicy;
188
+ }
189
+ >;
190
+
191
+ const DEFAULT_PROTOCOL_RECORD_CAPTURE: ResolvedProtocolRecordCapturePolicy = Object.freeze({
192
+ level: "none",
193
+ includeMethods: Object.freeze([]),
194
+ excludeMethods: Object.freeze([]),
195
+ });
196
+
197
+ export const DEFAULT_CONVERSATION_RECORD_CAPTURE: ConversationRecordCapturePolicy = Object.freeze({
198
+ message: "content",
199
+ tool_call: "metadata",
200
+ permission: "metadata",
201
+ configuration: "metadata",
202
+ protocol: DEFAULT_PROTOCOL_RECORD_CAPTURE,
203
+ native_action: "metadata",
204
+ agent_action: "metadata",
205
+ thinking: "none",
206
+ activity: "metadata",
207
+ metering: "metadata",
208
+ });
209
+
210
+ export interface AgentPersistenceIdentity {
211
+ readonly agentSessionId: AgentSessionId;
212
+ readonly createdAt: string;
213
+ readonly updatedAt: string;
214
+ readonly metadata?: string;
215
+ }
216
+
217
+ export interface AgentConversationSummary {
218
+ readonly agentConversationId: AgentConversationId;
219
+ readonly agentSessionId: AgentSessionId;
220
+ readonly title?: string;
221
+ readonly participants: readonly ParticipantRef[];
222
+ readonly createdAt: string;
223
+ readonly updatedAt: string;
224
+ readonly latestSequence: number;
225
+ readonly deletedAt?: string;
226
+ readonly metadata?: string;
227
+ }
228
+
229
+ export interface CreateAgentConversationInput {
230
+ readonly agentConversationId: AgentConversationId;
231
+ readonly agentSessionId: AgentSessionId;
232
+ readonly participants?: readonly ParticipantRef[];
233
+ readonly title?: string;
234
+ readonly createdAt?: string;
235
+ readonly metadata?: string;
236
+ }
237
+
238
+ export interface ConversationListOptions {
239
+ readonly participantIds?: readonly string[];
240
+ readonly includeDeleted?: boolean;
241
+ readonly limit?: number;
242
+ readonly cursor?: string;
243
+ }
244
+
245
+ export interface ConversationPage {
246
+ readonly conversations: readonly AgentConversationSummary[];
247
+ readonly nextCursor?: string;
248
+ }
249
+
250
+ export interface RecordListOptions {
251
+ readonly kinds?: readonly ConversationRecordKind[];
252
+ readonly afterSequence?: number;
253
+ readonly throughSequence?: number;
254
+ readonly limit?: number;
255
+ readonly cursor?: string;
256
+ }
257
+
258
+ export interface ConversationRecordPage {
259
+ readonly records: readonly ConversationRecord[];
260
+ readonly nextCursor?: string;
261
+ }
262
+
263
+ export interface MessageListOptions {
264
+ readonly afterSequence?: number;
265
+ readonly throughSequence?: number;
266
+ readonly participantIds?: readonly string[];
267
+ readonly limit?: number;
268
+ readonly cursor?: string;
269
+ }
270
+
271
+ export interface MessagePage {
272
+ readonly messages: readonly MessageRecord[];
273
+ readonly nextCursor?: string;
274
+ }
275
+
276
+ export interface ConversationRuntimeCheckpoint {
277
+ readonly agentConversationId: AgentConversationId;
278
+ readonly revision: number;
279
+ readonly coveredSequence: number;
280
+ readonly state: PersistenceJsonValue;
281
+ readonly updatedAt: string;
282
+ }
283
+
284
+ export interface ProviderSessionRecord {
285
+ readonly providerSessionRecordId: string;
286
+ readonly agentConversationId: AgentConversationId;
287
+ readonly internalSessionId: string;
288
+ readonly adapterId: string;
289
+ readonly mode: "normal" | "degraded";
290
+ readonly model?: string;
291
+ readonly activatedAt: string;
292
+ readonly deactivatedAt?: string;
293
+ readonly transitionId?: string;
294
+ readonly metadata?: string;
295
+ }
296
+
297
+ export interface SearchQuery {
298
+ readonly text: string;
299
+ readonly conversationIds?: readonly AgentConversationId[];
300
+ readonly participantIds?: readonly string[];
301
+ readonly kinds?: readonly ConversationRecordKind[];
302
+ readonly after?: string;
303
+ readonly before?: string;
304
+ readonly limit?: number;
305
+ }
306
+
307
+ export interface SearchMatch {
308
+ readonly recordId: string;
309
+ readonly agentConversationId: AgentConversationId;
310
+ readonly sequence: number;
311
+ readonly kind: ConversationRecordKind;
312
+ /** Backend-specific relevance where lower or higher is not assumed by consumers. */
313
+ readonly score: number;
314
+ readonly snippet?: string;
315
+ }
316
+
317
+ export interface IdentityMemoryObservation {
318
+ readonly memoryId: string;
319
+ readonly agentSessionId: AgentSessionId;
320
+ readonly sequence: number;
321
+ readonly sourceConversationId: AgentConversationId;
322
+ readonly sourceRecordIds: readonly string[];
323
+ readonly participantId?: string;
324
+ readonly kind: string;
325
+ readonly content: PersistenceJsonValue;
326
+ readonly createdAt: string;
327
+ readonly metadata?: string;
328
+ }
329
+
330
+ export type NewIdentityMemoryObservation = Omit<IdentityMemoryObservation, "sequence">;
331
+
332
+ export interface PersistedIdentitySnapshot {
333
+ readonly snapshotId: string;
334
+ readonly agentSessionId: AgentSessionId;
335
+ readonly version: number;
336
+ readonly processedThroughSequence: number;
337
+ readonly value: PersistenceJsonValue;
338
+ readonly createdAt: string;
339
+ }
340
+
341
+ export interface IdentityProjectionState {
342
+ readonly agentSessionId: AgentSessionId;
343
+ readonly observedThroughSequence: number;
344
+ readonly processedThroughSequence: number;
345
+ readonly activeSnapshotId?: string;
346
+ }
347
+
348
+ export interface AuditOutboxItem {
349
+ readonly outboxId: string;
350
+ readonly auditSequence: number;
351
+ readonly sourceObservationId: string;
352
+ readonly sourceRecordId?: string;
353
+ readonly operationId?: string;
354
+ readonly agentConversationId?: AgentConversationId;
355
+ readonly occurredAt: string;
356
+ readonly kind: string;
357
+ readonly captureLevel: string;
358
+ readonly captureFingerprint: string;
359
+ readonly payload: PersistenceJsonValue;
360
+ readonly payloadSha256: string;
361
+ readonly payloadBytes: number;
362
+ readonly createdAt: string;
363
+ readonly attemptCount: number;
364
+ readonly nextAttemptAt?: string;
365
+ readonly lastError?: string;
366
+ }
367
+
368
+ export type NewAuditOutboxItem = Omit<
369
+ AuditOutboxItem,
370
+ | "auditSequence"
371
+ | "payloadSha256"
372
+ | "payloadBytes"
373
+ | "attemptCount"
374
+ | "nextAttemptAt"
375
+ | "lastError"
376
+ >;
377
+
378
+ export interface AgentAuditState {
379
+ readonly auditLogId: string;
380
+ readonly lastAllocatedSequence: number;
381
+ readonly lastDeliveredSequence: number;
382
+ readonly captureFingerprint: string;
383
+ readonly createdAt: string;
384
+ readonly updatedAt: string;
385
+ }
386
+
387
+ export interface AuditOutboxBacklog {
388
+ readonly pendingCount: number;
389
+ readonly pendingPayloadBytes: number;
390
+ readonly oldestPendingAt?: string;
391
+ }
392
+
393
+ export interface PersistenceExtensionRegistration {
394
+ readonly extensionId: string;
395
+ readonly schemaVersion: number;
396
+ readonly installedAt: string;
397
+ readonly updatedAt: string;
398
+ }
399
+
400
+ export interface ConversationPersistence {
401
+ create(input: CreateAgentConversationInput): Promise<AgentConversationSummary>;
402
+ get(agentConversationId: AgentConversationId): Promise<AgentConversationSummary | null>;
403
+ list(options?: ConversationListOptions): Promise<ConversationPage>;
404
+ renameParticipant(
405
+ agentConversationId: AgentConversationId,
406
+ participantId: string,
407
+ name: string | undefined,
408
+ ): Promise<void>;
409
+ ensureParticipant(
410
+ agentConversationId: AgentConversationId,
411
+ participant: ParticipantRef,
412
+ ): Promise<ParticipantRef>;
413
+ delete(agentConversationId: AgentConversationId, deletedAt?: string): Promise<void>;
414
+ }
415
+
416
+ export interface ConversationRecordPersistence {
417
+ append(record: NewConversationRecord): Promise<ConversationRecord>;
418
+ appendMany(records: readonly NewConversationRecord[]): Promise<readonly ConversationRecord[]>;
419
+ get(recordId: string): Promise<ConversationRecord | null>;
420
+ list(
421
+ agentConversationId: AgentConversationId,
422
+ options?: RecordListOptions,
423
+ ): Promise<ConversationRecordPage>;
424
+ }
425
+
426
+ export interface ConversationMessagePersistence {
427
+ list(
428
+ agentConversationId: AgentConversationId,
429
+ options?: MessageListOptions,
430
+ ): Promise<MessagePage>;
431
+ }
432
+
433
+ export interface ConversationCheckpointPersistence {
434
+ get(agentConversationId: AgentConversationId): Promise<ConversationRuntimeCheckpoint | null>;
435
+ put(
436
+ checkpoint: ConversationRuntimeCheckpoint,
437
+ expectedRevision?: number,
438
+ ): Promise<ConversationRuntimeCheckpoint>;
439
+ }
440
+
441
+ export interface ProviderSessionPersistence {
442
+ append(record: ProviderSessionRecord): Promise<void>;
443
+ list(agentConversationId: AgentConversationId): Promise<readonly ProviderSessionRecord[]>;
444
+ active(agentConversationId: AgentConversationId): Promise<ProviderSessionRecord | null>;
445
+ }
446
+
447
+ export type MeteringRecordRetention = "all" | "none" | { readonly retain: number };
448
+
449
+ export interface PersistedConversationMeteringState {
450
+ readonly agentConversationId: AgentConversationId;
451
+ readonly revision: number;
452
+ readonly state: AgentSessionMeteringState;
453
+ readonly updatedAt: string;
454
+ }
455
+
456
+ export interface MeteringCommitInput {
457
+ readonly agentConversationId: AgentConversationId;
458
+ readonly record: OperationMeteringRecord;
459
+ readonly meteringRecords: MeteringRecordRetention;
460
+ readonly updatedAt?: string;
461
+ }
462
+
463
+ export interface PersistedAgentMeteringState {
464
+ readonly agentSessionId: AgentSessionId;
465
+ readonly revision: number;
466
+ readonly state: AgentSessionMeteringState;
467
+ readonly updatedAt: string;
468
+ }
469
+
470
+ export interface AgentMeteringCommitInput {
471
+ readonly agentSessionId: AgentSessionId;
472
+ readonly record: OperationMeteringRecord;
473
+ readonly meteringRecords: MeteringRecordRetention;
474
+ readonly updatedAt?: string;
475
+ }
476
+
477
+ export interface MeteringRecordListOptions {
478
+ readonly limit?: number;
479
+ readonly cursor?: string;
480
+ }
481
+
482
+ export interface MeteringRecordPage {
483
+ readonly records: readonly OperationMeteringRecord[];
484
+ readonly nextCursor?: string;
485
+ }
486
+
487
+ export interface MeteringPersistence {
488
+ /** Atomically deduplicate the operation and advance its bounded restoration state. */
489
+ commit(input: MeteringCommitInput): Promise<PersistedConversationMeteringState>;
490
+ saveState(
491
+ agentConversationId: AgentConversationId,
492
+ state: AgentSessionMeteringState,
493
+ updatedAt?: string,
494
+ ): Promise<PersistedConversationMeteringState>;
495
+ state(agentConversationId: AgentConversationId): Promise<PersistedConversationMeteringState | null>;
496
+ list(
497
+ agentConversationId: AgentConversationId,
498
+ options?: MeteringRecordListOptions,
499
+ ): Promise<MeteringRecordPage>;
500
+ get(
501
+ agentConversationId: AgentConversationId,
502
+ operationId: string,
503
+ ): Promise<OperationMeteringRecord | null>;
504
+ /** Agent-level scope for internal work that was not caused by a conversation. */
505
+ commitAgent(input: AgentMeteringCommitInput): Promise<PersistedAgentMeteringState>;
506
+ agentState(agentSessionId: AgentSessionId): Promise<PersistedAgentMeteringState | null>;
507
+ listAgent(
508
+ agentSessionId: AgentSessionId,
509
+ options?: MeteringRecordListOptions,
510
+ ): Promise<MeteringRecordPage>;
511
+ getAgent(agentSessionId: AgentSessionId, operationId: string): Promise<OperationMeteringRecord | null>;
512
+ }
513
+
514
+ export interface SearchPersistence {
515
+ search(query: SearchQuery): Promise<readonly SearchMatch[]>;
516
+ rebuild(): Promise<void>;
517
+ integrityCheck(): Promise<void>;
518
+ }
519
+
520
+ export interface IdentityPersistence {
521
+ append(
522
+ observations: readonly NewIdentityMemoryObservation[],
523
+ ): Promise<readonly IdentityMemoryObservation[]>;
524
+ listAfter(sequence: number, limit?: number): Promise<readonly IdentityMemoryObservation[]>;
525
+ latestSnapshot(): Promise<PersistedIdentitySnapshot | null>;
526
+ publishSnapshot(
527
+ snapshot: PersistedIdentitySnapshot,
528
+ expectedVersion?: number,
529
+ ): Promise<void>;
530
+ projectionState(): Promise<IdentityProjectionState>;
531
+ }
532
+
533
+ export interface AuditOutboxPersistence {
534
+ initialize(auditLogId: string, captureFingerprint: string, now?: string): Promise<AgentAuditState>;
535
+ state(): Promise<AgentAuditState | null>;
536
+ backlog(): Promise<AuditOutboxBacklog>;
537
+ enqueue(item: NewAuditOutboxItem): Promise<AuditOutboxItem>;
538
+ head(): Promise<AuditOutboxItem | null>;
539
+ pending(limit?: number, now?: string): Promise<readonly AuditOutboxItem[]>;
540
+ acknowledge(outboxIds: readonly string[], deliveredAt?: string): Promise<AgentAuditState>;
541
+ markFailed(outboxId: string, error: string, nextAttemptAt?: string): Promise<void>;
542
+ retryHead(): Promise<void>;
543
+ }
544
+
545
+ export interface PersistenceExtensionCatalog {
546
+ get(extensionId: string): Promise<PersistenceExtensionRegistration | null>;
547
+ list(): Promise<readonly PersistenceExtensionRegistration[]>;
548
+ }
549
+
550
+ export interface PersistenceCapabilities {
551
+ readonly transactions: true;
552
+ readonly fullTextSearch: boolean;
553
+ readonly identity: boolean;
554
+ readonly auditOutbox: boolean;
555
+ readonly extensions: boolean;
556
+ readonly vectorSearch: boolean;
557
+ readonly metering: boolean;
558
+ }
559
+
560
+ export interface PersistenceScope {
561
+ readonly conversations: ConversationPersistence;
562
+ readonly records: ConversationRecordPersistence;
563
+ readonly messages: ConversationMessagePersistence;
564
+ readonly checkpoints: ConversationCheckpointPersistence;
565
+ readonly providerSessions: ProviderSessionPersistence;
566
+ readonly metering: MeteringPersistence;
567
+ readonly internalInferences?: InternalInferenceRepository;
568
+ readonly recoveryCheckpoints?: ConversationRecoveryCheckpointRepository;
569
+ readonly identity?: IdentityPersistence;
570
+ readonly search?: SearchPersistence;
571
+ readonly auditOutbox?: AuditOutboxPersistence;
572
+ readonly extensions?: PersistenceExtensionCatalog;
573
+ }
574
+
575
+ export interface PersistenceBackend extends PersistenceScope {
576
+ readonly identityRecord: AgentPersistenceIdentity;
577
+ readonly capabilities: PersistenceCapabilities;
578
+ transaction<T>(work: (transaction: PersistenceScope) => T | Promise<T>): Promise<T>;
579
+ close(): Promise<void>;
580
+ }
581
+
582
+ export interface PersistenceExtensionMigrationContext {
583
+ readonly extensionId: string;
584
+ readonly installedVersion: number;
585
+ execute(sql: string, parameters?: readonly PersistenceJsonPrimitive[]): Promise<void>;
586
+ }
587
+
588
+ export interface PersistenceExtension {
589
+ readonly id: string;
590
+ readonly version: number;
591
+ migrate(context: PersistenceExtensionMigrationContext): Promise<void>;
592
+ recordsCommitted?(records: readonly ConversationRecord[]): Promise<void>;
593
+ }
594
+
595
+ export interface VectorSearchQuery {
596
+ readonly embedding: readonly number[];
597
+ readonly limit?: number;
598
+ readonly conversationIds?: readonly AgentConversationId[];
599
+ readonly participantIds?: readonly string[];
600
+ }
601
+
602
+ export interface VectorSearchMatch {
603
+ readonly memoryId: string;
604
+ readonly distance: number;
605
+ }
606
+
607
+ export interface VectorIndex {
608
+ upsert(
609
+ values: readonly {
610
+ readonly memoryId: string;
611
+ readonly modelId: string;
612
+ readonly embedding: readonly number[];
613
+ }[],
614
+ ): Promise<void>;
615
+ remove(memoryIds: readonly string[]): Promise<void>;
616
+ search(query: VectorSearchQuery): Promise<readonly VectorSearchMatch[]>;
617
+ }
618
+
619
+ export class PersistenceConflictError extends Error {
620
+ constructor(message: string) {
621
+ super(message);
622
+ this.name = "PersistenceConflictError";
623
+ }
624
+ }
625
+
626
+ export class PersistenceCapabilityError extends Error {
627
+ constructor(capability: keyof PersistenceCapabilities) {
628
+ super(`persistence capability is unavailable: ${capability}`);
629
+ this.name = "PersistenceCapabilityError";
630
+ }
631
+ }
632
+
633
+ export function isParticipantKind(value: unknown): value is ParticipantKind {
634
+ return typeof value === "string" && PARTICIPANT_KINDS.includes(value as ParticipantKind);
635
+ }
636
+
637
+ export function normalizeParticipantRef(participant: ParticipantRef): ParticipantRef {
638
+ const id = participant.id.trim();
639
+ if (!id) throw new Error("participant id cannot be blank");
640
+ if (!isParticipantKind(participant.kind)) {
641
+ throw new Error(`unsupported participant kind: ${String(participant.kind)}`);
642
+ }
643
+ const name = participant.name?.trim();
644
+ return Object.freeze({
645
+ id,
646
+ kind: participant.kind,
647
+ ...(name ? { name } : {}),
648
+ });
649
+ }
650
+
651
+ export function isConversationRecordKind(value: unknown): value is ConversationRecordKind {
652
+ return typeof value === "string"
653
+ && CONVERSATION_RECORD_KINDS.includes(value as ConversationRecordKind);
654
+ }
655
+
656
+ export function resolveConversationRecordCapture(
657
+ override: ConversationRecordCaptureConfig = {},
658
+ ): ConversationRecordCapturePolicy {
659
+ const resolved: Record<string, unknown> = { ...DEFAULT_CONVERSATION_RECORD_CAPTURE };
660
+ for (const [kind, value] of Object.entries(override)) {
661
+ if (!isConversationRecordKind(kind)) throw new Error(`unknown record capture kind: ${kind}`);
662
+ if (kind === "protocol") {
663
+ resolved.protocol = resolveProtocolRecordCapture(value as ProtocolRecordCapture);
664
+ continue;
665
+ }
666
+ if (!["none", "metadata", "content", "raw"].includes(String(value))) {
667
+ throw new Error(`invalid capture level for ${kind}: ${String(value)}`);
668
+ }
669
+ resolved[kind] = value as RecordCaptureLevel;
670
+ }
671
+ return Object.freeze(resolved) as ConversationRecordCapturePolicy;
672
+ }
673
+
674
+ export function shouldCaptureProtocolMethod(
675
+ policy: ResolvedProtocolRecordCapturePolicy,
676
+ method: string | undefined,
677
+ ): boolean {
678
+ if (!method) return true;
679
+ if (policy.excludeMethods.includes(method)) return false;
680
+ return policy.includeMethods.length === 0 || policy.includeMethods.includes(method);
681
+ }
682
+
683
+ function resolveProtocolRecordCapture(
684
+ value: ProtocolRecordCapture,
685
+ ): ResolvedProtocolRecordCapturePolicy {
686
+ if (typeof value === "string") {
687
+ if (!["none", "metadata", "raw"].includes(value)) {
688
+ throw new Error(`invalid capture level for protocol: ${value}`);
689
+ }
690
+ return Object.freeze({
691
+ level: value as ProtocolRecordCaptureLevel,
692
+ includeMethods: Object.freeze([]),
693
+ excludeMethods: Object.freeze([]),
694
+ });
695
+ }
696
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
697
+ throw new Error("invalid protocol capture policy");
698
+ }
699
+ for (const key of Object.keys(value)) {
700
+ if (!["level", "includeMethods", "excludeMethods"].includes(key)) {
701
+ throw new Error(`unknown protocol capture option: ${key}`);
702
+ }
703
+ }
704
+ if (!["none", "metadata", "raw"].includes(String(value.level))) {
705
+ throw new Error(`invalid capture level for protocol: ${String(value.level)}`);
706
+ }
707
+ const includeMethods = normalizeProtocolMethods(value.includeMethods, "includeMethods");
708
+ const excludeMethods = normalizeProtocolMethods(value.excludeMethods, "excludeMethods");
709
+ if (includeMethods.length && excludeMethods.length) {
710
+ throw new Error("protocol capture cannot combine includeMethods and excludeMethods");
711
+ }
712
+ return Object.freeze({
713
+ level: value.level,
714
+ includeMethods,
715
+ excludeMethods,
716
+ });
717
+ }
718
+
719
+ function normalizeProtocolMethods(
720
+ value: readonly string[] | undefined,
721
+ field: string,
722
+ ): readonly string[] {
723
+ if (value === undefined) return Object.freeze([]);
724
+ if (!Array.isArray(value)) throw new Error(`protocol capture ${field} must be an array`);
725
+ const methods = value.map((method) => {
726
+ if (typeof method !== "string" || !method.trim()) {
727
+ throw new Error(`protocol capture ${field} contains a blank method`);
728
+ }
729
+ return method.trim();
730
+ });
731
+ if (new Set(methods).size !== methods.length) {
732
+ throw new Error(`protocol capture ${field} contains duplicate methods`);
733
+ }
734
+ return Object.freeze(methods);
735
+ }
736
+
737
+ /** Text projection for one record. Record boundaries remain separate search documents. */
738
+ export function searchableText(record: ConversationRecord): string {
739
+ switch (record.kind) {
740
+ case "message":
741
+ case "thinking":
742
+ return contentText(record.content);
743
+ case "tool_call":
744
+ return [record.name, jsonText(record.input), contentText(record.output)].filter(Boolean).join("\n");
745
+ case "permission":
746
+ return [jsonText(record.request), record.outcome].filter(Boolean).join("\n");
747
+ case "configuration":
748
+ return [record.operation, record.configId, jsonText(record.value), record.error].filter(Boolean).join("\n");
749
+ case "protocol":
750
+ return [record.method, jsonText(record.message)].filter(Boolean).join("\n");
751
+ case "native_action":
752
+ case "agent_action":
753
+ return [record.action, jsonText(record.input), jsonText(record.output), record.error].filter(Boolean).join("\n");
754
+ case "activity":
755
+ return [record.activityType, contentText(record.content), jsonText(record.data)].filter(Boolean).join("\n");
756
+ case "metering":
757
+ return [record.operationId, record.meteringRecordId, record.status].join("\n");
758
+ }
759
+ }
760
+
761
+ function contentText(content: PersistedContent | undefined): string {
762
+ if (typeof content === "string") return content;
763
+ if (!content) return "";
764
+ return content.map((block) => {
765
+ if (block.type === "text") return block.text;
766
+ if (block.type === "image") return block.alt ?? "";
767
+ if (block.type === "resource") return [block.title, block.text, block.uri].filter(Boolean).join("\n");
768
+ return jsonText(block.value);
769
+ }).filter(Boolean).join("\n");
770
+ }
771
+
772
+ function jsonText(value: PersistenceJsonValue | undefined): string {
773
+ return value === undefined ? "" : JSON.stringify(value);
774
+ }