@qlairoslabs/acp-client 0.10.1 → 0.11.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 (42) hide show
  1. package/CONSUMER_GUIDE.md +252 -0
  2. package/README.md +0 -3
  3. package/package.json +1 -1
  4. package/src/agent/adoption/config.ts +57 -0
  5. package/src/agent/adoption/index.ts +8 -0
  6. package/src/agent/adoption/provider-session-delete.ts +27 -0
  7. package/src/agent/adoption/provider-sessions.ts +73 -0
  8. package/src/agent/adoption/recap.ts +15 -0
  9. package/src/agent/adoption/replay.ts +84 -0
  10. package/src/agent/config.ts +182 -0
  11. package/src/agent/conversation-manager.ts +1006 -0
  12. package/src/agent/manager-settings.ts +46 -0
  13. package/src/agent/persisted-lifecycle.ts +309 -0
  14. package/src/agent/persistence-policy/index.ts +8 -0
  15. package/src/agent/persistence-policy/resolver.ts +118 -0
  16. package/src/agent/persistence-policy/types.ts +50 -0
  17. package/src/agent/record-capture.ts +243 -0
  18. package/src/agent-conversation-contracts.ts +11 -0
  19. package/src/agent-conversation-errors.ts +24 -0
  20. package/src/agent-conversation-owner.ts +7 -0
  21. package/src/agent-conversation-queue.ts +23 -0
  22. package/src/agent-session.ts +236 -66
  23. package/src/agent.ts +63 -1223
  24. package/src/audit/config.ts +29 -0
  25. package/src/audit/index.ts +1 -0
  26. package/src/checkpointing/contracts.ts +2 -0
  27. package/src/checkpointing/persistence/sqlite-repository.ts +13 -0
  28. package/src/checkpointing/strategy.ts +11 -5
  29. package/src/client.ts +25 -2
  30. package/src/controller.ts +3 -0
  31. package/src/index.ts +24 -0
  32. package/src/internal-inference/contracts.ts +23 -0
  33. package/src/internal-inference/coordination/manager.ts +22 -8
  34. package/src/persistence/backend.ts +17 -0
  35. package/src/persistence/sqlite-backend.ts +30 -4
  36. package/src/persistence/sqlite-provider-sessions.ts +35 -0
  37. package/src/persistence/sqlite-schema.ts +13 -3
  38. package/src/steering/combine.ts +56 -0
  39. package/src/steering/contracts.ts +84 -0
  40. package/src/steering/controller.ts +205 -0
  41. package/src/steering/index.ts +14 -0
  42. package/src/transport/acp-transport.ts +11 -0
