@qlairoslabs/acp-client 0.10.2 → 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 (36) hide show
  1. package/CONSUMER_GUIDE.md +153 -0
  2. package/package.json +1 -1
  3. package/src/agent/adoption/config.ts +57 -0
  4. package/src/agent/adoption/index.ts +8 -0
  5. package/src/agent/adoption/provider-session-delete.ts +27 -0
  6. package/src/agent/adoption/provider-sessions.ts +73 -0
  7. package/src/agent/adoption/recap.ts +15 -0
  8. package/src/agent/adoption/replay.ts +84 -0
  9. package/src/agent/config.ts +182 -0
  10. package/src/agent/conversation-manager.ts +1006 -0
  11. package/src/agent/manager-settings.ts +46 -0
  12. package/src/agent/persisted-lifecycle.ts +309 -0
  13. package/src/agent/persistence-policy/index.ts +8 -0
  14. package/src/agent/persistence-policy/resolver.ts +118 -0
  15. package/src/agent/persistence-policy/types.ts +50 -0
  16. package/src/agent/record-capture.ts +243 -0
  17. package/src/agent-conversation-contracts.ts +2 -0
  18. package/src/agent-conversation-errors.ts +24 -0
  19. package/src/agent-conversation-owner.ts +2 -0
  20. package/src/agent-session.ts +115 -1
  21. package/src/agent.ts +63 -1233
  22. package/src/audit/config.ts +29 -0
  23. package/src/audit/index.ts +1 -0
  24. package/src/checkpointing/contracts.ts +2 -0
  25. package/src/checkpointing/persistence/sqlite-repository.ts +13 -0
  26. package/src/checkpointing/strategy.ts +11 -5
  27. package/src/client.ts +22 -1
  28. package/src/controller.ts +3 -0
  29. package/src/index.ts +14 -0
  30. package/src/internal-inference/contracts.ts +23 -0
  31. package/src/internal-inference/coordination/manager.ts +22 -8
  32. package/src/persistence/backend.ts +17 -0
  33. package/src/persistence/sqlite-backend.ts +30 -4
  34. package/src/persistence/sqlite-provider-sessions.ts +35 -0
  35. package/src/persistence/sqlite-schema.ts +13 -3
  36. package/src/transport/acp-transport.ts +3 -0
package/src/agent.ts CHANGED
@@ -1,27 +1,13 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import type * as schema from "@agentclientprotocol/sdk";
3
2
  import {
4
- createAgentConversationId,
5
- type AgentConversationId,
6
3
  type AgentSessionId,
7
4
  } from "./agent-ids.ts";
8
5
  import {
9
6
  AgentAdapterRegistry,
10
7
  type AgentAdapterRegistration,
11
8
  } 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
9
  import {
23
10
  NoopAgentIdentityRuntime,
24
- composeIdentityPrompt,
25
11
  type AgentIdentityRuntime,
26
12
  type IdentityConsistency,
27
13
  } from "./identity.ts";
@@ -30,37 +16,15 @@ import {
30
16
  type CheckpointBackedIdentityConfig,
31
17
  } from "./identity/checkpoint-backed.ts";
32
18
  import {
33
- IMPLICIT_USER_PARTICIPANT_ID,
34
19
  PersistenceCapabilityError,
35
- normalizeParticipantRef,
36
20
  resolveConversationRecordCapture,
37
- shouldCaptureProtocolMethod,
38
- type AgentConversationSummary,
39
- type ConversationListOptions,
40
- type ConversationPage,
41
- type ConversationPreviewPage,
42
- type ConversationErrorDetails,
43
- type ConversationErrorRecoverability,
44
- type ConversationErrorSource,
45
21
  type ConversationRecord,
46
- type ConversationRecordCaptureConfig,
47
- type ConversationRecordCapturePolicy,
48
- type MessageRecord,
49
- type MeteringRecordRetention,
50
- type NewConversationRecord,
51
- type ParticipantRef,
52
22
  type PersistenceBackend,
53
- type PersistenceExtension,
54
- type PersistenceScope,
55
- type RecordCaptureLevel,
56
23
  } from "./persistence/backend.ts";
57
24
  import { SqliteAgentPersistence } from "./persistence/sqlite-backend.ts";
58
25
  import {
59
- projectAgentAuditObservation,
60
26
  resolveAgentAuditLogConfig,
61
27
  AgentAuditRuntime,
62
- type AgentAuditLogConfig,
63
- type NormalizedAgentObservation,
64
28
  type ResolvedAgentAuditLogConfig,
65
29
  } from "./audit/index.ts";
66
30
  import { noopLogger } from "./logger.ts";
@@ -68,146 +32,59 @@ import {
68
32
  CommittedRecordEventBus,
69
33
  type AgentEventBus,
70
34
  } from "./observation/agent-event-bus.ts";
71
- import type {
72
- AgentConversationOwnerLifecycle,
73
- OwnedPromptCommitResult,
74
- OwnedPromptCompleted,
75
- OwnedPromptFailed,
76
- OwnedPromptInput,
77
- } from "./agent-conversation-owner.ts";
78
- import { OwnedPromptPostCommitError } from "./agent-conversation-owner.ts";
79
- import { ProviderSessionError } from "./agent-conversation-errors.ts";
80
- import {
81
- OUT_OF_BAND_MESSAGE_ORIGIN,
82
- composeProviderPrompt,
83
- pendingOutOfBandMessages,
84
- type AppendAssistantMessageInput,
85
- } from "./out-of-band-messages.ts";
86
- import { buildConversationErrorDetails } from "./persistence/error-records.ts";
87
- import type {
88
- ProviderAttachmentCommitAcknowledgement,
89
- } from "./persistence/provider-attachment.ts";
90
35
  import {
91
36
  resolveInternalInferenceConfig,
92
- type InternalInferenceConfig,
93
37
  } from "./internal-inference/config.ts";
94
38
  import type {
95
39
  InternalInferenceManager,
96
- InternalInferenceStrategy,
97
40
  } from "./internal-inference/contracts.ts";
98
41
  import { DefaultInternalInferenceManager } from "./internal-inference/coordination/manager.ts";
99
- import type { InternalInferenceSnapshot } from "./internal-inference/contracts.ts";
100
42
  import { HarnessInternalInferenceRuntime } from "./internal-inference/runtime/harness-runtime.ts";
101
43
  import {
102
44
  ConversationCheckpointCoordinator,
103
45
  ConversationCheckpointStrategy,
104
46
  CONVERSATION_CHECKPOINT_STRATEGY_ID,
105
- buildRecoverySeed,
106
- classifyProviderSessionLoadError,
107
47
  resolveConversationCheckpointingConfig,
108
- type ConversationCheckpointingConfig,
109
- type ConversationRecoveryProgress,
110
- type ConversationRecoveryResult,
111
- type ResolvedConversationCheckpointingConfig,
112
48
  } from "./checkpointing/index.ts";
113
49
 
