@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
package/src/agent.ts ADDED
@@ -0,0 +1,1175 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import type * as schema from "@agentclientprotocol/sdk";
3
+ import {
4
+ createAgentConversationId,
5
+ type AgentConversationId,
6
+ type AgentSessionId,
7
+ } from "./agent-ids.ts";
8
+ import {
9
+ AgentAdapterRegistry,
10
+ type AgentAdapterRegistration,
11
+ } from "./agent-adapter-registry.ts";
12
+ import {
13
+ AgentConversation,
14
+ type AgentConversationConfig,
15
+ } from "./agent-session.ts";
16
+ import type { AgentMode } from "./controller.ts";
17
+ import type { OperationMeteringRecord } from "./metering/record.ts";
18
+ import type { MeteredOperationKind } from "./metering/record.ts";
19
+ import { MeteringEngine } from "./metering/engine.ts";
20
+ import { createModelsDevResolver } from "./metering/catalog/index.ts";
21
+ import type { AgentSessionMeteringState } from "./metering/state.ts";
22
+ import {
23
+ NoopAgentIdentityRuntime,
24
+ composeIdentityPrompt,
25
+ type AgentIdentityRuntime,
26
+ type IdentityConsistency,
27
+ } from "./identity.ts";
28
+ import {
29
+ IMPLICIT_USER_PARTICIPANT_ID,
30
+ PersistenceCapabilityError,
31
+ normalizeParticipantRef,
32
+ resolveConversationRecordCapture,
33
+ shouldCaptureProtocolMethod,
34
+ type AgentConversationSummary,
35
+ type ConversationListOptions,
36
+ type ConversationPage,
37
+ type ConversationRecord,
38
+ type ConversationRecordCaptureConfig,
39
+ type ConversationRecordCapturePolicy,
40
+ type MeteringRecordRetention,
41
+ type NewConversationRecord,
42
+ type ParticipantRef,
43
+ type PersistenceBackend,
44
+ type PersistenceExtension,
45
+ type PersistenceScope,
46
+ type RecordCaptureLevel,
47
+ } from "./persistence/backend.ts";
48
+ import { SqliteAgentPersistence } from "./persistence/sqlite-backend.ts";
49
+ import {
50
+ projectAgentAuditObservation,
51
+ resolveAgentAuditLogConfig,
52
+ AgentAuditRuntime,
53
+ type AgentAuditLogConfig,
54
+ type NormalizedAgentObservation,
55
+ type ResolvedAgentAuditLogConfig,
56
+ } from "./audit/index.ts";
57
+ import type {
58
+ AgentConversationOwnerLifecycle,
59
+ OwnedPromptCompleted,
60
+ OwnedPromptFailed,
61
+ OwnedPromptInput,
62
+ } from "./agent-conversation-owner.ts";
63
+ import {
64
+ resolveInternalInferenceConfig,
65
+ type InternalInferenceConfig,
66
+ } from "./internal-inference/config.ts";
67
+ import type {
68
+ InternalInferenceManager,
69
+ InternalInferenceStrategy,
70
+ } from "./internal-inference/contracts.ts";
71
+ import { DefaultInternalInferenceManager } from "./internal-inference/coordination/manager.ts";
72
+ import type { InternalInferenceSnapshot } from "./internal-inference/contracts.ts";
73
+ import { HarnessInternalInferenceRuntime } from "./internal-inference/runtime/harness-runtime.ts";
74
+ import {
75
+ ConversationCheckpointCoordinator,
76
+ ConversationCheckpointStrategy,
77
+ CONVERSATION_CHECKPOINT_STRATEGY_ID,
78
+ buildRecoverySeed,
79
+ isMissingProviderSessionError,
80
+ resolveConversationCheckpointingConfig,
81
+ type ConversationCheckpointingConfig,
82
+ type ConversationRecoveryProgress,
83
+ type ConversationRecoveryResult,
84
+ type ResolvedConversationCheckpointingConfig,
85
+ } from "./checkpointing/index.ts";
86
+
87
+ export type AgentPersistenceConfig =
88
+ | {
89
+ readonly kind: "sqlite";
90
+ readonly path: string;
91
+ readonly metadata?: string;
92
+ readonly busyTimeoutMs?: number;
93
+ readonly extensions?: readonly PersistenceExtension[];
94
+ readonly allowUnsafeWalVersion?: boolean;
95
+ }
96
+ | { readonly kind: "custom"; readonly backend: PersistenceBackend };
97
+
98
+ type OwnerControlledConversationKey =
99
+ | "adapter"
100
+ | "adapterId"
101
+ | "agentSessionId"
102
+ | "agentConversationId"
103
+ | "ownerAgentSessionId"
104
+ | "participants"
105
+ | "ownerLifecycle"
106
+ | "providerSession"
107
+ | "persistence"
108
+ | "transcriptPath"
109
+ | "transcriptDir"
110
+ | "sessions";
111
+
112
+ export type AgentConversationRuntimeDefaults = Omit<
113
+ AgentConversationConfig,
114
+ OwnerControlledConversationKey
115
+ >;
116
+
117
+ export interface AgentConfig {
118
+ readonly id?: AgentSessionId;
119
+ readonly persistence: AgentPersistenceConfig;
120
+ readonly adapters: Readonly<Record<string, import("./adapters.ts").Adapter>>
121
+ | readonly AgentAdapterRegistration[];
122
+ readonly defaultAdapterId?: string;
123
+ readonly identity?: AgentIdentityRuntime;
124
+ readonly identityConsistency?: IdentityConsistency;
125
+ readonly identityTimeoutMs?: number;
126
+ readonly capture?: ConversationRecordCaptureConfig;
127
+ readonly conversationDefaults?: AgentConversationRuntimeDefaults;
128
+ /** Bounded metering state is always persisted; this controls detailed local history. */
129
+ readonly meteringPersistence?: {
130
+ readonly meteringRecords?: MeteringRecordRetention;
131
+ };
132
+ readonly internalInference?: InternalInferenceConfig & {
133
+ readonly strategies?: readonly InternalInferenceStrategy[];
134
+ };
135
+ readonly checkpointing?: ConversationCheckpointingConfig;
136
+ readonly auditLog?: false | AgentAuditLogConfig;
137
+ }
138
+
139
+ export interface CreateAgentConversationConfig {
140
+ readonly id?: AgentConversationId;
141
+ readonly adapterId?: string;
142
+ readonly mode?: AgentMode;
143
+ readonly participants?: readonly ParticipantRef[];
144
+ readonly title?: string;
145
+ readonly metadata?: string;
146
+ readonly mcpServers?: schema.McpServer[];
147
+ readonly runtime?: AgentConversationRuntimeDefaults;
148
+ }
149
+
150
+ export interface OpenAgentConversationConfig {
151
+ readonly adapterId?: string;
152
+ readonly mode?: AgentMode;
153
+ readonly mcpServers?: schema.McpServer[];
154
+ readonly runtime?: AgentConversationRuntimeDefaults;
155
+ readonly onRecoveryProgress?: (event: ConversationRecoveryProgress) => void;
156
+ }
157
+
158
+ export interface OpenOwnedAgentConversationResult {
159
+ readonly conversation: AgentConversation;
160
+ readonly providerSession: "already_open" | "loaded" | "new" | "recovered";
161
+ readonly recovery?: ConversationRecoveryResult;
162
+ }
163
+
164
+ export interface AgentConversationManager {
165
+ create(config?: CreateAgentConversationConfig): Promise<AgentConversation>;
166
+ open(
167
+ id: AgentConversationId,
168
+ config?: OpenAgentConversationConfig,
169
+ ): Promise<OpenOwnedAgentConversationResult>;
170
+ get(id: AgentConversationId): Promise<AgentConversationSummary | null>;
171
+ list(options?: ConversationListOptions): Promise<ConversationPage>;
172
+ delete(id: AgentConversationId, deletedAt?: string): Promise<void>;
173
+ }
174
+
175
+ /** Durable owner of one agent identity, its adapters, identity runtime, and conversations. */
176
+ export class Agent {
177
+ readonly id: AgentSessionId;
178
+ readonly persistence: PersistenceBackend;
179
+ readonly identity: AgentIdentityRuntime;
180
+ readonly adapters: AgentAdapterRegistry;
181
+ readonly conversations: AgentConversationManager;
182
+ readonly internalInferences?: InternalInferenceManager;
183
+ readonly checkpointing?: ConversationCheckpointCoordinator;
184
+ readonly audit?: AgentAuditRuntime;
185
+
186
+ private readonly manager: DefaultAgentConversationManager;
187
+ private auditObservationTail: Promise<void> = Promise.resolve();
188
+ private auditObservationError: unknown;
189
+ private detachInternalInferenceAudit?: () => void;
190
+ private closed = false;
191
+
192
+ private constructor(
193
+ id: AgentSessionId,
194
+ persistence: PersistenceBackend,
195
+ identity: AgentIdentityRuntime,
196
+ adapters: AgentAdapterRegistry,
197
+ config: AgentConfig,
198
+ private readonly auditLog: ResolvedAgentAuditLogConfig | null,
199
+ audit: AgentAuditRuntime | undefined,
200
+ ) {
201
+ this.id = id;
202
+ this.persistence = persistence;
203
+ this.identity = identity;
204
+ this.adapters = adapters;
205
+ this.audit = audit;
206
+ const checkpointing = config.checkpointing
207
+ ? resolveConversationCheckpointingConfig(config.checkpointing)
208
+ : null;
209
+ this.manager = new DefaultAgentConversationManager(this, {
210
+ defaultAdapterId: config.defaultAdapterId,
211
+ identityConsistency: config.identityConsistency ?? "eventual",
212
+ identityTimeoutMs: config.identityTimeoutMs,
213
+ capture: resolveConversationRecordCapture(config.capture),
214
+ defaults: config.conversationDefaults ?? {},
215
+ meteringRecords: config.meteringPersistence?.meteringRecords ?? "all",
216
+ checkpointing,
217
+ auditLog,
218
+ auditIdentityUpdate: async (agentConversationId, records) => {
219
+ if (records.length === 0) return;
220
+ await this.recordAgentAuditObservation("identity", "updated", {
221
+ agentConversationId,
222
+ sourceRecordIds: records.map((record) => record.recordId),
223
+ }, `identity:${records.map((record) => record.recordId).join(":")}`);
224
+ },
225
+ });
226
+ this.conversations = this.manager;
227
+ if (checkpointing?.enabled) {
228
+ const messageCapture = resolveConversationRecordCapture(config.capture).message;
229
+ if (messageCapture !== "content" && messageCapture !== "raw") {
230
+ throw new Error("conversation checkpointing requires message capture at content or raw level");
231
+ }
232
+ }
233
+ if (config.internalInference || checkpointing?.enabled) {
234
+ const inferenceConfig = config.internalInference ?? {};
235
+ const settings = resolveInternalInferenceConfig(inferenceConfig);
236
+ if (!persistence.internalInferences) {
237
+ throw new Error("persistence backend does not support internal inference");
238
+ }
239
+ const runtime = settings.runtime ?? new HarnessInternalInferenceRuntime({
240
+ controllerConfig: (request) => ({
241
+ adapter: adapters.require(request.adapterId),
242
+ adapterId: request.adapterId,
243
+ ...(config.conversationDefaults?.launcher
244
+ ? { launcher: config.conversationDefaults.launcher }
245
+ : {}),
246
+ ...(config.conversationDefaults?.execPrefix
247
+ ? { execPrefix: config.conversationDefaults.execPrefix }
248
+ : {}),
249
+ ...(config.conversationDefaults?.env ? { env: config.conversationDefaults.env } : {}),
250
+ ...(config.conversationDefaults?.cwd ? { cwd: config.conversationDefaults.cwd } : {}),
251
+ ...(config.conversationDefaults?.clientInfo
252
+ ? { clientInfo: config.conversationDefaults.clientInfo }
253
+ : {}),
254
+ ...(config.conversationDefaults?.clientCapabilities
255
+ ? { clientCapabilities: config.conversationDefaults.clientCapabilities }
256
+ : {}),
257
+ ...(config.conversationDefaults?.logger
258
+ ? { logger: config.conversationDefaults.logger }
259
+ : {}),
260
+ ...(config.conversationDefaults?.wire ? { wire: config.conversationDefaults.wire } : {}),
261
+ }),
262
+ });
263
+ const strategies = [...(inferenceConfig.strategies ?? [])];
264
+ if (checkpointing?.enabled) {
265
+ if (strategies.some((strategy) =>
266
+ strategy.purpose === "conversation_checkpoint"
267
+ && strategy.strategyId === CONVERSATION_CHECKPOINT_STRATEGY_ID
268
+ && strategy.version === 1)) {
269
+ throw new Error("the built-in conversation checkpoint strategy is already registered");
270
+ }
271
+ strategies.push(new ConversationCheckpointStrategy());
272
+ }
273
+ this.internalInferences = new DefaultInternalInferenceManager({
274
+ agentSessionId: id,
275
+ repository: persistence.internalInferences,
276
+ persistence,
277
+ runtime,
278
+ settings,
279
+ strategies,
280
+ meteringRecords: config.meteringPersistence?.meteringRecords ?? "all",
281
+ beginMetering: async (attempt, session) => {
282
+ return await this.manager.beginInternalInferenceMetering(attempt, session);
283
+ },
284
+ resolveAdapterId: async (requestedAdapterId, agentConversationId) => {
285
+ if (requestedAdapterId) {
286
+ adapters.require(requestedAdapterId);
287
+ return requestedAdapterId;
288
+ }
289
+ if (settings.adapter !== "same") {
290
+ adapters.require(settings.adapter);
291
+ return settings.adapter;
292
+ }
293
+ if (agentConversationId) {
294
+ const active = await persistence.providerSessions.active(agentConversationId);
295
+ if (active) {
296
+ adapters.require(active.adapterId);
297
+ return active.adapterId;
298
+ }
299
+ }
300
+ const fallback = config.defaultAdapterId ?? adapters.list()[0]?.id;
301
+ if (!fallback) throw new Error("internal inference could not resolve an adapter");
302
+ adapters.require(fallback);
303
+ return fallback;
304
+ },
305
+ });
306
+ if (auditLog) {
307
+ this.detachInternalInferenceAudit = this.internalInferences.subscribe((event) => {
308
+ this.queueAgentAuditObservation(
309
+ "internal_inference",
310
+ event.snapshot.stage,
311
+ event.snapshot as unknown as import("./persistence/backend.ts").PersistenceJsonValue,
312
+ `internal-inference:${event.inferenceId}:${event.sequence}`,
313
+ event.inferenceId,
314
+ );
315
+ });
316
+ }
317
+ if (checkpointing?.enabled) {
318
+ this.checkpointing = new ConversationCheckpointCoordinator(
319
+ persistence,
320
+ this.internalInferences,
321
+ checkpointing,
322
+ );
323
+ }
324
+ }
325
+ }
326
+
327
+ static async open(config: AgentConfig): Promise<Agent> {
328
+ const auditLog = config.auditLog && resolveAgentAuditLogConfig(config.auditLog);
329
+ if (auditLog && config.persistence.kind === "custom") {
330
+ throw new PersistenceCapabilityError("auditOutbox");
331
+ }
332
+ const registrations = Array.isArray(config.adapters)
333
+ ? config.adapters
334
+ : Object.entries(config.adapters).map(([id, adapter]) => ({ id, adapter }));
335
+ const adapters = new AgentAdapterRegistry(registrations);
336
+ if (adapters.list().length === 0) throw new Error("Agent requires at least one adapter");
337
+ if (config.defaultAdapterId) adapters.require(config.defaultAdapterId);
338
+
339
+ let persistence: PersistenceBackend;
340
+ let id: AgentSessionId;
341
+ if (config.persistence.kind === "custom") {
342
+ persistence = config.persistence.backend;
343
+ id = config.id ?? persistence.identityRecord.agentSessionId;
344
+ if (persistence.identityRecord.agentSessionId !== id) {
345
+ throw new Error(
346
+ `custom persistence belongs to ${persistence.identityRecord.agentSessionId}, not ${id}`,
347
+ );
348
+ }
349
+ } else {
350
+ persistence = await SqliteAgentPersistence.open({
351
+ path: config.persistence.path,
352
+ ...(config.id ? { agentSessionId: config.id } : {}),
353
+ ...(config.persistence.metadata !== undefined ? { metadata: config.persistence.metadata } : {}),
354
+ ...(config.persistence.busyTimeoutMs !== undefined
355
+ ? { busyTimeoutMs: config.persistence.busyTimeoutMs }
356
+ : {}),
357
+ ...(config.persistence.extensions ? { extensions: config.persistence.extensions } : {}),
358
+ ...(config.persistence.allowUnsafeWalVersion !== undefined
359
+ ? { allowUnsafeWalVersion: config.persistence.allowUnsafeWalVersion }
360
+ : {}),
361
+ });
362
+ id = persistence.identityRecord.agentSessionId;
363
+ }
364
+ let audit: AgentAuditRuntime | undefined;
365
+ try {
366
+ if (auditLog) {
367
+ if (!persistence.auditOutbox) throw new PersistenceCapabilityError("auditOutbox");
368
+ const state = await persistence.auditOutbox.state();
369
+ const initialized = await persistence.auditOutbox.initialize(
370
+ state?.auditLogId ?? `audlog-${randomUUID()}`,
371
+ auditLog.captureFingerprint,
372
+ );
373
+ audit = await AgentAuditRuntime.open({
374
+ persistence,
375
+ agentSessionId: id,
376
+ config: auditLog,
377
+ auditState: initialized,
378
+ });
379
+ }
380
+ const agent = new Agent(
381
+ id,
382
+ persistence,
383
+ config.identity ?? new NoopAgentIdentityRuntime(),
384
+ adapters,
385
+ config,
386
+ auditLog || null,
387
+ audit,
388
+ );
389
+ await agent.recordAgentAuditObservation("agent_lifecycle", "opened");
390
+ return agent;
391
+ } catch (error) {
392
+ await audit?.close().catch(() => undefined);
393
+ await persistence.close().catch(() => undefined);
394
+ throw error;
395
+ }
396
+ }
397
+
398
+ static async create(config: AgentConfig): Promise<Agent> {
399
+ return await Agent.open(config);
400
+ }
401
+
402
+ async close(): Promise<void> {
403
+ if (this.closed) return;
404
+ this.closed = true;
405
+ let shutdownError: unknown;
406
+ try {
407
+ this.checkpointing?.close();
408
+ await (this.internalInferences as DefaultInternalInferenceManager | undefined)?.close();
409
+ this.detachInternalInferenceAudit?.();
410
+ this.detachInternalInferenceAudit = undefined;
411
+ await this.auditObservationTail;
412
+ const observationError = this.auditObservationError;
413
+ await this.manager.stopAll();
414
+ await this.recordAgentAuditObservation("agent_lifecycle", "closed");
415
+ if (observationError !== undefined) throw observationError;
416
+ } catch (error) {
417
+ shutdownError = error;
418
+ }
419
+ const cleanupErrors: unknown[] = [];
420
+ try {
421
+ await this.audit?.close();
422
+ } catch (error) {
423
+ cleanupErrors.push(error);
424
+ }
425
+ try {
426
+ await this.persistence.close();
427
+ } catch (error) {
428
+ cleanupErrors.push(error);
429
+ }
430
+ if (shutdownError !== undefined) cleanupErrors.unshift(shutdownError);
431
+ if (cleanupErrors.length === 1) throw cleanupErrors[0];
432
+ if (cleanupErrors.length > 1) throw new AggregateError(cleanupErrors, "agent shutdown failed");
433
+ }
434
+
435
+ private async recordAgentAuditObservation(
436
+ kind: "agent_lifecycle" | "identity" | "internal_inference",
437
+ state: string,
438
+ payload?: import("./persistence/backend.ts").PersistenceJsonValue,
439
+ sourceObservationId = `${kind}-${randomUUID()}`,
440
+ operationId?: string,
441
+ ): Promise<void> {
442
+ const auditLog = this.auditLog;
443
+ if (!auditLog) return;
444
+ await enqueueAuditObservation(this.persistence, {
445
+ scope: "agent",
446
+ sourceObservationId,
447
+ agentSessionId: this.id,
448
+ kind,
449
+ occurredAt: new Date().toISOString(),
450
+ state,
451
+ ...(operationId ? { operationId } : {}),
452
+ ...(payload !== undefined ? { payload } : {}),
453
+ }, auditLog);
454
+ this.audit?.notifyPending();
455
+ }
456
+
457
+ private queueAgentAuditObservation(
458
+ kind: "agent_lifecycle" | "identity" | "internal_inference",
459
+ state: string,
460
+ payload?: import("./persistence/backend.ts").PersistenceJsonValue,
461
+ sourceObservationId?: string,
462
+ operationId?: string,
463
+ ): void {
464
+ const write = this.auditObservationTail.then(() => this.recordAgentAuditObservation(
465
+ kind,
466
+ state,
467
+ payload,
468
+ sourceObservationId,
469
+ operationId,
470
+ ));
471
+ this.auditObservationTail = write.catch((error) => {
472
+ if (this.auditObservationError === undefined) this.auditObservationError = error;
473
+ });
474
+ }
475
+ }
476
+
477
+ interface ManagerSettings {
478
+ readonly defaultAdapterId?: string;
479
+ readonly identityConsistency: IdentityConsistency;
480
+ readonly identityTimeoutMs?: number;
481
+ readonly capture: ConversationRecordCapturePolicy;
482
+ readonly defaults: AgentConversationRuntimeDefaults;
483
+ readonly meteringRecords: MeteringRecordRetention;
484
+ readonly checkpointing: ResolvedConversationCheckpointingConfig | null;
485
+ readonly auditLog: ResolvedAgentAuditLogConfig | null;
486
+ readonly auditIdentityUpdate: (
487
+ agentConversationId: AgentConversationId,
488
+ records: readonly ConversationRecord[],
489
+ ) => Promise<void>;
490
+ }
491
+
492
+ class DefaultAgentConversationManager implements AgentConversationManager {
493
+ private readonly live = new Map<AgentConversationId, AgentConversation>();
494
+ private readonly openings = new Map<AgentConversationId, Promise<OpenOwnedAgentConversationResult>>();
495
+ private readonly meteringSetupLocks = new Map<AgentConversationId, Promise<void>>();
496
+ private readonly detachedMeteringBarriers = new Map<AgentConversationId, Promise<void>>();
497
+ private agentMeteringBarrier: Promise<void> | undefined;
498
+
499
+ constructor(private readonly agent: Agent, private readonly settings: ManagerSettings) {}
500
+
501
+ async create(config: CreateAgentConversationConfig = {}): Promise<AgentConversation> {
502
+ const id = config.id ?? createAgentConversationId();
503
+ const participants = normalizeParticipants(config.participants);
504
+ await this.agent.persistence.conversations.create({
505
+ agentSessionId: this.agent.id,
506
+ agentConversationId: id,
507
+ participants,
508
+ ...(config.title !== undefined ? { title: config.title } : {}),
509
+ ...(config.metadata !== undefined ? { metadata: config.metadata } : {}),
510
+ });
511
+ return await this.start(id, participants, {
512
+ ...config,
513
+ providerSession: "new",
514
+ });
515
+ }
516
+
517
+ async open(
518
+ id: AgentConversationId,
519
+ config: OpenAgentConversationConfig = {},
520
+ ): Promise<OpenOwnedAgentConversationResult> {
521
+ const existing = this.live.get(id);
522
+ if (existing && existing.state.phase !== "stopped") {
523
+ return Object.freeze({ conversation: existing, providerSession: "already_open" });
524
+ }
525
+ const pending = this.openings.get(id);
526
+ if (pending) return await pending;
527
+ const opening = this.openOnce(id, config);
528
+ this.openings.set(id, opening);
529
+ try {
530
+ return await opening;
531
+ } finally {
532
+ if (this.openings.get(id) === opening) this.openings.delete(id);
533
+ }
534
+ }
535
+
536
+ private async openOnce(
537
+ id: AgentConversationId,
538
+ config: OpenAgentConversationConfig,
539
+ ): Promise<OpenOwnedAgentConversationResult> {
540
+ const summary = await this.agent.persistence.conversations.get(id);
541
+ if (!summary || summary.deletedAt) throw new Error(`unknown active conversation: ${id}`);
542
+ const active = await this.agent.persistence.providerSessions.active(id);
543
+ if (active && config.adapterId && config.adapterId !== active.adapterId) {
544
+ throw new Error(
545
+ `conversation ${id} is active on ${active.adapterId}; use a conversation switch instead of loading it with ${config.adapterId}`,
546
+ );
547
+ }
548
+ const startConfig = {
549
+ ...config,
550
+ runtime: {
551
+ ...(summary.title ? { title: summary.title } : {}),
552
+ ...config.runtime,
553
+ },
554
+ adapterId: config.adapterId ?? active?.adapterId,
555
+ };
556
+ try {
557
+ const conversation = await this.start(id, summary.participants, {
558
+ ...startConfig,
559
+ providerSession: active ? "load" : "new",
560
+ internalSessionId: active?.internalSessionId,
561
+ });
562
+ return Object.freeze({
563
+ conversation,
564
+ providerSession: active ? "loaded" : "new",
565
+ });
566
+ } catch (error) {
567
+ const recovery = this.settings.checkpointing?.recovery;
568
+ if (
569
+ !active
570
+ || recovery?.onLoadFailure !== "recover"
571
+ || !isMissingProviderSessionError(error, recovery.isMissingProviderSession)
572
+ ) throw error;
573
+ config.onRecoveryProgress?.({ stage: "load_failed" });
574
+ config.onRecoveryProgress?.({ stage: "loading_checkpoint" });
575
+ const checkpoint = await this.agent.persistence.recoveryCheckpoints?.latest(id);
576
+ if (!checkpoint) throw error;
577
+ config.onRecoveryProgress?.({ stage: "loading_checkpoint", checkpointId: checkpoint.checkpointId });
578
+ const seed = await buildRecoverySeed(
579
+ this.agent.persistence.messages,
580
+ id,
581
+ checkpoint,
582
+ summary.latestSequence,
583
+ recovery,
584
+ );
585
+ config.onRecoveryProgress?.({ stage: "creating_session", checkpointId: checkpoint.checkpointId });
586
+ const conversation = await this.start(id, summary.participants, {
587
+ ...startConfig,
588
+ providerSession: "new",
589
+ deferProviderSessionPersistence: true,
590
+ });
591
+ try {
592
+ config.onRecoveryProgress?.({ stage: "seeding", checkpointId: checkpoint.checkpointId });
593
+ await conversation.seedRecoveryContext(seed.prompt);
594
+ await this.persistProviderSession(conversation, id, conversation.adapterId, {
595
+ transitionId: `recovery-${randomUUID()}`,
596
+ metadata: JSON.stringify({
597
+ recoveryCheckpointId: checkpoint.checkpointId,
598
+ previousInternalSessionId: active.internalSessionId,
599
+ recoveredThroughSequence: seed.recoveredThroughSequence,
600
+ }),
601
+ });
602
+ } catch (recoveryError) {
603
+ this.live.delete(id);
604
+ await conversation.stop().catch(() => undefined);
605
+ throw recoveryError;
606
+ }
607
+ const result: ConversationRecoveryResult = Object.freeze({
608
+ checkpointId: checkpoint.checkpointId,
609
+ coveredSequence: checkpoint.coveredSequence,
610
+ recoveredThroughSequence: seed.recoveredThroughSequence,
611
+ previousInternalSessionId: active.internalSessionId,
612
+ newInternalSessionId: conversation.internalSessionId!,
613
+ });
614
+ config.onRecoveryProgress?.({ stage: "completed", checkpointId: checkpoint.checkpointId });
615
+ return Object.freeze({ conversation, providerSession: "recovered", recovery: result });
616
+ }
617
+ }
618
+
619
+ async get(id: AgentConversationId): Promise<AgentConversationSummary | null> {
620
+ return await this.agent.persistence.conversations.get(id);
621
+ }
622
+
623
+ async list(options?: ConversationListOptions): Promise<ConversationPage> {
624
+ return await this.agent.persistence.conversations.list(options);
625
+ }
626
+
627
+ async delete(id: AgentConversationId, deletedAt?: string): Promise<void> {
628
+ const live = this.live.get(id);
629
+ if (live) await live.stop();
630
+ this.live.delete(id);
631
+ await this.agent.persistence.conversations.delete(id, deletedAt);
632
+ }
633
+
634
+ async stopAll(): Promise<void> {
635
+ await Promise.allSettled([...this.openings.values()]);
636
+ const conversations = [...this.live.values()];
637
+ this.live.clear();
638
+ await Promise.allSettled(conversations.map((conversation) => conversation.stop()));
639
+ }
640
+
641
+ async beginInternalInferenceMetering(
642
+ attempt: InternalInferenceSnapshot,
643
+ session: { readonly internalSessionId: string; readonly model: string | null },
644
+ ): Promise<import("./internal-inference/contracts.ts").InternalInferenceMeteringOperation | null> {
645
+ const conversationId = attempt.agentConversationId;
646
+ const releaseSetup = conversationId
647
+ ? await this.acquireMeteringSetupLock(conversationId)
648
+ : () => {};
649
+ let barrier: Promise<void> | undefined;
650
+ let releaseBarrier = () => {};
651
+ try {
652
+ const conversation = conversationId ? this.live.get(conversationId) : undefined;
653
+ if (conversation && conversation.state.phase !== "stopped") {
654
+ const operation = await conversation.beginDetachedMetering({
655
+ operationId: attempt.id,
656
+ operationKind: internalInferenceMeteringKind(attempt.purpose),
657
+ internalSessionId: session.internalSessionId,
658
+ model: session.model,
659
+ });
660
+ let closed = false;
661
+ releaseSetup();
662
+ return {
663
+ close: async ({ outcome, result, error }) => {
664
+ if (closed) throw new Error(`internal inference metering already closed: ${attempt.id}`);
665
+ closed = true;
666
+ return await conversation.closeDetachedMetering(operation, {
667
+ outcome,
668
+ usage: result?.usage ?? null,
669
+ ...(error ? { usageFailureReason: String(error) } : {}),
670
+ });
671
+ },
672
+ settled() {},
673
+ };
674
+ }
675
+
676
+ const previous = conversationId
677
+ ? this.detachedMeteringBarriers.get(conversationId) ?? Promise.resolve()
678
+ : this.agentMeteringBarrier ?? Promise.resolve();
679
+ const ownBarrier = new Promise<void>((resolve) => { releaseBarrier = resolve; });
680
+ barrier = previous.then(() => ownBarrier);
681
+ if (conversationId) this.detachedMeteringBarriers.set(conversationId, barrier);
682
+ else this.agentMeteringBarrier = barrier;
683
+ releaseSetup();
684
+ // Detached operations for one closed conversation must restore and commit in order.
685
+ // Otherwise two workers can derive the same next operation count from one snapshot.
686
+ await previous;
687
+ const persisted = conversationId
688
+ ? await this.agent.persistence.metering.state(conversationId)
689
+ : await this.agent.persistence.metering.agentState(this.agent.id);
690
+ const meteringConfig = this.settings.defaults.metering;
691
+ const engine = new MeteringEngine({
692
+ agentSessionId: this.agent.id,
693
+ adapterId: attempt.adapterId,
694
+ enforcement: meteringConfig?.enforcement ?? "best_effort",
695
+ pricing: meteringConfig?.pricing ?? createModelsDevResolver(),
696
+ ...(persisted ? { initialState: persisted.state } : {}),
697
+ createdActiveThread: false,
698
+ ...(meteringConfig?.counterInterpretation
699
+ ? { counterInterpretation: meteringConfig.counterInterpretation }
700
+ : {}),
701
+ ...(meteringConfig?.inferenceSource
702
+ ? { inferenceSource: meteringConfig.inferenceSource }
703
+ : {}),
704
+ });
705
+ const operation = await engine.openDetached({
706
+ operationId: attempt.id,
707
+ operationKind: internalInferenceMeteringKind(attempt.purpose),
708
+ internalSessionId: session.internalSessionId,
709
+ providerId: null,
710
+ model: session.model,
711
+ });
712
+ let closed = false;
713
+ let settled = false;
714
+ return {
715
+ close: async ({ outcome, result, error }) => {
716
+ if (closed) throw new Error(`internal inference metering already closed: ${attempt.id}`);
717
+ closed = true;
718
+ return await engine.closeDetached(operation, {
719
+ outcome,
720
+ reportedCumulative: result?.usage ?? null,
721
+ ...(error ? { usageFailureReason: String(error) } : {}),
722
+ contextAfter: null,
723
+ providerCostAfter: null,
724
+ });
725
+ },
726
+ settled: () => {
727
+ if (settled) return;
728
+ settled = true;
729
+ if (conversationId && this.detachedMeteringBarriers.get(conversationId) === barrier) {
730
+ this.detachedMeteringBarriers.delete(conversationId);
731
+ } else if (!conversationId && this.agentMeteringBarrier === barrier) {
732
+ this.agentMeteringBarrier = undefined;
733
+ }
734
+ releaseBarrier();
735
+ },
736
+ };
737
+ } catch (error) {
738
+ releaseSetup();
739
+ if (barrier && conversationId && this.detachedMeteringBarriers.get(conversationId) === barrier) {
740
+ this.detachedMeteringBarriers.delete(conversationId);
741
+ } else if (barrier && !conversationId && this.agentMeteringBarrier === barrier) {
742
+ this.agentMeteringBarrier = undefined;
743
+ }
744
+ releaseBarrier();
745
+ throw error;
746
+ }
747
+ }
748
+
749
+ private async start(
750
+ id: AgentConversationId,
751
+ participants: readonly ParticipantRef[],
752
+ config: (CreateAgentConversationConfig | OpenAgentConversationConfig) & {
753
+ readonly providerSession: "new" | "load";
754
+ readonly internalSessionId?: string;
755
+ readonly deferProviderSessionPersistence?: boolean;
756
+ },
757
+ ): Promise<AgentConversation> {
758
+ const releaseSetup = await this.acquireMeteringSetupLock(id);
759
+ let conversation: AgentConversation | undefined;
760
+ try {
761
+ const adapterId = this.resolveAdapterId(config.adapterId);
762
+ const adapter = this.agent.adapters.require(adapterId);
763
+ const runtime = { ...this.settings.defaults, ...config.runtime };
764
+ await this.detachedMeteringBarriers.get(id);
765
+ const persistedMetering = await this.agent.persistence.metering.state(id);
766
+ const lifecycle = new PersistedConversationLifecycle(
767
+ this.agent,
768
+ id,
769
+ participants,
770
+ this.settings,
771
+ );
772
+ conversation = await AgentConversation.create({
773
+ ...runtime,
774
+ ...(persistedMetering
775
+ ? { metering: { ...runtime.metering, initialState: persistedMetering.state } }
776
+ : {}),
777
+ ...("title" in config && config.title !== undefined ? { title: config.title } : {}),
778
+ adapter,
779
+ adapterId,
780
+ agentSessionId: this.agent.id,
781
+ ownerAgentSessionId: this.agent.id,
782
+ agentConversationId: id,
783
+ participants,
784
+ ownerLifecycle: lifecycle,
785
+ mode: config.mode ?? runtime.mode,
786
+ ...(config.mcpServers ? { mcpServers: [...config.mcpServers] } : {}),
787
+ providerSession: config.providerSession === "load"
788
+ ? { kind: "load", internalSessionId: config.internalSessionId!, onFailure: "error" }
789
+ : { kind: "new" },
790
+ persistence: false,
791
+ });
792
+ this.live.set(id, conversation);
793
+ conversation.subscribe((notification) => {
794
+ if (notification.event.kind === "state_changed" && notification.event.state.phase === "stopped") {
795
+ if (this.live.get(id) === conversation) this.live.delete(id);
796
+ }
797
+ });
798
+ if (conversation.internalSessionId && !config.deferProviderSessionPersistence) {
799
+ await this.persistProviderSession(conversation, id, adapterId);
800
+ }
801
+ return conversation;
802
+ } catch (error) {
803
+ this.live.delete(id);
804
+ await conversation?.stop().catch(() => undefined);
805
+ throw error;
806
+ } finally {
807
+ releaseSetup();
808
+ }
809
+ }
810
+
811
+ private async acquireMeteringSetupLock(id: AgentConversationId): Promise<() => void> {
812
+ const previous = this.meteringSetupLocks.get(id) ?? Promise.resolve();
813
+ let releaseGate!: () => void;
814
+ const gate = new Promise<void>((resolve) => { releaseGate = resolve; });
815
+ const current = previous.then(() => gate);
816
+ this.meteringSetupLocks.set(id, current);
817
+ await previous;
818
+ let released = false;
819
+ return () => {
820
+ if (released) return;
821
+ released = true;
822
+ if (this.meteringSetupLocks.get(id) === current) this.meteringSetupLocks.delete(id);
823
+ releaseGate();
824
+ };
825
+ }
826
+
827
+ private resolveAdapterId(requested?: string): string {
828
+ if (requested) return requested;
829
+ if (this.settings.defaultAdapterId) return this.settings.defaultAdapterId;
830
+ const registrations = this.agent.adapters.list();
831
+ if (registrations.length === 1) return registrations[0]!.id;
832
+ throw new Error("adapterId is required when an Agent has no unique default adapter");
833
+ }
834
+
835
+ private async persistProviderSession(
836
+ conversation: AgentConversation,
837
+ id: AgentConversationId,
838
+ adapterId: string,
839
+ extra: { readonly transitionId?: string; readonly metadata?: string } = {},
840
+ ): Promise<void> {
841
+ if (!conversation.internalSessionId) throw new Error("provider session has no internal session id");
842
+ await this.agent.persistence.providerSessions.append({
843
+ providerSessionRecordId: `provider-${randomUUID()}`,
844
+ agentConversationId: id,
845
+ internalSessionId: conversation.internalSessionId,
846
+ adapterId,
847
+ mode: conversation.mode,
848
+ ...(conversation.model ? { model: conversation.model } : {}),
849
+ activatedAt: new Date().toISOString(),
850
+ ...extra,
851
+ });
852
+ }
853
+ }
854
+
855
+ class PersistedConversationLifecycle implements AgentConversationOwnerLifecycle {
856
+ constructor(
857
+ private readonly agent: Agent,
858
+ private readonly conversationId: AgentConversationId,
859
+ private readonly initialParticipants: readonly ParticipantRef[],
860
+ private readonly settings: ManagerSettings,
861
+ ) {}
862
+
863
+ async beforePrompt(input: OwnedPromptInput) {
864
+ const participant = await this.resolveParticipant(input.participantId);
865
+ const identity = await this.agent.identity.load({
866
+ agentSessionId: this.agent.id,
867
+ agentConversationId: this.conversationId,
868
+ participant,
869
+ prompt: input.text,
870
+ consistency: this.settings.identityConsistency,
871
+ ...(this.settings.identityTimeoutMs !== undefined
872
+ ? { timeoutMs: this.settings.identityTimeoutMs }
873
+ : {}),
874
+ });
875
+ const records = await this.appendMessages([{
876
+ recordId: `${input.operationId}:user`,
877
+ agentSessionId: this.agent.id,
878
+ agentConversationId: this.conversationId,
879
+ kind: "message",
880
+ timestamp: new Date().toISOString(),
881
+ role: "user",
882
+ participantId: participant.id,
883
+ content: input.text,
884
+ status: "completed",
885
+ metadata: JSON.stringify({ operationId: input.operationId }),
886
+ }]);
887
+ await this.updateIdentity(records);
888
+ return Object.freeze({
889
+ providerText: composeIdentityPrompt(input.text, identity),
890
+ participant,
891
+ });
892
+ }
893
+
894
+ async afterPrompt(input: OwnedPromptCompleted): Promise<void> {
895
+ const timestamp = new Date().toISOString();
896
+ const status = input.result.status === "error" ? "failed" : input.result.status;
897
+ const records = input.result.messages.map((message, index): NewConversationRecord => ({
898
+ recordId: `${input.operationId}:assistant:${index + 1}`,
899
+ agentSessionId: this.agent.id,
900
+ agentConversationId: this.conversationId,
901
+ kind: "message",
902
+ timestamp,
903
+ role: "assistant",
904
+ content: message.text,
905
+ status,
906
+ metadata: JSON.stringify({
907
+ operationId: input.operationId,
908
+ ...(message.messageId ? { providerMessageId: message.messageId } : {}),
909
+ }),
910
+ }));
911
+ await this.updateIdentity(await this.appendMessages(records));
912
+ if (status === "completed") {
913
+ await this.agent.checkpointing?.afterSuccessfulResponse(this.conversationId);
914
+ }
915
+ }
916
+
917
+ async promptFailed(input: OwnedPromptFailed): Promise<void> {
918
+ const timestamp = new Date().toISOString();
919
+ const records = input.messages.map((message, index): NewConversationRecord => ({
920
+ recordId: `${input.operationId}:assistant:${index + 1}`,
921
+ agentSessionId: this.agent.id,
922
+ agentConversationId: this.conversationId,
923
+ kind: "message",
924
+ timestamp,
925
+ role: "assistant",
926
+ content: message.text,
927
+ status: "failed",
928
+ metadata: JSON.stringify({
929
+ operationId: input.operationId,
930
+ ...(message.messageId ? { providerMessageId: message.messageId } : {}),
931
+ }),
932
+ }));
933
+ await this.updateIdentity(await this.appendMessages(records));
934
+ }
935
+
936
+ resolveAdapter(adapterId: string) {
937
+ return this.agent.adapters.require(adapterId);
938
+ }
939
+
940
+ async transitionActivated(input: {
941
+ readonly transitionId: string;
942
+ readonly agentConversationId: AgentConversationId;
943
+ readonly internalSessionId: string;
944
+ readonly adapterId: string;
945
+ readonly mode: AgentMode;
946
+ readonly model?: string;
947
+ readonly activatedAt: string;
948
+ }): Promise<void> {
949
+ await this.agent.persistence.providerSessions.append({
950
+ providerSessionRecordId: `provider-${randomUUID()}`,
951
+ agentConversationId: input.agentConversationId,
952
+ internalSessionId: input.internalSessionId,
953
+ adapterId: input.adapterId,
954
+ mode: input.mode,
955
+ ...(input.model ? { model: input.model } : {}),
956
+ activatedAt: input.activatedAt,
957
+ transitionId: input.transitionId,
958
+ });
959
+ }
960
+
961
+ async record(record: NewConversationRecord): Promise<void> {
962
+ await this.updateIdentity(await this.persistObservations([record]));
963
+ }
964
+
965
+ async meteringRecorded(record: OperationMeteringRecord): Promise<void> {
966
+ const level = this.settings.capture.metering;
967
+ let reference: ConversationRecord | undefined;
968
+ await this.agent.persistence.transaction(async (persistence) => {
969
+ await persistence.metering.commit({
970
+ agentConversationId: this.conversationId,
971
+ record,
972
+ meteringRecords: this.settings.meteringRecords,
973
+ });
974
+ const timelineRecord: NewConversationRecord = {
975
+ recordId: `${record.operationId}:metering`,
976
+ agentSessionId: this.agent.id,
977
+ agentConversationId: this.conversationId,
978
+ kind: "metering",
979
+ timestamp: new Date(record.completedAt).toISOString(),
980
+ operationId: record.operationId,
981
+ meteringRecordId: record.operationId,
982
+ status: record.usage.status === "metered" ? "available" : "unavailable",
983
+ metadata: JSON.stringify({ operationId: record.operationId }),
984
+ };
985
+ if (level !== "none") {
986
+ reference = await persistence.records.append(captureRuntimeRecord(timelineRecord, level));
987
+ }
988
+ if (this.settings.auditLog) {
989
+ await enqueueAuditObservation(persistence, {
990
+ scope: "conversation",
991
+ sourceObservationId: timelineRecord.recordId,
992
+ operationId: record.operationId,
993
+ record: timelineRecord,
994
+ meteringRecord: record,
995
+ }, this.settings.auditLog);
996
+ }
997
+ });
998
+ if (this.settings.auditLog) this.agent.audit?.notifyPending();
999
+ if (reference) await this.updateIdentity([reference]);
1000
+ }
1001
+
1002
+ async meteringStateChanged(state: AgentSessionMeteringState): Promise<void> {
1003
+ await this.agent.persistence.metering.saveState(this.conversationId, state);
1004
+ }
1005
+
1006
+ private async resolveParticipant(participantId?: string): Promise<ParticipantRef> {
1007
+ const id = participantId
1008
+ ?? (this.initialParticipants.length === 1
1009
+ ? this.initialParticipants[0]!.id
1010
+ : IMPLICIT_USER_PARTICIPANT_ID);
1011
+ const existing = (await this.agent.persistence.conversations.get(this.conversationId))
1012
+ ?.participants.find((participant) => participant.id === id);
1013
+ if (existing) return existing;
1014
+ return await this.agent.persistence.conversations.ensureParticipant(this.conversationId, {
1015
+ id,
1016
+ kind: "user",
1017
+ });
1018
+ }
1019
+
1020
+ private async appendMessages(
1021
+ records: readonly NewConversationRecord[],
1022
+ ): Promise<readonly ConversationRecord[]> {
1023
+ return await this.persistObservations(records);
1024
+ }
1025
+
1026
+ private async persistObservations(
1027
+ records: readonly NewConversationRecord[],
1028
+ ): Promise<readonly ConversationRecord[]> {
1029
+ if (records.length === 0) return Object.freeze([]);
1030
+ if (!this.settings.auditLog && records.every((record) => {
1031
+ if (record.kind !== "protocol") return this.settings.capture[record.kind] === "none";
1032
+ return this.settings.capture.protocol.level === "none"
1033
+ || !shouldCaptureProtocolMethod(this.settings.capture.protocol, record.method);
1034
+ })) return Object.freeze([]);
1035
+ const persisted: ConversationRecord[] = [];
1036
+ await this.agent.persistence.transaction(async (persistence) => {
1037
+ for (const record of records) {
1038
+ const level = record.kind === "protocol"
1039
+ ? this.settings.capture.protocol.level
1040
+ : this.settings.capture[record.kind];
1041
+ const canonicalAccepted = level !== "none" && (
1042
+ record.kind !== "protocol"
1043
+ || shouldCaptureProtocolMethod(this.settings.capture.protocol, record.method)
1044
+ );
1045
+ if (canonicalAccepted) {
1046
+ persisted.push(await persistence.records.append(captureRuntimeRecord(record, level)));
1047
+ }
1048
+ if (this.settings.auditLog) {
1049
+ await enqueueAuditObservation(persistence, {
1050
+ scope: "conversation",
1051
+ sourceObservationId: record.recordId,
1052
+ operationId: operationIdFromMetadata(record.metadata),
1053
+ record,
1054
+ }, this.settings.auditLog);
1055
+ }
1056
+ }
1057
+ });
1058
+ if (this.settings.auditLog) this.agent.audit?.notifyPending();
1059
+ return Object.freeze(persisted);
1060
+ }
1061
+
1062
+ private async updateIdentity(records: readonly ConversationRecord[]): Promise<void> {
1063
+ await this.agent.identity.update({
1064
+ agentSessionId: this.agent.id,
1065
+ agentConversationId: this.conversationId,
1066
+ records,
1067
+ });
1068
+ await this.settings.auditIdentityUpdate(this.conversationId, records);
1069
+ }
1070
+ }
1071
+
1072
+ function normalizeParticipants(participants?: readonly ParticipantRef[]): readonly ParticipantRef[] {
1073
+ const values = participants?.length
1074
+ ? participants.map(normalizeParticipantRef)
1075
+ : [{ id: IMPLICIT_USER_PARTICIPANT_ID, kind: "user" as const }];
1076
+ const seen = new Set<string>();
1077
+ for (const participant of values) {
1078
+ if (seen.has(participant.id)) throw new Error(`duplicate participant id: ${participant.id}`);
1079
+ seen.add(participant.id);
1080
+ }
1081
+ return Object.freeze(values);
1082
+ }
1083
+
1084
+ function internalInferenceMeteringKind(purpose: string): MeteredOperationKind {
1085
+ if (
1086
+ purpose === "conversation_checkpoint"
1087
+ || purpose === "conversation_recovery"
1088
+ || purpose === "identity_update"
1089
+ ) return purpose;
1090
+ return "internal_command";
1091
+ }
1092
+
1093
+ function captureRuntimeRecord(
1094
+ record: NewConversationRecord,
1095
+ level: RecordCaptureLevel,
1096
+ ): NewConversationRecord {
1097
+ if (level !== "metadata") return record;
1098
+ switch (record.kind) {
1099
+ case "message":
1100
+ return { ...record, content: "" };
1101
+ case "tool_call":
1102
+ return {
1103
+ recordId: record.recordId,
1104
+ agentSessionId: record.agentSessionId,
1105
+ agentConversationId: record.agentConversationId,
1106
+ kind: record.kind,
1107
+ timestamp: record.timestamp,
1108
+ ...(record.metadata ? { metadata: record.metadata } : {}),
1109
+ toolCallId: record.toolCallId,
1110
+ state: record.state,
1111
+ ...(record.name ? { name: record.name } : {}),
1112
+ };
1113
+ case "permission":
1114
+ return {
1115
+ recordId: record.recordId,
1116
+ agentSessionId: record.agentSessionId,
1117
+ agentConversationId: record.agentConversationId,
1118
+ kind: record.kind,
1119
+ timestamp: record.timestamp,
1120
+ ...(record.metadata ? { metadata: record.metadata } : {}),
1121
+ permissionId: record.permissionId,
1122
+ state: record.state,
1123
+ ...(record.outcome ? { outcome: record.outcome } : {}),
1124
+ };
1125
+ case "configuration":
1126
+ return { ...record, value: undefined };
1127
+ case "protocol":
1128
+ return { ...record, message: undefined };
1129
+ case "native_action":
1130
+ case "agent_action":
1131
+ return { ...record, input: undefined, output: undefined };
1132
+ case "thinking":
1133
+ return { ...record, content: "" };
1134
+ case "activity":
1135
+ return { ...record, content: undefined, data: undefined };
1136
+ case "metering":
1137
+ return record;
1138
+ }
1139
+ }
1140
+
1141
+ async function enqueueAuditObservation(
1142
+ persistence: PersistenceBackend | PersistenceScope,
1143
+ observation: NormalizedAgentObservation,
1144
+ config: ResolvedAgentAuditLogConfig,
1145
+ ): Promise<void> {
1146
+ const projected = projectAgentAuditObservation(observation, config.capture);
1147
+ if (!projected) return;
1148
+ if (!persistence.auditOutbox) throw new PersistenceCapabilityError("auditOutbox");
1149
+ await persistence.auditOutbox.enqueue({
1150
+ outboxId: `aud-${randomUUID()}`,
1151
+ sourceObservationId: projected.sourceObservationId,
1152
+ ...(projected.sourceRecordId ? { sourceRecordId: projected.sourceRecordId } : {}),
1153
+ ...(projected.operationId ? { operationId: projected.operationId } : {}),
1154
+ ...(projected.agentConversationId ? { agentConversationId: projected.agentConversationId } : {}),
1155
+ occurredAt: projected.occurredAt,
1156
+ kind: projected.kind,
1157
+ captureLevel: projected.captureLevel,
1158
+ captureFingerprint: config.captureFingerprint,
1159
+ payload: projected.payload,
1160
+ createdAt: new Date().toISOString(),
1161
+ });
1162
+ }
1163
+
1164
+ function operationIdFromMetadata(metadata: string | undefined): string | undefined {
1165
+ if (!metadata) return undefined;
1166
+ try {
1167
+ const value = JSON.parse(metadata) as { operationId?: unknown };
1168
+ return typeof value.operationId === "string" && value.operationId ? value.operationId : undefined;
1169
+ } catch {
1170
+ return undefined;
1171
+ }
1172
+ }
1173
+
1174
+ export { AgentAdapterRegistry, NoopAgentIdentityRuntime, composeIdentityPrompt };
1175
+ export type { AgentAdapterRegistration, AgentIdentityRuntime, IdentityConsistency };