@@ -0,0 +1,1006 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import {
3
+ createAgentConversationId,
4
+ type AgentConversationId,
5
+ } from "../agent-ids.ts";
6
+ import {
7
+ AgentConversation,
8
+ } from "../agent-session.ts";
9
+ import type { AgentMode } from "../controller.ts";
10
+ import { MeteringEngine } from "../metering/engine.ts";
11
+ import { createModelsDevResolver } from "../metering/catalog/index.ts";
12
+ import {
13
+ type AgentConversationSummary,
14
+ type ConversationListOptions,
15
+ type ConversationPage,
16
+ type ConversationPreviewPage,
17
+ type ConversationErrorDetails,
18
+ type ConversationErrorRecoverability,
19
+ type ConversationErrorSource,
20
+ type ConversationRecord,
21
+ type MessageRecord,
22
+ type NewConversationRecord,
23
+ type ParticipantRef,
24
+ } from "../persistence/backend.ts";
25
+ import { ProviderSessionError, ProviderSessionInUseError } from "../agent-conversation-errors.ts";
26
+ import {
27
+ OUT_OF_BAND_MESSAGE_ORIGIN,
28
+ type AppendAssistantMessageInput,
29
+ } from "../out-of-band-messages.ts";
30
+ import type {
31
+ ProviderAttachmentCommitAcknowledgement,
32
+ } from "../persistence/provider-attachment.ts";
33
+ import type { InternalInferenceSnapshot } from "../internal-inference/contracts.ts";
34
+ import {
35
+ buildRecoverySeed,
36
+ classifyProviderSessionLoadError,
37
+ type ConversationRecoveryResult,
38
+ } from "../checkpointing/index.ts";
39
+
40
+ import type { ManagerSettings } from "./manager-settings.ts";
41
+ import {
42
+ updateConversationIdentity,
43
+ persistConversationObservations,
44
+ normalizeParticipants,
45
+ internalInferenceMeteringKind,
46
+ appendCanonicalRecord,
47
+ captureRuntimeRecord,
48
+ enqueueAuditObservation,
49
+ providerSessionErrorDetails,
50
+ } from "./record-capture.ts";
51
+ import {
52
+ PersistedConversationLifecycle,
53
+ } from "./persisted-lifecycle.ts";
54
+ import type {
55
+ AgentConversationManager,
56
+ AgentConversationRuntimeDefaults,
57
+ ClearTranscriptOptions,
58
+ ClearTranscriptResult,
59
+ CreateAgentConversationConfig,
60
+ DeleteConversationOptions,
61
+ DeleteConversationResult,
62
+ OpenAgentConversationConfig,
63
+ OpenOwnedAgentConversationResult,
64
+ } from "./config.ts";
65
+
66
+ import type { Agent } from "../agent.ts";
67
+ import type { ConversationWritePolicy } from "../internal-inference/contracts.ts";
68
+ import { ConversationSettingsResolver } from "./persistence-policy/index.ts";
69
+ import {
70
+ RECAP_INSTRUCTION,
71
+ RECAP_ORIGIN,
72
+ deleteProviderSession,
73
+ listProviderSessions,
74
+ normalizeAdoption,
75
+ selectTail,
76
+ turnsFromReplay,
77
+ type ListProviderSessionsOptions,
78
+ type NormalizedAdoption,
79
+ type ProviderSessionSummary,
80
+ } from "./adoption/index.ts";
81
+ import { NoopAgentIdentityRuntime } from "../identity.ts";
82
+ import type { ConversationPersistenceContext } from "./persistence-policy/index.ts";
83
+
84
+ export class DefaultAgentConversationManager implements AgentConversationManager {
85
+ private readonly live = new Map<AgentConversationId, AgentConversation>();
86
+ private readonly openings = new Map<AgentConversationId, Promise<OpenOwnedAgentConversationResult>>();
87
+ private readonly meteringSetupLocks = new Map<AgentConversationId, Promise<void>>();
88
+ private readonly detachedMeteringBarriers = new Map<AgentConversationId, Promise<void>>();
89
+ private agentMeteringBarrier: Promise<void> | undefined;
90
+ /** Resolves what each conversation persists: the Agent's settings with the consumer's per-conversation overrides. */
91
+ private readonly policies: ConversationSettingsResolver;
92
+ /** The settings a live conversation started with. A live conversation keeps them until it is opened again. */
93
+ private readonly liveSettings = new Map<AgentConversationId, ManagerSettings>();
94
+
95
+ constructor(private readonly agent: Agent, private readonly settings: ManagerSettings) {
96
+ this.policies = new ConversationSettingsResolver(settings, settings.conversationPersistence);
97
+ }
98
+
99
+ private contextOf(summary: AgentConversationSummary): ConversationPersistenceContext {
100
+ return {
101
+ agentConversationId: summary.agentConversationId,
102
+ participants: summary.participants,
103
+ ...(summary.title !== undefined && summary.title !== null ? { title: summary.title } : {}),
104
+ ...(summary.metadata !== undefined && summary.metadata !== null ? { metadata: summary.metadata } : {}),
105
+ adopted: summary.adopted === true,
106
+ };
107
+ }
108
+
109
+ /**
110
+ * What a conversation persists, for the writes an internal inference makes about it (a checkpoint's
111
+ * `native_action` record, the detailed metering record). Resolved from the stored conversation, or the live
112
+ * one's own settings.
113
+ */
114
+ async writePolicyFor(id: AgentConversationId): Promise<ConversationWritePolicy> {
115
+ const summary = await this.agent.persistence.conversations.get(id);
116
+ const settings = summary && !summary.deletedAt ? this.writeSettings(summary) : this.settings;
117
+ return {
118
+ meteringRecords: settings.meteringRecords,
119
+ appendRecord: (persistence, record) => appendCanonicalRecord(settings, persistence, record),
120
+ };
121
+ }
122
+
123
+ /** Whether the conversation is kept out of the audit stream (`auditLog: false`), when the Agent audits at all. */
124
+ async auditExcluded(id: AgentConversationId): Promise<boolean> {
125
+ if (!this.settings.auditLog) return false;
126
+ const summary = await this.agent.persistence.conversations.get(id);
127
+ if (!summary || summary.deletedAt) return false;
128
+ return this.writeSettings(summary).auditLog === null;
129
+ }
130
+
131
+ /** Settings for a write about a conversation: the live conversation's own, or what the resolver says now. */
132
+ private writeSettings(summary: AgentConversationSummary): ManagerSettings {
133
+ return (this.live.has(summary.agentConversationId) && this.liveSettings.get(summary.agentConversationId))
134
+ || this.policies.settingsFor(this.contextOf(summary));
135
+ }
136
+
137
+ async create(config: CreateAgentConversationConfig = {}): Promise<AgentConversation> {
138
+ const id = config.id ?? createAgentConversationId();
139
+ const participants = normalizeParticipants(config.participants);
140
+ // What this conversation persists is decided before any write, so a resolver that throws or
141
+ // returns something invalid leaves no row, no error record and no provider session behind.
142
+ const adoption = config.adopt
143
+ ? normalizeAdoption(config.adopt, { recap: !(this.agent.identity instanceof NoopAgentIdentityRuntime) })
144
+ : undefined;
145
+ const settings = this.policies.settingsFor({
146
+ agentConversationId: id,
147
+ participants,
148
+ ...(config.title !== undefined ? { title: config.title } : {}),
149
+ ...(config.metadata !== undefined ? { metadata: config.metadata } : {}),
150
+ adopted: adoption !== undefined,
151
+ });
152
+ if (adoption) {
153
+ // An adopted conversation joins the Agent's memory, which is built from stored messages; one that
154
+ // stores none would join it empty. Driving a session without storing anything is `acp-client`'s job.
155
+ const level = settings.capture.message;
156
+ if (level !== "content" && level !== "raw") {
157
+ throw new Error(`adopting a provider session requires message capture "content" or "raw", not "${level}"`);
158
+ }
159
+ }
160
+ // Validate caller input before the durable row: a mistake must not orphan a
161
+ // conversation, and must not be recorded as a provider-session failure.
162
+ this.prepareStart({ ...config, providerSession: adoption ? "load" : "new" });
163
+ if (adoption) return await this.createAdopting(id, participants, config, adoption, settings);
164
+ await this.agent.persistence.conversations.create({
165
+ agentSessionId: this.agent.id,
166
+ agentConversationId: id,
167
+ participants,
168
+ ...(config.title !== undefined ? { title: config.title } : {}),
169
+ ...(config.metadata !== undefined ? { metadata: config.metadata } : {}),
170
+ });
171
+ const attemptId = `provider-create-${randomUUID()}`;
172
+ try {
173
+ return await this.start(id, participants, {
174
+ ...config,
175
+ providerSession: "new",
176
+ settings,
177
+ });
178
+ } catch (error) {
179
+ return await this.throwCreateFailure(id, attemptId, error, settings);
180
+ }
181
+ }
182
+
183
+ /**
184
+ * Create a conversation around an existing provider session and load it. The ownership check and the row
185
+ * are one transaction, so two adoptions of the same session cannot both pass. From the row on, a provider
186
+ * failure is recorded and the row stays (like `create()`); `open()` of such a conversation retries the load.
187
+ */
188
+ private async createAdopting(
189
+ id: AgentConversationId,
190
+ participants: readonly ParticipantRef[],
191
+ config: CreateAgentConversationConfig,
192
+ adoption: NormalizedAdoption,
193
+ settings: ManagerSettings,
194
+ ): Promise<AgentConversation> {
195
+ await this.agent.persistence.transaction(async (persistence) => {
196
+ const owners = persistence.providerSessions.conversationsUsing;
197
+ if (!owners) {
198
+ throw new Error(
199
+ "this persistence backend cannot tell which conversation owns a provider session, so one cannot be adopted",
200
+ );
201
+ }
202
+ const owned = await owners.call(persistence.providerSessions, adoption.providerSessionId);
203
+ if (owned.length > 0) throw new ProviderSessionInUseError(adoption.providerSessionId, owned);
204
+ await persistence.conversations.create({
205
+ agentSessionId: this.agent.id,
206
+ agentConversationId: id,
207
+ participants,
208
+ ...(config.title !== undefined ? { title: config.title } : {}),
209
+ ...(config.metadata !== undefined ? { metadata: config.metadata } : {}),
210
+ adoptProviderSessionId: adoption.providerSessionId,
211
+ });
212
+ });
213
+ const attemptId = `provider-load-${randomUUID()}`;
214
+ const replay: unknown[] = [];
215
+ let conversation: AgentConversation;
216
+ try {
217
+ conversation = await this.start(id, participants, {
218
+ ...config,
219
+ providerSession: "load",
220
+ internalSessionId: adoption.providerSessionId,
221
+ settings,
222
+ ...(adoption.importHistory ? { onReplay: (notification: unknown) => replay.push(notification) } : {}),
223
+ });
224
+ } catch (error) {
225
+ throw await this.loadFailure(id, attemptId, adoption.providerSessionId, error, settings);
226
+ }
227
+ try {
228
+ await this.recordAdoptedProviderSession(conversation, id, attemptId);
229
+ if (adoption.recap) await this.recap(conversation, id, attemptId, settings);
230
+ if (adoption.importHistory) {
231
+ const turns = selectTail(turnsFromReplay(replay), adoption.importHistory.last);
232
+ await conversation.importHistory(turns, `${attemptId}-import`);
233
+ }
234
+ } catch (error) {
235
+ this.live.delete(id);
236
+ await conversation.stop().catch(() => undefined);
237
+ throw error;
238
+ }
239
+ return conversation;
240
+ }
241
+
242
+ /**
243
+ * Ask the adopted session to summarize itself and store the answer ahead of the imported turns. A recap
244
+ * that fails is recorded and does not fail the adoption: the conversation is usable, but is not in the
245
+ * Agent's memory until something summarizes it.
246
+ */
247
+ private async recap(
248
+ conversation: AgentConversation,
249
+ id: AgentConversationId,
250
+ attemptId: string,
251
+ settings: ManagerSettings,
252
+ ): Promise<void> {
253
+ const recapId = `${attemptId}-recap`;
254
+ try {
255
+ const summary = await conversation.requestRecap(RECAP_INSTRUCTION, recapId);
256
+ await conversation.recordRecap(summary, recapId, RECAP_ORIGIN);
257
+ } catch (error) {
258
+ await this.recordConversationError({
259
+ settings,
260
+ agentConversationId: id,
261
+ attemptId: recapId,
262
+ source: "operation",
263
+ code: "adoption_recap_failed",
264
+ recoverability: "retryable",
265
+ message: "The adopted session could not be summarized.",
266
+ details: providerSessionErrorDetails(error),
267
+ });
268
+ }
269
+ }
270
+
271
+ /** Record a failed provider-session load and build the structured error for it. */
272
+ private async loadFailure(
273
+ id: AgentConversationId,
274
+ attemptId: string,
275
+ internalSessionId: string,
276
+ error: unknown,
277
+ settings: ManagerSettings,
278
+ ): Promise<ProviderSessionError> {
279
+ const classification = classifyProviderSessionLoadError(error, settings.checkpointing?.recovery?.isMissingProviderSession);
280
+ const recorded = await this.recordConversationError({
281
+ settings,
282
+ agentConversationId: id,
283
+ attemptId,
284
+ source: "provider_session",
285
+ code: classification.code,
286
+ recoverability: classification.recoverability,
287
+ message: "The provider session could not be loaded.",
288
+ transitionId: attemptId,
289
+ internalSessionId,
290
+ details: providerSessionErrorDetails(error),
291
+ });
292
+ return new ProviderSessionError({
293
+ agentSessionId: this.agent.id,
294
+ agentConversationId: id,
295
+ attemptId,
296
+ internalSessionId,
297
+ code: classification.code,
298
+ source: "provider_session",
299
+ recoverability: classification.recoverability,
300
+ ...(recorded.record ? { recordId: recorded.record.recordId } : {}),
301
+ ...(recorded.recordingError ? { recordingError: recorded.recordingError } : {}),
302
+ cause: error,
303
+ });
304
+ }
305
+
306
+ /**
307
+ * Write the provider-session row of a loaded session that no conversation had recorded yet (an adoption). A
308
+ * loaded thread is "recorded" in memory already, so this is the one write that makes it durable; the
309
+ * identity delivery cursors restart, as for any new provider context.
310
+ */
311
+ private async recordAdoptedProviderSession(
312
+ conversation: AgentConversation,
313
+ id: AgentConversationId,
314
+ transitionId: string,
315
+ ): Promise<void> {
316
+ const attachment = conversation.providerAttachmentState;
317
+ if (attachment.kind === "absent") throw new Error("the adopted provider session is not attached");
318
+ const descriptor = attachment.descriptor;
319
+ await this.agent.persistence.transaction(async (persistence) => {
320
+ await persistence.identityDelivery?.reset(id, descriptor.internalSessionId);
321
+ await persistence.providerSessions.append({
322
+ providerSessionRecordId: `provider-${randomUUID()}`,
323
+ agentConversationId: id,
324
+ internalSessionId: descriptor.internalSessionId,
325
+ adapterId: descriptor.adapterId,
326
+ mode: descriptor.mode,
327
+ ...(descriptor.model ? { model: descriptor.model } : {}),
328
+ activatedAt: descriptor.acquiredAt,
329
+ transitionId,
330
+ metadata: JSON.stringify({ adopted: true }),
331
+ });
332
+ });
333
+ }
334
+
335
+ async open(
336
+ id: AgentConversationId,
337
+ config: OpenAgentConversationConfig = {},
338
+ ): Promise<OpenOwnedAgentConversationResult> {
339
+ const existing = this.live.get(id);
340
+ if (existing && existing.state.phase !== "stopped") {
341
+ return Object.freeze({ conversation: existing, providerSession: "already_open" });
342
+ }
343
+ const pending = this.openings.get(id);
344
+ if (pending) return await pending;
345
+ const opening = this.openOnce(id, config);
346
+ this.openings.set(id, opening);
347
+ try {
348
+ return await opening;
349
+ } finally {
350
+ if (this.openings.get(id) === opening) this.openings.delete(id);
351
+ }
352
+ }
353
+
354
+ private async openOnce(
355
+ id: AgentConversationId,
356
+ config: OpenAgentConversationConfig,
357
+ ): Promise<OpenOwnedAgentConversationResult> {
358
+ const summary = await this.agent.persistence.conversations.get(id);
359
+ if (!summary || summary.deletedAt) throw new Error(`unknown active conversation: ${id}`);
360
+ const recorded = await this.agent.persistence.providerSessions.active(id);
361
+ // An adoption that failed before its session was recorded keeps asking for that session: opening it
362
+ // retries the load. Starting a new session instead would silently not be the one that was adopted.
363
+ const pendingAdoption = !recorded && summary.adopted === true;
364
+ if (pendingAdoption && !summary.adoptProviderSessionId) {
365
+ throw new Error(`adopted conversation ${id} has no provider session to load`);
366
+ }
367
+ const active = recorded ?? (pendingAdoption
368
+ ? { internalSessionId: summary.adoptProviderSessionId!, adapterId: this.resolveAdapterId(config.adapterId) }
369
+ : null);
370
+ if (active && config.adapterId && config.adapterId !== active.adapterId) {
371
+ throw new Error(
372
+ `conversation ${id} is active on ${active.adapterId}; use a conversation switch instead of loading it with ${config.adapterId}`,
373
+ );
374
+ }
375
+ // Resolved once for this open, before any write: the load-failure and recovery records below and the
376
+ // recovered provider thread all follow this conversation's policy, and the resolver is not called again.
377
+ const settings = this.policies.settingsFor(this.contextOf(summary));
378
+ const startConfig = {
379
+ ...config,
380
+ runtime: {
381
+ ...(summary.title ? { title: summary.title } : {}),
382
+ ...config.runtime,
383
+ },
384
+ adapterId: config.adapterId ?? active?.adapterId,
385
+ };
386
+ // Validate caller input before the recorded region so a configuration mistake is not
387
+ // persisted as a provider-session failure.
388
+ this.prepareStart({ ...startConfig, providerSession: active ? "load" : "new" });
389
+ const attemptId = active ? `provider-load-${randomUUID()}` : `provider-create-${randomUUID()}`;
390
+ try {
391
+ const conversation = await this.start(id, summary.participants, {
392
+ ...startConfig,
393
+ providerSession: active ? "load" : "new",
394
+ internalSessionId: active?.internalSessionId,
395
+ settings,
396
+ });
397
+ if (pendingAdoption) {
398
+ try {
399
+ await this.recordAdoptedProviderSession(conversation, id, attemptId);
400
+ } catch (recordError) {
401
+ this.live.delete(id);
402
+ await conversation.stop().catch(() => undefined);
403
+ throw recordError;
404
+ }
405
+ }
406
+ return Object.freeze({
407
+ conversation,
408
+ providerSession: active ? "loaded" : "new",
409
+ });
410
+ } catch (error) {
411
+ // No recorded mapping means this open was creating a thread, not loading one.
412
+ if (!active) return await this.throwCreateFailure(id, attemptId, error, settings);
413
+ const recovery = settings.checkpointing?.recovery;
414
+ const classification = classifyProviderSessionLoadError(error, recovery?.isMissingProviderSession);
415
+ const recorded = await this.recordConversationError({
416
+ settings,
417
+ agentConversationId: id,
418
+ attemptId,
419
+ source: "provider_session",
420
+ code: classification.code,
421
+ recoverability: classification.recoverability,
422
+ message: "The provider session could not be loaded.",
423
+ transitionId: attemptId,
424
+ internalSessionId: active.internalSessionId,
425
+ details: providerSessionErrorDetails(error),
426
+ });
427
+ const structuredError = (): ProviderSessionError => new ProviderSessionError({
428
+ agentSessionId: this.agent.id,
429
+ agentConversationId: id,
430
+ attemptId,
431
+ internalSessionId: active.internalSessionId,
432
+ code: classification.code,
433
+ source: "provider_session",
434
+ recoverability: classification.recoverability,
435
+ ...(recorded.record ? { recordId: recorded.record.recordId } : {}),
436
+ ...(recorded.recordingError ? { recordingError: recorded.recordingError } : {}),
437
+ cause: error,
438
+ });
439
+ if (recovery?.onLoadFailure !== "recover" || !classification.missing) throw structuredError();
440
+ config.onRecoveryProgress?.({ stage: "load_failed" });
441
+ config.onRecoveryProgress?.({ stage: "loading_checkpoint" });
442
+ const checkpoint = await this.agent.persistence.recoveryCheckpoints?.latest(id);
443
+ if (!checkpoint) throw structuredError();
444
+ config.onRecoveryProgress?.({ stage: "loading_checkpoint", checkpointId: checkpoint.checkpointId });
445
+ const recoveryAttemptId = `recovery-${randomUUID()}`;
446
+ try {
447
+ const seed = await buildRecoverySeed(
448
+ this.agent.persistence.messages,
449
+ id,
450
+ checkpoint,
451
+ summary.latestSequence,
452
+ recovery,
453
+ );
454
+ config.onRecoveryProgress?.({ stage: "creating_session", checkpointId: checkpoint.checkpointId });
455
+ const conversation = await this.start(id, summary.participants, {
456
+ ...startConfig,
457
+ providerSession: "new",
458
+ settings,
459
+ });
460
+ try {
461
+ config.onRecoveryProgress?.({ stage: "seeding", checkpointId: checkpoint.checkpointId });
462
+ await conversation.seedRecoveryContext(seed.prompt);
463
+ const acknowledgement = await this.persistProviderSession(conversation, id, {
464
+ transitionId: recoveryAttemptId,
465
+ metadata: JSON.stringify({
466
+ recoveryCheckpointId: checkpoint.checkpointId,
467
+ previousInternalSessionId: active.internalSessionId,
468
+ recoveredThroughSequence: seed.recoveredThroughSequence,
469
+ }),
470
+ }, true);
471
+ conversation.acknowledgeProviderAttachment(acknowledgement);
472
+ } catch (recoveryError) {
473
+ this.live.delete(id);
474
+ await conversation.stop().catch(() => undefined);
475
+ throw recoveryError;
476
+ }
477
+ const result: ConversationRecoveryResult = Object.freeze({
478
+ checkpointId: checkpoint.checkpointId,
479
+ coveredSequence: checkpoint.coveredSequence,
480
+ recoveredThroughSequence: seed.recoveredThroughSequence,
481
+ previousInternalSessionId: active.internalSessionId,
482
+ newInternalSessionId: conversation.internalSessionId!,
483
+ });
484
+ config.onRecoveryProgress?.({ stage: "completed", checkpointId: checkpoint.checkpointId });
485
+ return Object.freeze({ conversation, providerSession: "recovered", recovery: result });
486
+ } catch (recoveryError) {
487
+ // A recovery failure is a distinct root cause from the load failure already
488
+ // recorded above; it prevents the logical conversation from reopening.
489
+ const recoveryRecorded = await this.recordConversationError({
490
+ settings,
491
+ agentConversationId: id,
492
+ attemptId: recoveryAttemptId,
493
+ source: "recovery",
494
+ code: "recovery_failed",
495
+ recoverability: "recoverable",
496
+ message: "The conversation could not be recovered from its checkpoint.",
497
+ transitionId: recoveryAttemptId,
498
+ internalSessionId: active.internalSessionId,
499
+ });
500
+ throw new ProviderSessionError({
501
+ agentSessionId: this.agent.id,
502
+ agentConversationId: id,
503
+ attemptId: recoveryAttemptId,
504
+ internalSessionId: active.internalSessionId,
505
+ code: "recovery_failed",
506
+ source: "recovery",
507
+ recoverability: "recoverable",
508
+ message: "The conversation could not be recovered from its checkpoint.",
509
+ ...(recoveryRecorded.record ? { recordId: recoveryRecorded.record.recordId } : {}),
510
+ ...(recoveryRecorded.recordingError ? { recordingError: recoveryRecorded.recordingError } : {}),
511
+ cause: recoveryError,
512
+ });
513
+ }
514
+ }
515
+ }
516
+
517
+ async get(id: AgentConversationId): Promise<AgentConversationSummary | null> {
518
+ return await this.agent.persistence.conversations.get(id);
519
+ }
520
+
521
+ async list(options?: ConversationListOptions): Promise<ConversationPage> {
522
+ return await this.agent.persistence.conversations.list(options);
523
+ }
524
+
525
+ /** How to start a harness for a call that has no conversation: the conversations' launcher, env and cwd defaults. */
526
+ private providerClient() {
527
+ const defaults = this.settings.defaults;
528
+ return {
529
+ ...(defaults.launcher ? { launcher: defaults.launcher } : {}),
530
+ ...(defaults.execPrefix ? { execPrefix: defaults.execPrefix } : {}),
531
+ ...(defaults.env ? { env: defaults.env } : {}),
532
+ ...(defaults.cwd ? { cwd: defaults.cwd } : {}),
533
+ ...(defaults.clientInfo ? { clientInfo: defaults.clientInfo } : {}),
534
+ ...(defaults.logger ? { logger: defaults.logger } : {}),
535
+ };
536
+ }
537
+
538
+ async listProviderSessions(options: ListProviderSessionsOptions = {}): Promise<readonly ProviderSessionSummary[]> {
539
+ const adapterId = this.resolveAdapterId(options.adapterId);
540
+ const owners = this.agent.persistence.providerSessions.conversationsUsing;
541
+ return await listProviderSessions({
542
+ adapterId,
543
+ adapter: this.agent.adapters.require(adapterId),
544
+ client: this.providerClient(),
545
+ owners: async (providerSessionId) =>
546
+ owners ? await owners.call(this.agent.persistence.providerSessions, providerSessionId) : [],
547
+ }, options);
548
+ }
549
+
550
+ async listPreviews(options?: ConversationListOptions): Promise<ConversationPreviewPage> {
551
+ if (!this.agent.persistence.conversations.listPreviews) {
552
+ throw new Error("conversation previews are unavailable on this persistence backend");
553
+ }
554
+ return await this.agent.persistence.conversations.listPreviews(options);
555
+ }
556
+
557
+ async delete(
558
+ id: AgentConversationId,
559
+ options: string | DeleteConversationOptions = {},
560
+ ): Promise<DeleteConversationResult> {
561
+ const { deletedAt, providerSession = "no", checkpoints = false }: DeleteConversationOptions =
562
+ typeof options === "string" ? { deletedAt: options } : options;
563
+ // Read what the provider side needs before the conversation is gone from view.
564
+ const active = providerSession === "best-effort"
565
+ ? await this.agent.persistence.providerSessions.active(id)
566
+ : null;
567
+ const live = this.live.get(id);
568
+ if (live) await live.stop();
569
+ this.live.delete(id);
570
+ const checkpointsDeleted = checkpoints
571
+ ? (await this.agent.persistence.recoveryCheckpoints?.deleteForConversation?.(id)) ?? 0
572
+ : 0;
573
+ await this.agent.persistence.conversations.delete(id, deletedAt);
574
+ let providerDeleted: boolean | "unsupported" = false;
575
+ if (active) {
576
+ providerDeleted = await deleteProviderSession({
577
+ adapterId: active.adapterId,
578
+ adapter: this.agent.adapters.require(active.adapterId),
579
+ client: this.providerClient(),
580
+ }, active.internalSessionId);
581
+ }
582
+ return Object.freeze({ providerDeleted, checkpointsDeleted });
583
+ }
584
+
585
+ async clearTranscript(
586
+ id: AgentConversationId,
587
+ options: ClearTranscriptOptions = {},
588
+ ): Promise<ClearTranscriptResult> {
589
+ const summary = await this.agent.persistence.conversations.get(id);
590
+ if (!summary || summary.deletedAt) throw new Error(`unknown active conversation: ${id}`);
591
+ const live = this.live.get(id);
592
+ if (live?.isBusy) {
593
+ throw new Error(`conversation ${id} is busy; wait for its running operation before clearing its transcript`);
594
+ }
595
+ if (!this.agent.persistence.records.deleteForConversation) {
596
+ throw new Error("this persistence backend cannot clear a transcript");
597
+ }
598
+ return await this.agent.persistence.transaction(async (persistence) => {
599
+ const recordsDeleted = await persistence.records.deleteForConversation!(id);
600
+ const checkpointsDeleted = options.checkpoints
601
+ ? (await persistence.recoveryCheckpoints?.deleteForConversation?.(id)) ?? 0
602
+ : 0;
603
+ return Object.freeze({ recordsDeleted, checkpointsDeleted });
604
+ });
605
+ }
606
+
607
+ async appendAssistantMessage(
608
+ id: AgentConversationId,
609
+ input: AppendAssistantMessageInput,
610
+ ): Promise<MessageRecord> {
611
+ if (typeof input.text !== "string" || !input.text.trim()) {
612
+ throw new Error("assistant message text cannot be blank");
613
+ }
614
+ const summary = await this.agent.persistence.conversations.get(id);
615
+ if (!summary || summary.deletedAt) throw new Error(`unknown active conversation: ${id}`);
616
+ const settings = this.writeSettings(summary);
617
+ const level = settings.capture.message;
618
+ if (level !== "content" && level !== "raw") {
619
+ throw new Error(
620
+ `appending an assistant message requires message capture "content" or "raw", not "${level}"`,
621
+ );
622
+ }
623
+ const appendId = `append-${randomUUID()}`;
624
+ const [record] = await persistConversationObservations(this.agent, settings, [{
625
+ recordId: `${appendId}:assistant`,
626
+ agentSessionId: this.agent.id,
627
+ agentConversationId: id,
628
+ kind: "message",
629
+ timestamp: new Date().toISOString(),
630
+ role: "assistant",
631
+ logicalMessageId: `message:${appendId}:assistant`,
632
+ ...(input.consumerMetadata !== undefined ? { consumerMetadata: input.consumerMetadata } : {}),
633
+ content: input.text,
634
+ status: "completed",
635
+ metadata: JSON.stringify({ origin: OUT_OF_BAND_MESSAGE_ORIGIN, appendId }),
636
+ }]);
637
+ if (record?.kind !== "message") throw new Error("assistant message was not persisted");
638
+ await updateConversationIdentity(this.agent, settings, id, [record]);
639
+ return record;
640
+ }
641
+
642
+ async stopAll(): Promise<void> {
643
+ await Promise.allSettled([...this.openings.values()]);
644
+ const conversations = [...this.live.values()];
645
+ this.live.clear();
646
+ await Promise.allSettled(conversations.map((conversation) => conversation.stop()));
647
+ }
648
+
649
+ async beginInternalInferenceMetering(
650
+ attempt: InternalInferenceSnapshot,
651
+ session: { readonly internalSessionId: string; readonly model: string | null },
652
+ ): Promise<import("../internal-inference/contracts.ts").InternalInferenceMeteringOperation | null> {
653
+ const conversationId = attempt.agentConversationId;
654
+ const releaseSetup = conversationId
655
+ ? await this.acquireMeteringSetupLock(conversationId)
656
+ : () => {};
657
+ let barrier: Promise<void> | undefined;
658
+ let releaseBarrier = () => {};
659
+ try {
660
+ const conversation = conversationId ? this.live.get(conversationId) : undefined;
661
+ if (conversation && conversation.state.phase !== "stopped") {
662
+ const operation = await conversation.beginDetachedMetering({
663
+ operationId: attempt.id,
664
+ operationKind: internalInferenceMeteringKind(attempt.purpose),
665
+ internalSessionId: session.internalSessionId,
666
+ model: session.model,
667
+ });
668
+ let closed = false;
669
+ releaseSetup();
670
+ return {
671
+ close: async ({ outcome, result, error }) => {
672
+ if (closed) throw new Error(`internal inference metering already closed: ${attempt.id}`);
673
+ closed = true;
674
+ return await conversation.closeDetachedMetering(operation, {
675
+ outcome,
676
+ usage: result?.usage ?? null,
677
+ ...(error ? { usageFailureReason: String(error) } : {}),
678
+ });
679
+ },
680
+ settled() {},
681
+ };
682
+ }
683
+
684
+ const previous = conversationId
685
+ ? this.detachedMeteringBarriers.get(conversationId) ?? Promise.resolve()
686
+ : this.agentMeteringBarrier ?? Promise.resolve();
687
+ const ownBarrier = new Promise<void>((resolve) => { releaseBarrier = resolve; });
688
+ barrier = previous.then(() => ownBarrier);
689
+ if (conversationId) this.detachedMeteringBarriers.set(conversationId, barrier);
690
+ else this.agentMeteringBarrier = barrier;
691
+ releaseSetup();
692
+ // Detached operations for one closed conversation must restore and commit in order.
693
+ // Otherwise two workers can derive the same next operation count from one snapshot.
694
+ await previous;
695
+ const persisted = conversationId
696
+ ? await this.agent.persistence.metering.state(conversationId)
697
+ : await this.agent.persistence.metering.agentState(this.agent.id);
698
+ const meteringConfig = this.settings.defaults.metering;
699
+ const engine = new MeteringEngine({
700
+ agentSessionId: this.agent.id,
701
+ adapterId: attempt.adapterId,
702
+ enforcement: meteringConfig?.enforcement ?? "best_effort",
703
+ pricing: meteringConfig?.pricing ?? createModelsDevResolver(),
704
+ ...(persisted ? { initialState: persisted.state } : {}),
705
+ createdActiveThread: false,
706
+ ...(meteringConfig?.counterInterpretation
707
+ ? { counterInterpretation: meteringConfig.counterInterpretation }
708
+ : {}),
709
+ ...(meteringConfig?.inferenceSource
710
+ ? { inferenceSource: meteringConfig.inferenceSource }
711
+ : {}),
712
+ });
713
+ const operation = await engine.openDetached({
714
+ operationId: attempt.id,
715
+ operationKind: internalInferenceMeteringKind(attempt.purpose),
716
+ internalSessionId: session.internalSessionId,
717
+ providerId: null,
718
+ model: session.model,
719
+ });
720
+ let closed = false;
721
+ let settled = false;
722
+ return {
723
+ close: async ({ outcome, result, error }) => {
724
+ if (closed) throw new Error(`internal inference metering already closed: ${attempt.id}`);
725
+ closed = true;
726
+ return await engine.closeDetached(operation, {
727
+ outcome,
728
+ reportedCumulative: result?.usage ?? null,
729
+ ...(error ? { usageFailureReason: String(error) } : {}),
730
+ contextAfter: null,
731
+ providerCostAfter: null,
732
+ });
733
+ },
734
+ settled: () => {
735
+ if (settled) return;
736
+ settled = true;
737
+ if (conversationId && this.detachedMeteringBarriers.get(conversationId) === barrier) {
738
+ this.detachedMeteringBarriers.delete(conversationId);
739
+ } else if (!conversationId && this.agentMeteringBarrier === barrier) {
740
+ this.agentMeteringBarrier = undefined;
741
+ }
742
+ releaseBarrier();
743
+ },
744
+ };
745
+ } catch (error) {
746
+ releaseSetup();
747
+ if (barrier && conversationId && this.detachedMeteringBarriers.get(conversationId) === barrier) {
748
+ this.detachedMeteringBarriers.delete(conversationId);
749
+ } else if (barrier && !conversationId && this.agentMeteringBarrier === barrier) {
750
+ this.agentMeteringBarrier = undefined;
751
+ }
752
+ releaseBarrier();
753
+ throw error;
754
+ }
755
+ }
756
+
757
+ private async start(
758
+ id: AgentConversationId,
759
+ participants: readonly ParticipantRef[],
760
+ config: (CreateAgentConversationConfig | OpenAgentConversationConfig) & {
761
+ readonly providerSession: "new" | "load";
762
+ readonly internalSessionId?: string;
763
+ /** What this conversation persists, resolved before it started. */
764
+ readonly settings: ManagerSettings;
765
+ /** Receives the history a loaded provider session replays (raw `session/update` notifications). */
766
+ readonly onReplay?: (notification: unknown) => void;
767
+ },
768
+ ): Promise<AgentConversation> {
769
+ const releaseSetup = await this.acquireMeteringSetupLock(id);
770
+ let conversation: AgentConversation | undefined;
771
+ try {
772
+ const adapterId = this.resolveAdapterId(config.adapterId);
773
+ const adapter = this.agent.adapters.require(adapterId);
774
+ const runtime = { ...this.settings.defaults, ...config.runtime };
775
+ await this.detachedMeteringBarriers.get(id);
776
+ const persistedMetering = await this.agent.persistence.metering.state(id);
777
+ const lifecycle = new PersistedConversationLifecycle(
778
+ this.agent,
779
+ id,
780
+ participants,
781
+ config.settings,
782
+ );
783
+ this.liveSettings.set(id, config.settings);
784
+ conversation = await AgentConversation.create({
785
+ ...runtime,
786
+ ...(persistedMetering
787
+ ? { metering: { ...runtime.metering, initialState: persistedMetering.state } }
788
+ : {}),
789
+ ...("title" in config && config.title !== undefined ? { title: config.title } : {}),
790
+ adapter,
791
+ adapterId,
792
+ agentSessionId: this.agent.id,
793
+ ownerAgentSessionId: this.agent.id,
794
+ agentConversationId: id,
795
+ participants,
796
+ ownerLifecycle: lifecycle,
797
+ mode: config.mode ?? runtime.mode,
798
+ ...(config.mcpServers ? { mcpServers: [...config.mcpServers] } : {}),
799
+ providerSession: config.providerSession === "load"
800
+ ? {
801
+ kind: "load",
802
+ internalSessionId: config.internalSessionId!,
803
+ onFailure: "error",
804
+ ...(config.onReplay ? { onReplay: config.onReplay } : {}),
805
+ }
806
+ : { kind: "new" },
807
+ persistence: false,
808
+ });
809
+ const openedConversation = conversation;
810
+ this.live.set(id, openedConversation);
811
+ openedConversation.subscribe((notification) => {
812
+ if (notification.event.kind === "state_changed" && notification.event.state.phase === "stopped") {
813
+ // The stopped state is published before the active turn finishes its
814
+ // error/finalization path. Keep it discoverable to stopAll() until stop()
815
+ // has drained those writes, or Agent.close() may close SQLite too early.
816
+ void openedConversation.stop().then(() => {
817
+ if (this.live.get(id) === openedConversation) this.live.delete(id);
818
+ }, () => {
819
+ if (this.live.get(id) === openedConversation) this.live.delete(id);
820
+ });
821
+ }
822
+ });
823
+ return conversation;
824
+ } catch (error) {
825
+ this.live.delete(id);
826
+ await conversation?.stop().catch(() => undefined);
827
+ throw error;
828
+ } finally {
829
+ releaseSetup();
830
+ }
831
+ }
832
+
833
+ private async acquireMeteringSetupLock(id: AgentConversationId): Promise<() => void> {
834
+ const previous = this.meteringSetupLocks.get(id) ?? Promise.resolve();
835
+ let releaseGate!: () => void;
836
+ const gate = new Promise<void>((resolve) => { releaseGate = resolve; });
837
+ const current = previous.then(() => gate);
838
+ this.meteringSetupLocks.set(id, current);
839
+ await previous;
840
+ let released = false;
841
+ return () => {
842
+ if (released) return;
843
+ released = true;
844
+ if (this.meteringSetupLocks.get(id) === current) this.meteringSetupLocks.delete(id);
845
+ releaseGate();
846
+ };
847
+ }
848
+
849
+ private resolveAdapterId(requested?: string): string {
850
+ if (requested) return requested;
851
+ if (this.settings.defaultAdapterId) return this.settings.defaultAdapterId;
852
+ const registrations = this.agent.adapters.list();
853
+ if (registrations.length === 1) return registrations[0]!.id;
854
+ throw new Error("adapterId is required when an Agent has no unique default adapter");
855
+ }
856
+
857
+ /**
858
+ * Persist one conversation error record and its audit intent in a single transaction,
859
+ * then publish it through the committed-record bus.
860
+ *
861
+ * A recording failure never replaces the primary provider diagnosis: it is returned so
862
+ * the caller can attach it to the structured exception instead.
863
+ */
864
+ private async recordConversationError(input: {
865
+ /** The conversation's own settings; the Agent's when the record is not about one conversation's start. */
866
+ readonly settings?: ManagerSettings;
867
+ readonly agentConversationId: AgentConversationId;
868
+ readonly attemptId: string;
869
+ readonly source: ConversationErrorSource;
870
+ readonly code: string;
871
+ readonly recoverability: ConversationErrorRecoverability;
872
+ readonly message?: string;
873
+ readonly operationId?: string;
874
+ readonly transitionId?: string;
875
+ readonly internalSessionId?: string;
876
+ readonly details?: ConversationErrorDetails;
877
+ }): Promise<{ readonly record?: ConversationRecord; readonly recordingError?: Error }> {
878
+ const record: NewConversationRecord = {
879
+ recordId: `${input.attemptId}:error`,
880
+ agentSessionId: this.agent.id,
881
+ agentConversationId: input.agentConversationId,
882
+ kind: "error",
883
+ timestamp: new Date().toISOString(),
884
+ source: input.source,
885
+ code: input.code,
886
+ recoverability: input.recoverability,
887
+ ...(input.message === undefined ? {} : { message: input.message }),
888
+ ...(input.operationId === undefined ? {} : { operationId: input.operationId }),
889
+ ...(input.transitionId === undefined ? {} : { transitionId: input.transitionId }),
890
+ ...(input.internalSessionId === undefined ? {} : { internalSessionId: input.internalSessionId }),
891
+ ...(input.details === undefined ? {} : { details: input.details }),
892
+ };
893
+ const settings = input.settings ?? this.settings;
894
+ const level = settings.capture.error;
895
+ const audit = settings.auditLog;
896
+ let persisted: ConversationRecord | undefined;
897
+ try {
898
+ await this.agent.persistence.transaction(async (persistence) => {
899
+ if (level !== "none") {
900
+ persisted = await persistence.records.append(captureRuntimeRecord(record, level));
901
+ }
902
+ if (audit) {
903
+ await enqueueAuditObservation(persistence, {
904
+ scope: "conversation",
905
+ sourceObservationId: record.recordId,
906
+ ...(input.operationId === undefined ? {} : { operationId: input.operationId }),
907
+ record,
908
+ }, audit);
909
+ }
910
+ });
911
+ } catch (error) {
912
+ return { recordingError: error instanceof Error ? error : new Error(String(error)) };
913
+ }
914
+ if (persisted) this.agent.publishCommittedRecords([persisted]);
915
+ if (audit) this.agent.audit?.notifyPending();
916
+ return persisted ? { record: persisted } : {};
917
+ }
918
+
919
+ /**
920
+ * Validate caller-supplied start configuration before any durable write or recorded
921
+ * region.
922
+ *
923
+ * Adapter resolution and mode/provider-thread compatibility are caller mistakes, not
924
+ * conversation failures. Persisting them as provider-session errors would violate the
925
+ * spec and mislead a UI (for example, `retryable` for an adapter that can never resolve).
926
+ */
927
+ private prepareStart(config: {
928
+ readonly adapterId?: string;
929
+ readonly mode?: AgentMode;
930
+ readonly runtime?: AgentConversationRuntimeDefaults;
931
+ readonly providerSession: "new" | "load";
932
+ }): void {
933
+ const adapterId = this.resolveAdapterId(config.adapterId);
934
+ this.agent.adapters.require(adapterId);
935
+ const mode = config.mode ?? config.runtime?.mode ?? this.settings.defaults.mode;
936
+ if (mode === "degraded" && config.providerSession === "load") {
937
+ throw new Error("providerSession.kind=load requires ACP (normal) mode");
938
+ }
939
+ }
940
+
941
+ /**
942
+ * Record a failed provider-session creation and throw the structured error. Used where
943
+ * the durable conversation row already exists, so the caller always learns which logical
944
+ * conversation holds the error.
945
+ */
946
+ private async throwCreateFailure(
947
+ id: AgentConversationId,
948
+ attemptId: string,
949
+ error: unknown,
950
+ settings?: ManagerSettings,
951
+ ): Promise<never> {
952
+ const recorded = await this.recordConversationError({
953
+ ...(settings ? { settings } : {}),
954
+ agentConversationId: id,
955
+ attemptId,
956
+ source: "provider_session",
957
+ code: "provider_session_create_failed",
958
+ recoverability: "retryable",
959
+ message: "The provider session could not be created.",
960
+ transitionId: attemptId,
961
+ });
962
+ throw new ProviderSessionError({
963
+ agentSessionId: this.agent.id,
964
+ agentConversationId: id,
965
+ attemptId,
966
+ code: "provider_session_create_failed",
967
+ source: "provider_session",
968
+ recoverability: "retryable",
969
+ message: "The provider session could not be created.",
970
+ ...(recorded.record ? { recordId: recorded.record.recordId } : {}),
971
+ ...(recorded.recordingError ? { recordingError: recorded.recordingError } : {}),
972
+ cause: error,
973
+ });
974
+ }
975
+
976
+ private async persistProviderSession(
977
+ conversation: AgentConversation,
978
+ id: AgentConversationId,
979
+ extra: { readonly transitionId?: string; readonly metadata?: string } = {},
980
+ newContext = false,
981
+ ): Promise<ProviderAttachmentCommitAcknowledgement> {
982
+ const attachment = conversation.providerAttachmentState;
983
+ if (attachment.kind !== "runtime_only") {
984
+ throw new Error("provider attachment is not awaiting persistence");
985
+ }
986
+ const descriptor = attachment.descriptor;
987
+ const providerSessionRecordId = `provider-${randomUUID()}`;
988
+ await this.agent.persistence.transaction(async (persistence) => {
989
+ if (newContext) await persistence.identityDelivery?.reset(id, descriptor.internalSessionId);
990
+ await persistence.providerSessions.append({
991
+ providerSessionRecordId,
992
+ agentConversationId: id,
993
+ internalSessionId: descriptor.internalSessionId,
994
+ adapterId: descriptor.adapterId,
995
+ mode: descriptor.mode,
996
+ ...(descriptor.model ? { model: descriptor.model } : {}),
997
+ activatedAt: descriptor.acquiredAt,
998
+ ...extra,
999
+ });
1000
+ });
1001
+ return Object.freeze({
1002
+ attachmentAttemptId: descriptor.attachmentAttemptId,
1003
+ providerSessionRecordId,
1004
+ });
1005
+ }
1006
+ }