114
- export type AgentPersistenceConfig =
115
- | {
116
- readonly kind: "sqlite";
117
- readonly path: string;
118
- readonly metadata?: string;
119
- readonly busyTimeoutMs?: number;
120
- readonly extensions?: readonly PersistenceExtension[];
121
- readonly allowUnsafeWalVersion?: boolean;
122
- }
123
- | { readonly kind: "custom"; readonly backend: PersistenceBackend };
124
-
125
- type OwnerControlledConversationKey =
126
- | "adapter"
127
- | "adapterId"
128
- | "agentSessionId"
129
- | "agentConversationId"
130
- | "ownerAgentSessionId"
131
- | "participants"
132
- | "ownerLifecycle"
133
- | "providerSession"
134
- | "persistence"
135
- | "transcriptPath"
136
- | "transcriptDir"
137
- | "sessions";
138
-
139
- export type AgentConversationRuntimeDefaults = Omit<
140
- AgentConversationConfig,
141
- OwnerControlledConversationKey
142
- >;
143
-
144
- export interface AgentConfig {
145
- readonly id?: AgentSessionId;
146
- readonly persistence: AgentPersistenceConfig;
147
- readonly adapters: Readonly<Record<string, import("./adapters.ts").Adapter>>
148
- | readonly AgentAdapterRegistration[];
149
- readonly defaultAdapterId?: string;
150
- readonly identity?: AgentIdentityRuntime | CheckpointBackedIdentityConfig;
151
- readonly identityConsistency?: IdentityConsistency;
152
- readonly identityTimeoutMs?: number;
153
- readonly capture?: ConversationRecordCaptureConfig;
154
- readonly conversationDefaults?: AgentConversationRuntimeDefaults;
155
- /** Bounded metering state is always persisted; this controls detailed local history. */
156
- readonly meteringPersistence?: {
157
- readonly meteringRecords?: MeteringRecordRetention;
158
- };
159
- readonly internalInference?: InternalInferenceConfig & {
160
- readonly strategies?: readonly InternalInferenceStrategy[];
161
- };
162
- readonly checkpointing?: ConversationCheckpointingConfig;
163
- readonly auditLog?: false | AgentAuditLogConfig;
164
- }
165
-
166
- export interface CreateAgentConversationConfig {
167
- readonly id?: AgentConversationId;
168
- readonly adapterId?: string;
169
- readonly mode?: AgentMode;
170
- readonly participants?: readonly ParticipantRef[];
171
- readonly title?: string;
172
- readonly metadata?: string;
173
- readonly mcpServers?: schema.McpServer[];
174
- readonly runtime?: AgentConversationRuntimeDefaults;
175
- }
176
-
177
- export interface OpenAgentConversationConfig {
178
- readonly adapterId?: string;
179
- readonly mode?: AgentMode;
180
- readonly mcpServers?: schema.McpServer[];
181
- readonly runtime?: AgentConversationRuntimeDefaults;
182
- readonly onRecoveryProgress?: (event: ConversationRecoveryProgress) => void;
183
- }
184
-
185
- export interface OpenOwnedAgentConversationResult {
186
- readonly conversation: AgentConversation;
187
- readonly providerSession: "already_open" | "loaded" | "new" | "recovered";
188
- readonly recovery?: ConversationRecoveryResult;
189
- }
190
-
191
- export interface AgentConversationManager {
192
- create(config?: CreateAgentConversationConfig): Promise<AgentConversation>;
193
- open(
194
- id: AgentConversationId,
195
- config?: OpenAgentConversationConfig,
196
- ): Promise<OpenOwnedAgentConversationResult>;
197
- get(id: AgentConversationId): Promise<AgentConversationSummary | null>;
198
- list(options?: ConversationListOptions): Promise<ConversationPage>;
199
- listPreviews(options?: ConversationListOptions): Promise<ConversationPreviewPage>;
200
- delete(id: AgentConversationId, deletedAt?: string): Promise<void>;
201
- /**
202
- * Append a completed assistant message the provider did not produce, without a turn or a
203
- * live provider session. It is published on `agent.events`, and the conversation's next
204
- * turn shows it to the provider ahead of the user's text.
205
- */
206
- appendAssistantMessage(
207
- id: AgentConversationId,
208
- input: AppendAssistantMessageInput,
209
- ): Promise<MessageRecord>;
210
- }
50
+ import {
51
+ enqueueAuditObservation,
52
+ } from "./agent/record-capture.ts";
53
+ import {
54
+ DefaultAgentConversationManager,
55
+ } from "./agent/conversation-manager.ts";
56
+ import type {
57
+ AgentConfig,
58
+ AgentConversationManager,
59
+ } from "./agent/config.ts";
60
+
61
+ export type {
62
+ AdoptProviderSessionConfig,
63
+ ListProviderSessionsOptions,
64
+ ProviderSessionSummary,
65
+ } from "./agent/adoption/index.ts";
66
+
67
+ export type {
68
+ AgentConversationAuditCaptureConfig,
69
+ AgentConversationPersistenceOverride,
70
+ AgentScopeAuditObservationKind,
71
+ ConversationPersistenceContext,
72
+ ConversationPersistenceResolver,
73
+ } from "./agent/persistence-policy/index.ts";
74
+
75
+ export type {
76
+ AgentConfig,
77
+ AgentConversationManager,
78
+ ClearTranscriptOptions,
79
+ ClearTranscriptResult,
80
+ DeleteConversationOptions,
81
+ DeleteConversationResult,
82
+ AgentConversationRuntimeDefaults,
83
+ AgentPersistenceConfig,
84
+ CreateAgentConversationConfig,
85
+ OpenAgentConversationConfig,
86
+ OpenOwnedAgentConversationResult,
87
+ } from "./agent/config.ts";
211
88
 
212
89
  /** Durable owner of one agent identity, its adapters, identity runtime, and conversations. */
213
90
  export class Agent {
@@ -281,11 +158,17 @@ export class Agent {
281
158
  : identity && "load" in identity
282
159
  ? identity
283
160
  : new NoopAgentIdentityRuntime();
161
+ if (config.conversationPersistence !== undefined && typeof config.conversationPersistence !== "function") {
162
+ throw new Error("conversationPersistence must be a function");
163
+ }
284
164
  this.manager = new DefaultAgentConversationManager(this, {
285
165
  defaultAdapterId: config.defaultAdapterId,
286
166
  identityConsistency: config.identityConsistency ?? "eventual",
287
167
  identityTimeoutMs: config.identityTimeoutMs,
288
168
  capture: resolveConversationRecordCapture(config.capture),
169
+ ...(config.capture ? { captureConfig: config.capture } : {}),
170
+ ...(config.auditLog && config.auditLog.capture ? { auditCaptureConfig: config.auditLog.capture } : {}),
171
+ ...(config.conversationPersistence ? { conversationPersistence: config.conversationPersistence } : {}),
289
172
  defaults: config.conversationDefaults ?? {},
290
173
  meteringRecords: config.meteringPersistence?.meteringRecords ?? "all",
291
174
  checkpointing,
@@ -300,9 +183,12 @@ export class Agent {
300
183
  });
301
184
  this.conversations = this.manager;
302
185
  if (checkpointing?.enabled) {
186
+ // Checkpoints summarize stored messages, so `metadata` (messages with no text) would checkpoint nothing
187
+ // useful. `none` is allowed: a conversation that stores no messages has nothing to checkpoint, and the
188
+ // conversations that need recovery override to `content` through the resolver.
303
189
  const messageCapture = resolveConversationRecordCapture(config.capture).message;
304
- if (messageCapture !== "content" && messageCapture !== "raw") {
305
- throw new Error("conversation checkpointing requires message capture at content or raw level");
190
+ if (messageCapture === "metadata") {
191
+ throw new Error('conversation checkpointing cannot use message capture "metadata"');
306
192
  }
307
193
  }
308
194
  if (config.internalInference || checkpointing?.enabled) {
@@ -356,7 +242,12 @@ export class Agent {
356
242
  beginMetering: async (attempt, session) => {
357
243
  return await this.manager.beginInternalInferenceMetering(attempt, session);
358
244
  },
359
- onCommittedRecords: (records) => this.publishCommittedRecords(records),
245
+ onCommittedRecords: (records) => {
246
+ this.publishCommittedRecords(records);
247
+ // A record appended under a conversation's audit policy queued an audit entry in the same transaction.
248
+ this.audit?.notifyPending();
249
+ },
250
+ resolveConversationWrites: (agentConversationId) => this.manager.writePolicyFor(agentConversationId),
360
251
  resolveAdapterId: async (requestedAdapterId, agentConversationId) => {
361
252
  if (requestedAdapterId) {
362
253
  adapters.require(requestedAdapterId);
@@ -387,6 +278,7 @@ export class Agent {
387
278
  event.snapshot as unknown as import("./persistence/backend.ts").PersistenceJsonValue,
388
279
  `internal-inference:${event.inferenceId}:${event.sequence}`,
389
280
  event.inferenceId,
281
+ event.snapshot.agentConversationId,
390
282
  );
391
283
  });
392
284
  }
@@ -529,9 +421,14 @@ export class Agent {
529
421
  payload?: import("./persistence/backend.ts").PersistenceJsonValue,
530
422
  sourceObservationId = `${kind}-${randomUUID()}`,
531
423
  operationId?: string,
424
+ agentConversationId?: import("./agent-ids.ts").AgentConversationId,
532
425
  ): Promise<void> {
533
426
  const auditLog = this.auditLog;
534
427
  if (!auditLog) return;
428
+ // An observation about a conversation that is kept out of the audit stream is not written. If its policy
429
+ // cannot be resolved the observation is not written either (it never falls back to the Agent's levels,
430
+ // which could record more than the consumer allowed); the error is kept as the pending audit error.
431
+ if (agentConversationId && await this.manager.auditExcluded(agentConversationId)) return;
535
432
  await enqueueAuditObservation(this.persistence, {
536
433
  scope: "agent",
537
434
  sourceObservationId,
@@ -551,6 +448,7 @@ export class Agent {
551
448
  payload?: import("./persistence/backend.ts").PersistenceJsonValue,
552
449
  sourceObservationId?: string,
553
450
  operationId?: string,
451
+ agentConversationId?: import("./agent-ids.ts").AgentConversationId,
554
452
  ): void {
555
453
  const write = this.auditObservationTail.then(() => this.recordAgentAuditObservation(
556
454
  kind,
@@ -558,6 +456,7 @@ export class Agent {
558
456
  payload,
559
457
  sourceObservationId,
560
458
  operationId,
459
+ agentConversationId,
561
460
  ));
562
461
  this.auditObservationTail = write.catch((error) => {
563
462
  if (this.auditObservationError === undefined) this.auditObservationError = error;
@@ -565,1073 +464,4 @@ export class Agent {
565
464
  }
566
465
  }
567
466
 
568
- interface ManagerSettings {
569
- readonly defaultAdapterId?: string;
570
- readonly identityConsistency: IdentityConsistency;
571
- readonly identityTimeoutMs?: number;
572
- readonly capture: ConversationRecordCapturePolicy;
573
- readonly defaults: AgentConversationRuntimeDefaults;
574
- readonly meteringRecords: MeteringRecordRetention;
575
- readonly checkpointing: ResolvedConversationCheckpointingConfig | null;
576
- readonly auditLog: ResolvedAgentAuditLogConfig | null;
577
- readonly auditIdentityUpdate: (
578
- agentConversationId: AgentConversationId,
579
- records: readonly ConversationRecord[],
580
- ) => Promise<void>;
581
- }
582
-
583
- class DefaultAgentConversationManager implements AgentConversationManager {
584
- private readonly live = new Map<AgentConversationId, AgentConversation>();
585
- private readonly openings = new Map<AgentConversationId, Promise<OpenOwnedAgentConversationResult>>();
586
- private readonly meteringSetupLocks = new Map<AgentConversationId, Promise<void>>();
587
- private readonly detachedMeteringBarriers = new Map<AgentConversationId, Promise<void>>();
588
- private agentMeteringBarrier: Promise<void> | undefined;
589
-
590
- constructor(private readonly agent: Agent, private readonly settings: ManagerSettings) {}
591
-
592
- async create(config: CreateAgentConversationConfig = {}): Promise<AgentConversation> {
593
- const id = config.id ?? createAgentConversationId();
594
- const participants = normalizeParticipants(config.participants);
595
- // Validate caller input before the durable row: a mistake must not orphan a
596
- // conversation, and must not be recorded as a provider-session failure.
597
- this.prepareStart({ ...config, providerSession: "new" });
598
- await this.agent.persistence.conversations.create({
599
- agentSessionId: this.agent.id,
600
- agentConversationId: id,
601
- participants,
602
- ...(config.title !== undefined ? { title: config.title } : {}),
603
- ...(config.metadata !== undefined ? { metadata: config.metadata } : {}),
604
- });
605
- const attemptId = `provider-create-${randomUUID()}`;
606
- try {
607
- return await this.start(id, participants, {
608
- ...config,
609
- providerSession: "new",
610
- });
611
- } catch (error) {
612
- return await this.throwCreateFailure(id, attemptId, error);
613
- }
614
- }
615
-
616
- async open(
617
- id: AgentConversationId,
618
- config: OpenAgentConversationConfig = {},
619
- ): Promise<OpenOwnedAgentConversationResult> {
620
- const existing = this.live.get(id);
621
- if (existing && existing.state.phase !== "stopped") {
622
- return Object.freeze({ conversation: existing, providerSession: "already_open" });
623
- }
624
- const pending = this.openings.get(id);
625
- if (pending) return await pending;
626
- const opening = this.openOnce(id, config);
627
- this.openings.set(id, opening);
628
- try {
629
- return await opening;
630
- } finally {
631
- if (this.openings.get(id) === opening) this.openings.delete(id);
632
- }
633
- }
634
-
635
- private async openOnce(
636
- id: AgentConversationId,
637
- config: OpenAgentConversationConfig,
638
- ): Promise<OpenOwnedAgentConversationResult> {
639
- const summary = await this.agent.persistence.conversations.get(id);
640
- if (!summary || summary.deletedAt) throw new Error(`unknown active conversation: ${id}`);
641
- const active = await this.agent.persistence.providerSessions.active(id);
642
- if (active && config.adapterId && config.adapterId !== active.adapterId) {
643
- throw new Error(
644
- `conversation ${id} is active on ${active.adapterId}; use a conversation switch instead of loading it with ${config.adapterId}`,
645
- );
646
- }
647
- const startConfig = {
648
- ...config,
649
- runtime: {
650
- ...(summary.title ? { title: summary.title } : {}),
651
- ...config.runtime,
652
- },
653
- adapterId: config.adapterId ?? active?.adapterId,
654
- };
655
- // Validate caller input before the recorded region so a configuration mistake is not
656
- // persisted as a provider-session failure.
657
- this.prepareStart({ ...startConfig, providerSession: active ? "load" : "new" });
658
- const attemptId = active ? `provider-load-${randomUUID()}` : `provider-create-${randomUUID()}`;
659
- try {
660
- const conversation = await this.start(id, summary.participants, {
661
- ...startConfig,
662
- providerSession: active ? "load" : "new",
663
- internalSessionId: active?.internalSessionId,
664
- });
665
- return Object.freeze({
666
- conversation,
667
- providerSession: active ? "loaded" : "new",
668
- });
669
- } catch (error) {
670
- // No recorded mapping means this open was creating a thread, not loading one.
671
- if (!active) return await this.throwCreateFailure(id, attemptId, error);
672
- const recovery = this.settings.checkpointing?.recovery;
673
- const classification = classifyProviderSessionLoadError(error, recovery?.isMissingProviderSession);
674
- const recorded = await this.recordConversationError({
675
- agentConversationId: id,
676
- attemptId,
677
- source: "provider_session",
678
- code: classification.code,
679
- recoverability: classification.recoverability,
680
- message: "The provider session could not be loaded.",
681
- transitionId: attemptId,
682
- internalSessionId: active.internalSessionId,
683
- details: providerSessionErrorDetails(error),
684
- });
685
- const structuredError = (): ProviderSessionError => new ProviderSessionError({
686
- agentSessionId: this.agent.id,
687
- agentConversationId: id,
688
- attemptId,
689
- internalSessionId: active.internalSessionId,
690
- code: classification.code,
691
- source: "provider_session",
692
- recoverability: classification.recoverability,
693
- ...(recorded.record ? { recordId: recorded.record.recordId } : {}),
694
- ...(recorded.recordingError ? { recordingError: recorded.recordingError } : {}),
695
- cause: error,
696
- });
697
- if (recovery?.onLoadFailure !== "recover" || !classification.missing) throw structuredError();
698
- config.onRecoveryProgress?.({ stage: "load_failed" });
699
- config.onRecoveryProgress?.({ stage: "loading_checkpoint" });
700
- const checkpoint = await this.agent.persistence.recoveryCheckpoints?.latest(id);
701
- if (!checkpoint) throw structuredError();
702
- config.onRecoveryProgress?.({ stage: "loading_checkpoint", checkpointId: checkpoint.checkpointId });
703
- const recoveryAttemptId = `recovery-${randomUUID()}`;
704
- try {
705
- const seed = await buildRecoverySeed(
706
- this.agent.persistence.messages,
707
- id,
708
- checkpoint,
709
- summary.latestSequence,
710
- recovery,
711
- );
712
- config.onRecoveryProgress?.({ stage: "creating_session", checkpointId: checkpoint.checkpointId });
713
- const conversation = await this.start(id, summary.participants, {
714
- ...startConfig,
715
- providerSession: "new",
716
- });
717
- try {
718
- config.onRecoveryProgress?.({ stage: "seeding", checkpointId: checkpoint.checkpointId });
719
- await conversation.seedRecoveryContext(seed.prompt);
720
- const acknowledgement = await this.persistProviderSession(conversation, id, {
721
- transitionId: recoveryAttemptId,
722
- metadata: JSON.stringify({
723
- recoveryCheckpointId: checkpoint.checkpointId,
724
- previousInternalSessionId: active.internalSessionId,
725
- recoveredThroughSequence: seed.recoveredThroughSequence,
726
- }),
727
- }, true);
728
- conversation.acknowledgeProviderAttachment(acknowledgement);
729
- } catch (recoveryError) {
730
- this.live.delete(id);
731
- await conversation.stop().catch(() => undefined);
732
- throw recoveryError;
733
- }
734
- const result: ConversationRecoveryResult = Object.freeze({
735
- checkpointId: checkpoint.checkpointId,
736
- coveredSequence: checkpoint.coveredSequence,
737
- recoveredThroughSequence: seed.recoveredThroughSequence,
738
- previousInternalSessionId: active.internalSessionId,
739
- newInternalSessionId: conversation.internalSessionId!,
740
- });
741
- config.onRecoveryProgress?.({ stage: "completed", checkpointId: checkpoint.checkpointId });
742
- return Object.freeze({ conversation, providerSession: "recovered", recovery: result });
743
- } catch (recoveryError) {
744
- // A recovery failure is a distinct root cause from the load failure already
745
- // recorded above; it prevents the logical conversation from reopening.
746
- const recoveryRecorded = await this.recordConversationError({
747
- agentConversationId: id,
748
- attemptId: recoveryAttemptId,
749
- source: "recovery",
750
- code: "recovery_failed",
751
- recoverability: "recoverable",
752
- message: "The conversation could not be recovered from its checkpoint.",
753
- transitionId: recoveryAttemptId,
754
- internalSessionId: active.internalSessionId,
755
- });
756
- throw new ProviderSessionError({
757
- agentSessionId: this.agent.id,
758
- agentConversationId: id,
759
- attemptId: recoveryAttemptId,
760
- internalSessionId: active.internalSessionId,
761
- code: "recovery_failed",
762
- source: "recovery",
763
- recoverability: "recoverable",
764
- message: "The conversation could not be recovered from its checkpoint.",
765
- ...(recoveryRecorded.record ? { recordId: recoveryRecorded.record.recordId } : {}),
766
- ...(recoveryRecorded.recordingError ? { recordingError: recoveryRecorded.recordingError } : {}),
767
- cause: recoveryError,
768
- });
769
- }
770
- }
771
- }
772
-
773
- async get(id: AgentConversationId): Promise<AgentConversationSummary | null> {
774
- return await this.agent.persistence.conversations.get(id);
775
- }
776
-
777
- async list(options?: ConversationListOptions): Promise<ConversationPage> {
778
- return await this.agent.persistence.conversations.list(options);
779
- }
780
-
781
- async listPreviews(options?: ConversationListOptions): Promise<ConversationPreviewPage> {
782
- if (!this.agent.persistence.conversations.listPreviews) {
783
- throw new Error("conversation previews are unavailable on this persistence backend");
784
- }
785
- return await this.agent.persistence.conversations.listPreviews(options);
786
- }
787
-
788
- async delete(id: AgentConversationId, deletedAt?: string): Promise<void> {
789
- const live = this.live.get(id);
790
- if (live) await live.stop();
791
- this.live.delete(id);
792
- await this.agent.persistence.conversations.delete(id, deletedAt);
793
- }
794
-
795
- async appendAssistantMessage(
796
- id: AgentConversationId,
797
- input: AppendAssistantMessageInput,
798
- ): Promise<MessageRecord> {
799
- if (typeof input.text !== "string" || !input.text.trim()) {
800
- throw new Error("assistant message text cannot be blank");
801
- }
802
- const level = this.settings.capture.message;
803
- if (level !== "content" && level !== "raw") {
804
- throw new Error(
805
- `appending an assistant message requires message capture "content" or "raw", not "${level}"`,
806
- );
807
- }
808
- const summary = await this.agent.persistence.conversations.get(id);
809
- if (!summary || summary.deletedAt) throw new Error(`unknown active conversation: ${id}`);
810
- const appendId = `append-${randomUUID()}`;
811
- const [record] = await persistConversationObservations(this.agent, this.settings, [{
812
- recordId: `${appendId}:assistant`,
813
- agentSessionId: this.agent.id,
814
- agentConversationId: id,
815
- kind: "message",
816
- timestamp: new Date().toISOString(),
817
- role: "assistant",
818
- logicalMessageId: `message:${appendId}:assistant`,
819
- ...(input.consumerMetadata !== undefined ? { consumerMetadata: input.consumerMetadata } : {}),
820
- content: input.text,
821
- status: "completed",
822
- metadata: JSON.stringify({ origin: OUT_OF_BAND_MESSAGE_ORIGIN, appendId }),
823
- }]);
824
- if (record?.kind !== "message") throw new Error("assistant message was not persisted");
825
- await updateConversationIdentity(this.agent, this.settings, id, [record]);
826
- return record;
827
- }
828
-
829
- async stopAll(): Promise<void> {
830
- await Promise.allSettled([...this.openings.values()]);
831
- const conversations = [...this.live.values()];
832
- this.live.clear();
833
- await Promise.allSettled(conversations.map((conversation) => conversation.stop()));
834
- }
835
-
836
- async beginInternalInferenceMetering(
837
- attempt: InternalInferenceSnapshot,
838
- session: { readonly internalSessionId: string; readonly model: string | null },
839
- ): Promise<import("./internal-inference/contracts.ts").InternalInferenceMeteringOperation | null> {
840
- const conversationId = attempt.agentConversationId;
841
- const releaseSetup = conversationId
842
- ? await this.acquireMeteringSetupLock(conversationId)
843
- : () => {};
844
- let barrier: Promise<void> | undefined;
845
- let releaseBarrier = () => {};
846
- try {
847
- const conversation = conversationId ? this.live.get(conversationId) : undefined;
848
- if (conversation && conversation.state.phase !== "stopped") {
849
- const operation = await conversation.beginDetachedMetering({
850
- operationId: attempt.id,
851
- operationKind: internalInferenceMeteringKind(attempt.purpose),
852
- internalSessionId: session.internalSessionId,
853
- model: session.model,
854
- });
855
- let closed = false;
856
- releaseSetup();
857
- return {
858
- close: async ({ outcome, result, error }) => {
859
- if (closed) throw new Error(`internal inference metering already closed: ${attempt.id}`);
860
- closed = true;
861
- return await conversation.closeDetachedMetering(operation, {
862
- outcome,
863
- usage: result?.usage ?? null,
864
- ...(error ? { usageFailureReason: String(error) } : {}),
865
- });
866
- },
867
- settled() {},
868
- };
869
- }
870
-
871
- const previous = conversationId
872
- ? this.detachedMeteringBarriers.get(conversationId) ?? Promise.resolve()
873
- : this.agentMeteringBarrier ?? Promise.resolve();
874
- const ownBarrier = new Promise<void>((resolve) => { releaseBarrier = resolve; });
875
- barrier = previous.then(() => ownBarrier);
876
- if (conversationId) this.detachedMeteringBarriers.set(conversationId, barrier);
877
- else this.agentMeteringBarrier = barrier;
878
- releaseSetup();
879
- // Detached operations for one closed conversation must restore and commit in order.
880
- // Otherwise two workers can derive the same next operation count from one snapshot.
881
- await previous;
882
- const persisted = conversationId
883
- ? await this.agent.persistence.metering.state(conversationId)
884
- : await this.agent.persistence.metering.agentState(this.agent.id);
885
- const meteringConfig = this.settings.defaults.metering;
886
- const engine = new MeteringEngine({
887
- agentSessionId: this.agent.id,
888
- adapterId: attempt.adapterId,
889
- enforcement: meteringConfig?.enforcement ?? "best_effort",
890
- pricing: meteringConfig?.pricing ?? createModelsDevResolver(),
891
- ...(persisted ? { initialState: persisted.state } : {}),
892
- createdActiveThread: false,
893
- ...(meteringConfig?.counterInterpretation
894
- ? { counterInterpretation: meteringConfig.counterInterpretation }
895
- : {}),
896
- ...(meteringConfig?.inferenceSource
897
- ? { inferenceSource: meteringConfig.inferenceSource }
898
- : {}),
899
- });
900
- const operation = await engine.openDetached({
901
- operationId: attempt.id,
902
- operationKind: internalInferenceMeteringKind(attempt.purpose),
903
- internalSessionId: session.internalSessionId,
904
- providerId: null,
905
- model: session.model,
906
- });
907
- let closed = false;
908
- let settled = false;
909
- return {
910
- close: async ({ outcome, result, error }) => {
911
- if (closed) throw new Error(`internal inference metering already closed: ${attempt.id}`);
912
- closed = true;
913
- return await engine.closeDetached(operation, {
914
- outcome,
915
- reportedCumulative: result?.usage ?? null,
916
- ...(error ? { usageFailureReason: String(error) } : {}),
917
- contextAfter: null,
918
- providerCostAfter: null,
919
- });
920
- },
921
- settled: () => {
922
- if (settled) return;
923
- settled = true;
924
- if (conversationId && this.detachedMeteringBarriers.get(conversationId) === barrier) {
925
- this.detachedMeteringBarriers.delete(conversationId);
926
- } else if (!conversationId && this.agentMeteringBarrier === barrier) {
927
- this.agentMeteringBarrier = undefined;
928
- }
929
- releaseBarrier();
930
- },
931
- };
932
- } catch (error) {
933
- releaseSetup();
934
- if (barrier && conversationId && this.detachedMeteringBarriers.get(conversationId) === barrier) {
935
- this.detachedMeteringBarriers.delete(conversationId);
936
- } else if (barrier && !conversationId && this.agentMeteringBarrier === barrier) {
937
- this.agentMeteringBarrier = undefined;
938
- }
939
- releaseBarrier();
940
- throw error;
941
- }
942
- }
943
-
944
- private async start(
945
- id: AgentConversationId,
946
- participants: readonly ParticipantRef[],
947
- config: (CreateAgentConversationConfig | OpenAgentConversationConfig) & {
948
- readonly providerSession: "new" | "load";
949
- readonly internalSessionId?: string;
950
- },
951
- ): Promise<AgentConversation> {
952
- const releaseSetup = await this.acquireMeteringSetupLock(id);
953
- let conversation: AgentConversation | undefined;
954
- try {
955
- const adapterId = this.resolveAdapterId(config.adapterId);
956
- const adapter = this.agent.adapters.require(adapterId);
957
- const runtime = { ...this.settings.defaults, ...config.runtime };
958
- await this.detachedMeteringBarriers.get(id);
959
- const persistedMetering = await this.agent.persistence.metering.state(id);
960
- const lifecycle = new PersistedConversationLifecycle(
961
- this.agent,
962
- id,
963
- participants,
964
- this.settings,
965
- );
966
- conversation = await AgentConversation.create({
967
- ...runtime,
968
- ...(persistedMetering
969
- ? { metering: { ...runtime.metering, initialState: persistedMetering.state } }
970
- : {}),
971
- ...("title" in config && config.title !== undefined ? { title: config.title } : {}),
972
- adapter,
973
- adapterId,
974
- agentSessionId: this.agent.id,
975
- ownerAgentSessionId: this.agent.id,
976
- agentConversationId: id,
977
- participants,
978
- ownerLifecycle: lifecycle,
979
- mode: config.mode ?? runtime.mode,
980
- ...(config.mcpServers ? { mcpServers: [...config.mcpServers] } : {}),
981
- providerSession: config.providerSession === "load"
982
- ? { kind: "load", internalSessionId: config.internalSessionId!, onFailure: "error" }
983
- : { kind: "new" },
984
- persistence: false,
985
- });
986
- const openedConversation = conversation;
987
- this.live.set(id, openedConversation);
988
- openedConversation.subscribe((notification) => {
989
- if (notification.event.kind === "state_changed" && notification.event.state.phase === "stopped") {
990
- // The stopped state is published before the active turn finishes its
991
- // error/finalization path. Keep it discoverable to stopAll() until stop()
992
- // has drained those writes, or Agent.close() may close SQLite too early.
993
- void openedConversation.stop().then(() => {
994
- if (this.live.get(id) === openedConversation) this.live.delete(id);
995
- }, () => {
996
- if (this.live.get(id) === openedConversation) this.live.delete(id);
997
- });
998
- }
999
- });
1000
- return conversation;
1001
- } catch (error) {
1002
- this.live.delete(id);
1003
- await conversation?.stop().catch(() => undefined);
1004
- throw error;
1005
- } finally {
1006
- releaseSetup();
1007
- }
1008
- }
1009
-
1010
- private async acquireMeteringSetupLock(id: AgentConversationId): Promise<() => void> {
1011
- const previous = this.meteringSetupLocks.get(id) ?? Promise.resolve();
1012
- let releaseGate!: () => void;
1013
- const gate = new Promise<void>((resolve) => { releaseGate = resolve; });
1014
- const current = previous.then(() => gate);
1015
- this.meteringSetupLocks.set(id, current);
1016
- await previous;
1017
- let released = false;
1018
- return () => {
1019
- if (released) return;
1020
- released = true;
1021
- if (this.meteringSetupLocks.get(id) === current) this.meteringSetupLocks.delete(id);
1022
- releaseGate();
1023
- };
1024
- }
1025
-
1026
- private resolveAdapterId(requested?: string): string {
1027
- if (requested) return requested;
1028
- if (this.settings.defaultAdapterId) return this.settings.defaultAdapterId;
1029
- const registrations = this.agent.adapters.list();
1030
- if (registrations.length === 1) return registrations[0]!.id;
1031
- throw new Error("adapterId is required when an Agent has no unique default adapter");
1032
- }
1033
-
1034
- /**
1035
- * Persist one conversation error record and its audit intent in a single transaction,
1036
- * then publish it through the committed-record bus.
1037
- *
1038
- * A recording failure never replaces the primary provider diagnosis: it is returned so
1039
- * the caller can attach it to the structured exception instead.
1040
- */
1041
- private async recordConversationError(input: {
1042
- readonly agentConversationId: AgentConversationId;
1043
- readonly attemptId: string;
1044
- readonly source: ConversationErrorSource;
1045
- readonly code: string;
1046
- readonly recoverability: ConversationErrorRecoverability;
1047
- readonly message?: string;
1048
- readonly operationId?: string;
1049
- readonly transitionId?: string;
1050
- readonly internalSessionId?: string;
1051
- readonly details?: ConversationErrorDetails;
1052
- }): Promise<{ readonly record?: ConversationRecord; readonly recordingError?: Error }> {
1053
- const record: NewConversationRecord = {
1054
- recordId: `${input.attemptId}:error`,
1055
- agentSessionId: this.agent.id,
1056
- agentConversationId: input.agentConversationId,
1057
- kind: "error",
1058
- timestamp: new Date().toISOString(),
1059
- source: input.source,
1060
- code: input.code,
1061
- recoverability: input.recoverability,
1062
- ...(input.message === undefined ? {} : { message: input.message }),
1063
- ...(input.operationId === undefined ? {} : { operationId: input.operationId }),
1064
- ...(input.transitionId === undefined ? {} : { transitionId: input.transitionId }),
1065
- ...(input.internalSessionId === undefined ? {} : { internalSessionId: input.internalSessionId }),
1066
- ...(input.details === undefined ? {} : { details: input.details }),
1067
- };
1068
- const level = this.settings.capture.error;
1069
- const audit = this.settings.auditLog;
1070
- let persisted: ConversationRecord | undefined;
1071
- try {
1072
- await this.agent.persistence.transaction(async (persistence) => {
1073
- if (level !== "none") {
1074
- persisted = await persistence.records.append(captureRuntimeRecord(record, level));
1075
- }
1076
- if (audit) {
1077
- await enqueueAuditObservation(persistence, {
1078
- scope: "conversation",
1079
- sourceObservationId: record.recordId,
1080
- ...(input.operationId === undefined ? {} : { operationId: input.operationId }),
1081
- record,
1082
- }, audit);
1083
- }
1084
- });
1085
- } catch (error) {
1086
- return { recordingError: error instanceof Error ? error : new Error(String(error)) };
1087
- }
1088
- if (persisted) this.agent.publishCommittedRecords([persisted]);
1089
- if (audit) this.agent.audit?.notifyPending();
1090
- return persisted ? { record: persisted } : {};
1091
- }
1092
-
1093
- /**
1094
- * Validate caller-supplied start configuration before any durable write or recorded
1095
- * region.
1096
- *
1097
- * Adapter resolution and mode/provider-thread compatibility are caller mistakes, not
1098
- * conversation failures. Persisting them as provider-session errors would violate the
1099
- * spec and mislead a UI (for example, `retryable` for an adapter that can never resolve).
1100
- */
1101
- private prepareStart(config: {
1102
- readonly adapterId?: string;
1103
- readonly mode?: AgentMode;
1104
- readonly runtime?: AgentConversationRuntimeDefaults;
1105
- readonly providerSession: "new" | "load";
1106
- }): void {
1107
- const adapterId = this.resolveAdapterId(config.adapterId);
1108
- this.agent.adapters.require(adapterId);
1109
- const mode = config.mode ?? config.runtime?.mode ?? this.settings.defaults.mode;
1110
- if (mode === "degraded" && config.providerSession === "load") {
1111
- throw new Error("providerSession.kind=load requires ACP (normal) mode");
1112
- }
1113
- }
1114
-
1115
- /**
1116
- * Record a failed provider-session creation and throw the structured error. Used where
1117
- * the durable conversation row already exists, so the caller always learns which logical
1118
- * conversation holds the error.
1119
- */
1120
- private async throwCreateFailure(
1121
- id: AgentConversationId,
1122
- attemptId: string,
1123
- error: unknown,
1124
- ): Promise<never> {
1125
- const recorded = await this.recordConversationError({
1126
- agentConversationId: id,
1127
- attemptId,
1128
- source: "provider_session",
1129
- code: "provider_session_create_failed",
1130
- recoverability: "retryable",
1131
- message: "The provider session could not be created.",
1132
- transitionId: attemptId,
1133
- });
1134
- throw new ProviderSessionError({
1135
- agentSessionId: this.agent.id,
1136
- agentConversationId: id,
1137
- attemptId,
1138
- code: "provider_session_create_failed",
1139
- source: "provider_session",
1140
- recoverability: "retryable",
1141
- message: "The provider session could not be created.",
1142
- ...(recorded.record ? { recordId: recorded.record.recordId } : {}),
1143
- ...(recorded.recordingError ? { recordingError: recorded.recordingError } : {}),
1144
- cause: error,
1145
- });
1146
- }
1147
-
1148
- private async persistProviderSession(
1149
- conversation: AgentConversation,
1150
- id: AgentConversationId,
1151
- extra: { readonly transitionId?: string; readonly metadata?: string } = {},
1152
- newContext = false,
1153
- ): Promise<ProviderAttachmentCommitAcknowledgement> {
1154
- const attachment = conversation.providerAttachmentState;
1155
- if (attachment.kind !== "runtime_only") {
1156
- throw new Error("provider attachment is not awaiting persistence");
1157
- }
1158
- const descriptor = attachment.descriptor;
1159
- const providerSessionRecordId = `provider-${randomUUID()}`;
1160
- await this.agent.persistence.transaction(async (persistence) => {
1161
- if (newContext) await persistence.identityDelivery?.reset(id, descriptor.internalSessionId);
1162
- await persistence.providerSessions.append({
1163
- providerSessionRecordId,
1164
- agentConversationId: id,
1165
- internalSessionId: descriptor.internalSessionId,
1166
- adapterId: descriptor.adapterId,
1167
- mode: descriptor.mode,
1168
- ...(descriptor.model ? { model: descriptor.model } : {}),
1169
- activatedAt: descriptor.acquiredAt,
1170
- ...extra,
1171
- });
1172
- });
1173
- return Object.freeze({
1174
- attachmentAttemptId: descriptor.attachmentAttemptId,
1175
- providerSessionRecordId,
1176
- });
1177
- }
1178
- }
1179
-
1180
- class PersistedConversationLifecycle implements AgentConversationOwnerLifecycle {
1181
- constructor(
1182
- private readonly agent: Agent,
1183
- private readonly conversationId: AgentConversationId,
1184
- private readonly initialParticipants: readonly ParticipantRef[],
1185
- private readonly settings: ManagerSettings,
1186
- ) {}
1187
-
1188
- async beforePrompt(input: OwnedPromptInput) {
1189
- // A combined prompt records each original message as it was sent, under the same operation.
1190
- const parts = input.parts ?? [{
1191
- id: input.operationId,
1192
- text: input.text,
1193
- ...(input.participantId ? { participantId: input.participantId } : {}),
1194
- ...(input.consumerMetadata !== undefined ? { consumerMetadata: input.consumerMetadata } : {}),
1195
- }];
1196
- const participants: ParticipantRef[] = [];
1197
- for (const part of parts) participants.push(await this.resolveParticipant(part.participantId));
1198
- const participant = participants[0]!;
1199
- const identity = await this.agent.identity.load({
1200
- agentSessionId: this.agent.id,
1201
- agentConversationId: this.conversationId,
1202
- targetProviderContextId: input.targetProviderContextId,
1203
- participant,
1204
- prompt: input.text,
1205
- consistency: this.settings.identityConsistency,
1206
- ...(this.settings.identityTimeoutMs !== undefined
1207
- ? { timeoutMs: this.settings.identityTimeoutMs }
1208
- : {}),
1209
- });
1210
- const records = await this.appendMessages(parts.map((part, index): NewConversationRecord => ({
1211
- recordId: index === 0 ? `${input.operationId}:user` : `${input.operationId}:user:${index + 1}`,
1212
- agentSessionId: this.agent.id,
1213
- agentConversationId: this.conversationId,
1214
- kind: "message",
1215
- timestamp: new Date().toISOString(),
1216
- role: "user",
1217
- participantId: participants[index]!.id,
1218
- ...(part.consumerMetadata !== undefined ? { consumerMetadata: part.consumerMetadata } : {}),
1219
- content: part.text,
1220
- status: "completed",
1221
- metadata: JSON.stringify({ operationId: input.operationId }),
1222
- })));
1223
- await this.updateIdentity(records);
1224
- // Read after the user record commits so a concurrent append falls in this turn or the next.
1225
- const outOfBand = records[0]
1226
- ? await pendingOutOfBandMessages(
1227
- this.agent.persistence,
1228
- this.conversationId,
1229
- input.targetProviderContextId,
1230
- records[0].sequence,
1231
- )
1232
- : [];
1233
- return Object.freeze({
1234
- providerText: composeProviderPrompt(input.text, identity.promptPreamble, outOfBand),
1235
- participant,
1236
- participants: Object.freeze(participants),
1237
- ...(identity.deliveryReceipt ? { identityDeliveryReceipt: identity.deliveryReceipt } : {}),
1238
- });
1239
- }
1240
-
1241
- async afterPrompt(input: OwnedPromptCompleted): Promise<OwnedPromptCommitResult> {
1242
- const timestamp = new Date().toISOString();
1243
- const status = input.result.status === "error" ? "failed" : input.result.status;
1244
- const records = input.result.messages.map((message, index): NewConversationRecord => ({
1245
- recordId: `${input.operationId}:assistant:${index + 1}`,
1246
- agentSessionId: this.agent.id,
1247
- agentConversationId: this.conversationId,
1248
- kind: "message",
1249
- timestamp,
1250
- role: "assistant",
1251
- logicalMessageId: `message:${input.operationId}:assistant:${index + 1}`,
1252
- content: message.text,
1253
- status,
1254
- metadata: JSON.stringify({
1255
- operationId: input.operationId,
1256
- ...(message.messageId ? { providerMessageId: message.messageId } : {}),
1257
- }),
1258
- }));
1259
- const persisted: ConversationRecord[] = [];
1260
- let providerAttachment: ProviderAttachmentCommitAcknowledgement | undefined;
1261
- await this.agent.persistence.transaction(async (persistence) => {
1262
- await this.persistObservationsInTransaction(persistence, records, true, persisted);
1263
- if (status === "completed" && input.providerAttachment.kind === "runtime_only") {
1264
- const descriptor = input.providerAttachment.descriptor;
1265
- const providerSessionRecordId = `provider-${randomUUID()}`;
1266
- await persistence.identityDelivery?.reset(
1267
- this.conversationId,
1268
- descriptor.internalSessionId,
1269
- );
1270
- await persistence.providerSessions.append({
1271
- providerSessionRecordId,
1272
- agentConversationId: this.conversationId,
1273
- internalSessionId: descriptor.internalSessionId,
1274
- adapterId: descriptor.adapterId,
1275
- mode: descriptor.mode,
1276
- ...(descriptor.model ? { model: descriptor.model } : {}),
1277
- activatedAt: descriptor.acquiredAt,
1278
- ...(descriptor.transitionId ? { transitionId: descriptor.transitionId } : {}),
1279
- });
1280
- providerAttachment = Object.freeze({
1281
- attachmentAttemptId: descriptor.attachmentAttemptId,
1282
- providerSessionRecordId,
1283
- });
1284
- }
1285
- });
1286
- this.agent.publishCommittedRecords(persisted);
1287
- if (this.settings.auditLog) this.agent.audit?.notifyPending();
1288
- const commit: OwnedPromptCommitResult = Object.freeze({
1289
- ...(providerAttachment ? { providerAttachment } : {}),
1290
- });
1291
- try {
1292
- await this.updateIdentity(Object.freeze(persisted));
1293
- if (status === "completed" && input.identityDeliveryReceipt) {
1294
- await this.agent.identity.delivered?.(input.identityDeliveryReceipt);
1295
- }
1296
- if (status === "completed") {
1297
- await this.agent.checkpointing?.afterSuccessfulResponse(this.conversationId);
1298
- }
1299
- } catch (error) {
1300
- throw new OwnedPromptPostCommitError(commit, error);
1301
- }
1302
- return commit;
1303
- }
1304
-
1305
- async promptFailed(input: OwnedPromptFailed): Promise<void> {
1306
- const timestamp = new Date().toISOString();
1307
- const records = input.messages.map((message, index): NewConversationRecord => ({
1308
- recordId: `${input.operationId}:assistant:${index + 1}`,
1309
- agentSessionId: this.agent.id,
1310
- agentConversationId: this.conversationId,
1311
- kind: "message",
1312
- timestamp,
1313
- role: "assistant",
1314
- logicalMessageId: `message:${input.operationId}:assistant:${index + 1}`,
1315
- content: message.text,
1316
- status: "failed",
1317
- metadata: JSON.stringify({
1318
- operationId: input.operationId,
1319
- ...(message.messageId ? { providerMessageId: message.messageId } : {}),
1320
- }),
1321
- }));
1322
- await this.updateIdentity(await this.appendMessages(records));
1323
- }
1324
-
1325
- resolveAdapter(adapterId: string) {
1326
- return this.agent.adapters.require(adapterId);
1327
- }
1328
-
1329
- async transitionActivated(input: {
1330
- readonly transitionId: string;
1331
- readonly agentConversationId: AgentConversationId;
1332
- readonly internalSessionId: string;
1333
- readonly adapterId: string;
1334
- readonly mode: AgentMode;
1335
- readonly model?: string;
1336
- readonly activatedAt: string;
1337
- }): Promise<void> {
1338
- await this.agent.persistence.transaction(async (persistence) => {
1339
- await persistence.identityDelivery?.reset(input.agentConversationId, input.internalSessionId);
1340
- await persistence.providerSessions.append({
1341
- providerSessionRecordId: `provider-${randomUUID()}`,
1342
- agentConversationId: input.agentConversationId,
1343
- internalSessionId: input.internalSessionId,
1344
- adapterId: input.adapterId,
1345
- mode: input.mode,
1346
- ...(input.model ? { model: input.model } : {}),
1347
- activatedAt: input.activatedAt,
1348
- transitionId: input.transitionId,
1349
- });
1350
- });
1351
- }
1352
-
1353
- async record(record: NewConversationRecord): Promise<void> {
1354
- const streamingSnapshot = record.kind === "message" && record.status === "in_progress";
1355
- const persisted = await this.persistObservations([record], !streamingSnapshot);
1356
- // A streaming snapshot is a display revision, not a second completed response.
1357
- if (!streamingSnapshot) {
1358
- await this.updateIdentity(persisted);
1359
- }
1360
- }
1361
-
1362
- async meteringRecorded(record: OperationMeteringRecord): Promise<void> {
1363
- const level = this.settings.capture.metering;
1364
- let reference: ConversationRecord | undefined;
1365
- await this.agent.persistence.transaction(async (persistence) => {
1366
- await persistence.metering.commit({
1367
- agentConversationId: this.conversationId,
1368
- record,
1369
- meteringRecords: this.settings.meteringRecords,
1370
- });
1371
- const timelineRecord: NewConversationRecord = {
1372
- recordId: `${record.operationId}:metering`,
1373
- agentSessionId: this.agent.id,
1374
- agentConversationId: this.conversationId,
1375
- kind: "metering",
1376
- timestamp: new Date(record.completedAt).toISOString(),
1377
- operationId: record.operationId,
1378
- meteringRecordId: record.operationId,
1379
- status: record.usage.status === "metered" ? "available" : "unavailable",
1380
- metadata: JSON.stringify({ operationId: record.operationId }),
1381
- };
1382
- if (level !== "none") {
1383
- reference = await persistence.records.append(captureRuntimeRecord(timelineRecord, level));
1384
- }
1385
- if (this.settings.auditLog) {
1386
- await enqueueAuditObservation(persistence, {
1387
- scope: "conversation",
1388
- sourceObservationId: timelineRecord.recordId,
1389
- operationId: record.operationId,
1390
- record: timelineRecord,
1391
- meteringRecord: record,
1392
- }, this.settings.auditLog);
1393
- }
1394
- });
1395
- if (reference) this.agent.publishCommittedRecords([reference]);
1396
- if (this.settings.auditLog) this.agent.audit?.notifyPending();
1397
- if (reference) await this.updateIdentity([reference]);
1398
- }
1399
-
1400
- async meteringStateChanged(state: AgentSessionMeteringState): Promise<void> {
1401
- await this.agent.persistence.metering.saveState(this.conversationId, state);
1402
- }
1403
-
1404
- private async resolveParticipant(participantId?: string): Promise<ParticipantRef> {
1405
- const id = participantId
1406
- ?? (this.initialParticipants.length === 1
1407
- ? this.initialParticipants[0]!.id
1408
- : IMPLICIT_USER_PARTICIPANT_ID);
1409
- const existing = (await this.agent.persistence.conversations.get(this.conversationId))
1410
- ?.participants.find((participant) => participant.id === id);
1411
- if (existing) return existing;
1412
- return await this.agent.persistence.conversations.ensureParticipant(this.conversationId, {
1413
- id,
1414
- kind: "user",
1415
- });
1416
- }
1417
-
1418
- private async appendMessages(
1419
- records: readonly NewConversationRecord[],
1420
- ): Promise<readonly ConversationRecord[]> {
1421
- return await this.persistObservations(records);
1422
- }
1423
-
1424
- private async persistObservations(
1425
- records: readonly NewConversationRecord[],
1426
- audit = true,
1427
- ): Promise<readonly ConversationRecord[]> {
1428
- return await persistConversationObservations(this.agent, this.settings, records, audit);
1429
- }
1430
-
1431
- private async persistObservationsInTransaction(
1432
- persistence: PersistenceScope,
1433
- records: readonly NewConversationRecord[],
1434
- audit: boolean,
1435
- persisted: ConversationRecord[],
1436
- ): Promise<void> {
1437
- await persistObservationsInTransaction(this.settings, persistence, records, audit, persisted);
1438
- }
1439
-
1440
- private async updateIdentity(records: readonly ConversationRecord[]): Promise<void> {
1441
- await updateConversationIdentity(this.agent, this.settings, this.conversationId, records);
1442
- }
1443
- }
1444
-
1445
- async function updateConversationIdentity(
1446
- agent: Agent,
1447
- settings: ManagerSettings,
1448
- conversationId: AgentConversationId,
1449
- records: readonly ConversationRecord[],
1450
- ): Promise<void> {
1451
- await agent.identity.update({
1452
- agentSessionId: agent.id,
1453
- agentConversationId: conversationId,
1454
- records,
1455
- });
1456
- await settings.auditIdentityUpdate(conversationId, records);
1457
- }
1458
-
1459
- /** Persist canonical records and their audit intents in one transaction, then publish them. */
1460
- async function persistConversationObservations(
1461
- agent: Agent,
1462
- settings: ManagerSettings,
1463
- records: readonly NewConversationRecord[],
1464
- audit = true,
1465
- ): Promise<readonly ConversationRecord[]> {
1466
- if (records.length === 0) return Object.freeze([]);
1467
- if ((!audit || !settings.auditLog) && records.every((record) => {
1468
- if (record.kind !== "protocol") return settings.capture[record.kind] === "none";
1469
- return settings.capture.protocol.level === "none"
1470
- || !shouldCaptureProtocolMethod(settings.capture.protocol, record.method);
1471
- })) return Object.freeze([]);
1472
- const persisted: ConversationRecord[] = [];
1473
- await agent.persistence.transaction(async (persistence) => {
1474
- await persistObservationsInTransaction(settings, persistence, records, audit, persisted);
1475
- });
1476
- agent.publishCommittedRecords(persisted);
1477
- if (audit && settings.auditLog) agent.audit?.notifyPending();
1478
- return Object.freeze(persisted);
1479
- }
1480
-
1481
- async function persistObservationsInTransaction(
1482
- settings: ManagerSettings,
1483
- persistence: PersistenceScope,
1484
- records: readonly NewConversationRecord[],
1485
- audit: boolean,
1486
- persisted: ConversationRecord[],
1487
- ): Promise<void> {
1488
- for (const record of records) {
1489
- const level = record.kind === "protocol"
1490
- ? settings.capture.protocol.level
1491
- : settings.capture[record.kind];
1492
- const canonicalAccepted = level !== "none" && (
1493
- record.kind !== "protocol"
1494
- || shouldCaptureProtocolMethod(settings.capture.protocol, record.method)
1495
- );
1496
- if (canonicalAccepted) {
1497
- persisted.push(await persistence.records.append(captureRuntimeRecord(record, level)));
1498
- }
1499
- if (audit && settings.auditLog) {
1500
- await enqueueAuditObservation(persistence, {
1501
- scope: "conversation",
1502
- sourceObservationId: record.recordId,
1503
- operationId: operationIdFromMetadata(record.metadata),
1504
- record,
1505
- }, settings.auditLog);
1506
- }
1507
- }
1508
- }
1509
-
1510
- function normalizeParticipants(participants?: readonly ParticipantRef[]): readonly ParticipantRef[] {
1511
- const values = participants?.length
1512
- ? participants.map(normalizeParticipantRef)
1513
- : [{ id: IMPLICIT_USER_PARTICIPANT_ID, kind: "user" as const }];
1514
- const seen = new Set<string>();
1515
- for (const participant of values) {
1516
- if (seen.has(participant.id)) throw new Error(`duplicate participant id: ${participant.id}`);
1517
- seen.add(participant.id);
1518
- }
1519
- return Object.freeze(values);
1520
- }
1521
-
1522
- function internalInferenceMeteringKind(purpose: string): MeteredOperationKind {
1523
- if (
1524
- purpose === "conversation_checkpoint"
1525
- || purpose === "conversation_recovery"
1526
- || purpose === "identity_update"
1527
- ) return purpose;
1528
- return "internal_command";
1529
- }
1530
-
1531
- function captureRuntimeRecord(
1532
- record: NewConversationRecord,
1533
- level: RecordCaptureLevel,
1534
- ): NewConversationRecord {
1535
- if (record.kind === "error") {
1536
- // `metadata` omits the display message and details; `content` keeps the message but
1537
- // still omits details; `raw` retains the allow-listed details.
1538
- if (level === "raw") return record;
1539
- const { details: _details, message, ...rest } = record;
1540
- return level === "content"
1541
- ? { ...rest, ...(message === undefined ? {} : { message }) }
1542
- : rest;
1543
- }
1544
- if (level !== "metadata") return record;
1545
- switch (record.kind) {
1546
- case "message":
1547
- return { ...record, content: "" };
1548
- case "tool_call":
1549
- return {
1550
- recordId: record.recordId,
1551
- agentSessionId: record.agentSessionId,
1552
- agentConversationId: record.agentConversationId,
1553
- kind: record.kind,
1554
- timestamp: record.timestamp,
1555
- ...(record.metadata ? { metadata: record.metadata } : {}),
1556
- toolCallId: record.toolCallId,
1557
- state: record.state,
1558
- ...(record.name ? { name: record.name } : {}),
1559
- };
1560
- case "permission":
1561
- return {
1562
- recordId: record.recordId,
1563
- agentSessionId: record.agentSessionId,
1564
- agentConversationId: record.agentConversationId,
1565
- kind: record.kind,
1566
- timestamp: record.timestamp,
1567
- ...(record.metadata ? { metadata: record.metadata } : {}),
1568
- permissionId: record.permissionId,
1569
- state: record.state,
1570
- ...(record.outcome ? { outcome: record.outcome } : {}),
1571
- };
1572
- case "configuration":
1573
- return { ...record, value: undefined };
1574
- case "protocol":
1575
- return { ...record, message: undefined };
1576
- case "native_action":
1577
- case "agent_action":
1578
- return { ...record, input: undefined, output: undefined };
1579
- case "thinking":
1580
- return { ...record, content: "" };
1581
- case "activity":
1582
- return { ...record, content: undefined, data: undefined };
1583
- case "metering":
1584
- return record;
1585
- }
1586
- }
1587
-
1588
- async function enqueueAuditObservation(
1589
- persistence: PersistenceBackend | PersistenceScope,
1590
- observation: NormalizedAgentObservation,
1591
- config: ResolvedAgentAuditLogConfig,
1592
- ): Promise<void> {
1593
- const projected = projectAgentAuditObservation(observation, config.capture);
1594
- if (!projected) return;
1595
- if (!persistence.auditOutbox) throw new PersistenceCapabilityError("auditOutbox");
1596
- await persistence.auditOutbox.enqueue({
1597
- outboxId: `aud-${randomUUID()}`,
1598
- sourceObservationId: projected.sourceObservationId,
1599
- ...(projected.sourceRecordId ? { sourceRecordId: projected.sourceRecordId } : {}),
1600
- ...(projected.operationId ? { operationId: projected.operationId } : {}),
1601
- ...(projected.agentConversationId ? { agentConversationId: projected.agentConversationId } : {}),
1602
- occurredAt: projected.occurredAt,
1603
- kind: projected.kind,
1604
- captureLevel: projected.captureLevel,
1605
- captureFingerprint: config.captureFingerprint,
1606
- payload: projected.payload,
1607
- createdAt: new Date().toISOString(),
1608
- });
1609
- }
1610
-
1611
- /** Allow-listed machine-readable detail from a raw ACP error, when it exposes any. */
1612
- function providerSessionErrorDetails(error: unknown): ConversationErrorDetails | undefined {
1613
- const value = typeof error === "object" && error !== null
1614
- ? error as { code?: unknown; data?: unknown }
1615
- : null;
1616
- const data = typeof value?.data === "object" && value.data !== null
1617
- ? value.data as Record<string, unknown>
1618
- : undefined;
1619
- return buildConversationErrorDetails({
1620
- rpcCode: typeof value?.code === "number" ? value.code : undefined,
1621
- service: data?.service,
1622
- providerCode: data?.providerCode,
1623
- });
1624
- }
1625
-
1626
- function operationIdFromMetadata(metadata: string | undefined): string | undefined {
1627
- if (!metadata) return undefined;
1628
- try {
1629
- const value = JSON.parse(metadata) as { operationId?: unknown };
1630
- return typeof value.operationId === "string" && value.operationId ? value.operationId : undefined;
1631
- } catch {
1632
- return undefined;
1633
- }
1634
- }
1635
-
1636
- export { AgentAdapterRegistry, NoopAgentIdentityRuntime, composeIdentityPrompt };
1637
467
  export type { AgentAdapterRegistration, AgentIdentityRuntime, IdentityConsistency };