@qlairoslabs/acp-client 0.10.0 → 0.10.1

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.
package/src/agent.ts CHANGED
@@ -39,9 +39,13 @@ import {
39
39
  type ConversationListOptions,
40
40
  type ConversationPage,
41
41
  type ConversationPreviewPage,
42
+ type ConversationErrorDetails,
43
+ type ConversationErrorRecoverability,
44
+ type ConversationErrorSource,
42
45
  type ConversationRecord,
43
46
  type ConversationRecordCaptureConfig,
44
47
  type ConversationRecordCapturePolicy,
48
+ type MessageRecord,
45
49
  type MeteringRecordRetention,
46
50
  type NewConversationRecord,
47
51
  type ParticipantRef,
@@ -72,6 +76,14 @@ import type {
72
76
  OwnedPromptInput,
73
77
  } from "./agent-conversation-owner.ts";
74
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";
75
87
  import type {
76
88
  ProviderAttachmentCommitAcknowledgement,
77
89
  } from "./persistence/provider-attachment.ts";
@@ -91,7 +103,7 @@ import {
91
103
  ConversationCheckpointStrategy,
92
104
  CONVERSATION_CHECKPOINT_STRATEGY_ID,
93
105
  buildRecoverySeed,
94
- isMissingProviderSessionError,
106
+ classifyProviderSessionLoadError,
95
107
  resolveConversationCheckpointingConfig,
96
108
  type ConversationCheckpointingConfig,
97
109
  type ConversationRecoveryProgress,
@@ -186,6 +198,15 @@ export interface AgentConversationManager {
186
198
  list(options?: ConversationListOptions): Promise<ConversationPage>;
187
199
  listPreviews(options?: ConversationListOptions): Promise<ConversationPreviewPage>;
188
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>;
189
210
  }
190
211
 
191
212
  /** Durable owner of one agent identity, its adapters, identity runtime, and conversations. */
@@ -571,6 +592,9 @@ class DefaultAgentConversationManager implements AgentConversationManager {
571
592
  async create(config: CreateAgentConversationConfig = {}): Promise<AgentConversation> {
572
593
  const id = config.id ?? createAgentConversationId();
573
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" });
574
598
  await this.agent.persistence.conversations.create({
575
599
  agentSessionId: this.agent.id,
576
600
  agentConversationId: id,
@@ -578,10 +602,15 @@ class DefaultAgentConversationManager implements AgentConversationManager {
578
602
  ...(config.title !== undefined ? { title: config.title } : {}),
579
603
  ...(config.metadata !== undefined ? { metadata: config.metadata } : {}),
580
604
  });
581
- return await this.start(id, participants, {
582
- ...config,
583
- providerSession: "new",
584
- });
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
+ }
585
614
  }
586
615
 
587
616
  async open(
@@ -623,6 +652,10 @@ class DefaultAgentConversationManager implements AgentConversationManager {
623
652
  },
624
653
  adapterId: config.adapterId ?? active?.adapterId,
625
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()}`;
626
659
  try {
627
660
  const conversation = await this.start(id, summary.participants, {
628
661
  ...startConfig,
@@ -634,55 +667,106 @@ class DefaultAgentConversationManager implements AgentConversationManager {
634
667
  providerSession: active ? "loaded" : "new",
635
668
  });
636
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);
637
672
  const recovery = this.settings.checkpointing?.recovery;
638
- if (
639
- !active
640
- || recovery?.onLoadFailure !== "recover"
641
- || !isMissingProviderSessionError(error, recovery.isMissingProviderSession)
642
- ) throw error;
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();
643
698
  config.onRecoveryProgress?.({ stage: "load_failed" });
644
699
  config.onRecoveryProgress?.({ stage: "loading_checkpoint" });
645
700
  const checkpoint = await this.agent.persistence.recoveryCheckpoints?.latest(id);
646
- if (!checkpoint) throw error;
701
+ if (!checkpoint) throw structuredError();
647
702
  config.onRecoveryProgress?.({ stage: "loading_checkpoint", checkpointId: checkpoint.checkpointId });
648
- const seed = await buildRecoverySeed(
649
- this.agent.persistence.messages,
650
- id,
651
- checkpoint,
652
- summary.latestSequence,
653
- recovery,
654
- );
655
- config.onRecoveryProgress?.({ stage: "creating_session", checkpointId: checkpoint.checkpointId });
656
- const conversation = await this.start(id, summary.participants, {
657
- ...startConfig,
658
- providerSession: "new",
659
- });
703
+ const recoveryAttemptId = `recovery-${randomUUID()}`;
660
704
  try {
661
- config.onRecoveryProgress?.({ stage: "seeding", checkpointId: checkpoint.checkpointId });
662
- await conversation.seedRecoveryContext(seed.prompt);
663
- const acknowledgement = await this.persistProviderSession(conversation, id, {
664
- transitionId: `recovery-${randomUUID()}`,
665
- metadata: JSON.stringify({
666
- recoveryCheckpointId: checkpoint.checkpointId,
667
- previousInternalSessionId: active.internalSessionId,
668
- recoveredThroughSequence: seed.recoveredThroughSequence,
669
- }),
670
- }, true);
671
- conversation.acknowledgeProviderAttachment(acknowledgement);
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 });
672
743
  } catch (recoveryError) {
673
- this.live.delete(id);
674
- await conversation.stop().catch(() => undefined);
675
- throw 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
+ });
676
769
  }
677
- const result: ConversationRecoveryResult = Object.freeze({
678
- checkpointId: checkpoint.checkpointId,
679
- coveredSequence: checkpoint.coveredSequence,
680
- recoveredThroughSequence: seed.recoveredThroughSequence,
681
- previousInternalSessionId: active.internalSessionId,
682
- newInternalSessionId: conversation.internalSessionId!,
683
- });
684
- config.onRecoveryProgress?.({ stage: "completed", checkpointId: checkpoint.checkpointId });
685
- return Object.freeze({ conversation, providerSession: "recovered", recovery: result });
686
770
  }
687
771
  }
688
772
 
@@ -708,6 +792,40 @@ class DefaultAgentConversationManager implements AgentConversationManager {
708
792
  await this.agent.persistence.conversations.delete(id, deletedAt);
709
793
  }
710
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
+
711
829
  async stopAll(): Promise<void> {
712
830
  await Promise.allSettled([...this.openings.values()]);
713
831
  const conversations = [...this.live.values()];
@@ -913,6 +1031,120 @@ class DefaultAgentConversationManager implements AgentConversationManager {
913
1031
  throw new Error("adapterId is required when an Agent has no unique default adapter");
914
1032
  }
915
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
+
916
1148
  private async persistProviderSession(
917
1149
  conversation: AgentConversation,
918
1150
  id: AgentConversationId,
@@ -980,8 +1212,17 @@ class PersistedConversationLifecycle implements AgentConversationOwnerLifecycle
980
1212
  metadata: JSON.stringify({ operationId: input.operationId }),
981
1213
  }]);
982
1214
  await this.updateIdentity(records);
1215
+ // Read after the user record commits so a concurrent append falls in this turn or the next.
1216
+ const outOfBand = records[0]
1217
+ ? await pendingOutOfBandMessages(
1218
+ this.agent.persistence,
1219
+ this.conversationId,
1220
+ input.targetProviderContextId,
1221
+ records[0].sequence,
1222
+ )
1223
+ : [];
983
1224
  return Object.freeze({
984
- providerText: composeIdentityPrompt(input.text, identity),
1225
+ providerText: composeProviderPrompt(input.text, identity.promptPreamble, outOfBand),
985
1226
  participant,
986
1227
  ...(identity.deliveryReceipt ? { identityDeliveryReceipt: identity.deliveryReceipt } : {}),
987
1228
  });
@@ -1174,19 +1415,7 @@ class PersistedConversationLifecycle implements AgentConversationOwnerLifecycle
1174
1415
  records: readonly NewConversationRecord[],
1175
1416
  audit = true,
1176
1417
  ): Promise<readonly ConversationRecord[]> {
1177
- if (records.length === 0) return Object.freeze([]);
1178
- if ((!audit || !this.settings.auditLog) && records.every((record) => {
1179
- if (record.kind !== "protocol") return this.settings.capture[record.kind] === "none";
1180
- return this.settings.capture.protocol.level === "none"
1181
- || !shouldCaptureProtocolMethod(this.settings.capture.protocol, record.method);
1182
- })) return Object.freeze([]);
1183
- const persisted: ConversationRecord[] = [];
1184
- await this.agent.persistence.transaction(async (persistence) => {
1185
- await this.persistObservationsInTransaction(persistence, records, audit, persisted);
1186
- });
1187
- this.agent.publishCommittedRecords(persisted);
1188
- if (audit && this.settings.auditLog) this.agent.audit?.notifyPending();
1189
- return Object.freeze(persisted);
1418
+ return await persistConversationObservations(this.agent, this.settings, records, audit);
1190
1419
  }
1191
1420
 
1192
1421
  private async persistObservationsInTransaction(
@@ -1195,35 +1424,76 @@ class PersistedConversationLifecycle implements AgentConversationOwnerLifecycle
1195
1424
  audit: boolean,
1196
1425
  persisted: ConversationRecord[],
1197
1426
  ): Promise<void> {
1198
- for (const record of records) {
1199
- const level = record.kind === "protocol"
1200
- ? this.settings.capture.protocol.level
1201
- : this.settings.capture[record.kind];
1202
- const canonicalAccepted = level !== "none" && (
1203
- record.kind !== "protocol"
1204
- || shouldCaptureProtocolMethod(this.settings.capture.protocol, record.method)
1205
- );
1206
- if (canonicalAccepted) {
1207
- persisted.push(await persistence.records.append(captureRuntimeRecord(record, level)));
1208
- }
1209
- if (audit && this.settings.auditLog) {
1210
- await enqueueAuditObservation(persistence, {
1211
- scope: "conversation",
1212
- sourceObservationId: record.recordId,
1213
- operationId: operationIdFromMetadata(record.metadata),
1214
- record,
1215
- }, this.settings.auditLog);
1216
- }
1217
- }
1427
+ await persistObservationsInTransaction(this.settings, persistence, records, audit, persisted);
1218
1428
  }
1219
1429
 
1220
1430
  private async updateIdentity(records: readonly ConversationRecord[]): Promise<void> {
1221
- await this.agent.identity.update({
1222
- agentSessionId: this.agent.id,
1223
- agentConversationId: this.conversationId,
1224
- records,
1225
- });
1226
- await this.settings.auditIdentityUpdate(this.conversationId, records);
1431
+ await updateConversationIdentity(this.agent, this.settings, this.conversationId, records);
1432
+ }
1433
+ }
1434
+
1435
+ async function updateConversationIdentity(
1436
+ agent: Agent,
1437
+ settings: ManagerSettings,
1438
+ conversationId: AgentConversationId,
1439
+ records: readonly ConversationRecord[],
1440
+ ): Promise<void> {
1441
+ await agent.identity.update({
1442
+ agentSessionId: agent.id,
1443
+ agentConversationId: conversationId,
1444
+ records,
1445
+ });
1446
+ await settings.auditIdentityUpdate(conversationId, records);
1447
+ }
1448
+
1449
+ /** Persist canonical records and their audit intents in one transaction, then publish them. */
1450
+ async function persistConversationObservations(
1451
+ agent: Agent,
1452
+ settings: ManagerSettings,
1453
+ records: readonly NewConversationRecord[],
1454
+ audit = true,
1455
+ ): Promise<readonly ConversationRecord[]> {
1456
+ if (records.length === 0) return Object.freeze([]);
1457
+ if ((!audit || !settings.auditLog) && records.every((record) => {
1458
+ if (record.kind !== "protocol") return settings.capture[record.kind] === "none";
1459
+ return settings.capture.protocol.level === "none"
1460
+ || !shouldCaptureProtocolMethod(settings.capture.protocol, record.method);
1461
+ })) return Object.freeze([]);
1462
+ const persisted: ConversationRecord[] = [];
1463
+ await agent.persistence.transaction(async (persistence) => {
1464
+ await persistObservationsInTransaction(settings, persistence, records, audit, persisted);
1465
+ });
1466
+ agent.publishCommittedRecords(persisted);
1467
+ if (audit && settings.auditLog) agent.audit?.notifyPending();
1468
+ return Object.freeze(persisted);
1469
+ }
1470
+
1471
+ async function persistObservationsInTransaction(
1472
+ settings: ManagerSettings,
1473
+ persistence: PersistenceScope,
1474
+ records: readonly NewConversationRecord[],
1475
+ audit: boolean,
1476
+ persisted: ConversationRecord[],
1477
+ ): Promise<void> {
1478
+ for (const record of records) {
1479
+ const level = record.kind === "protocol"
1480
+ ? settings.capture.protocol.level
1481
+ : settings.capture[record.kind];
1482
+ const canonicalAccepted = level !== "none" && (
1483
+ record.kind !== "protocol"
1484
+ || shouldCaptureProtocolMethod(settings.capture.protocol, record.method)
1485
+ );
1486
+ if (canonicalAccepted) {
1487
+ persisted.push(await persistence.records.append(captureRuntimeRecord(record, level)));
1488
+ }
1489
+ if (audit && settings.auditLog) {
1490
+ await enqueueAuditObservation(persistence, {
1491
+ scope: "conversation",
1492
+ sourceObservationId: record.recordId,
1493
+ operationId: operationIdFromMetadata(record.metadata),
1494
+ record,
1495
+ }, settings.auditLog);
1496
+ }
1227
1497
  }
1228
1498
  }
1229
1499
 
@@ -1252,6 +1522,15 @@ function captureRuntimeRecord(
1252
1522
  record: NewConversationRecord,
1253
1523
  level: RecordCaptureLevel,
1254
1524
  ): NewConversationRecord {
1525
+ if (record.kind === "error") {
1526
+ // `metadata` omits the display message and details; `content` keeps the message but
1527
+ // still omits details; `raw` retains the allow-listed details.
1528
+ if (level === "raw") return record;
1529
+ const { details: _details, message, ...rest } = record;
1530
+ return level === "content"
1531
+ ? { ...rest, ...(message === undefined ? {} : { message }) }
1532
+ : rest;
1533
+ }
1255
1534
  if (level !== "metadata") return record;
1256
1535
  switch (record.kind) {
1257
1536
  case "message":
@@ -1319,6 +1598,21 @@ async function enqueueAuditObservation(
1319
1598
  });
1320
1599
  }
1321
1600
 
1601
+ /** Allow-listed machine-readable detail from a raw ACP error, when it exposes any. */
1602
+ function providerSessionErrorDetails(error: unknown): ConversationErrorDetails | undefined {
1603
+ const value = typeof error === "object" && error !== null
1604
+ ? error as { code?: unknown; data?: unknown }
1605
+ : null;
1606
+ const data = typeof value?.data === "object" && value.data !== null
1607
+ ? value.data as Record<string, unknown>
1608
+ : undefined;
1609
+ return buildConversationErrorDetails({
1610
+ rpcCode: typeof value?.code === "number" ? value.code : undefined,
1611
+ service: data?.service,
1612
+ providerCode: data?.providerCode,
1613
+ });
1614
+ }
1615
+
1322
1616
  function operationIdFromMetadata(metadata: string | undefined): string | undefined {
1323
1617
  if (!metadata) return undefined;
1324
1618
  try {
@@ -19,6 +19,7 @@ export interface AgentAuditCaptureConfig {
19
19
  readonly agent_action?: RecordCaptureLevel;
20
20
  readonly thinking?: RecordCaptureLevel;
21
21
  readonly activity?: RecordCaptureLevel;
22
+ readonly error?: RecordCaptureLevel;
22
23
  readonly metering?: "none" | "metadata" | "summary" | "raw";
23
24
  readonly agent_lifecycle?: RecordCaptureLevel;
24
25
  readonly identity?: RecordCaptureLevel;
@@ -54,6 +55,7 @@ export interface ResolvedAgentAuditCapturePolicy {
54
55
  readonly agent_action: RecordCaptureLevel;
55
56
  readonly thinking: RecordCaptureLevel;
56
57
  readonly activity: RecordCaptureLevel;
58
+ readonly error: RecordCaptureLevel;
57
59
  readonly metering: "none" | "metadata" | "summary" | "raw";
58
60
  readonly agent_lifecycle: RecordCaptureLevel;
59
61
  readonly identity: RecordCaptureLevel;
@@ -80,6 +82,7 @@ export const DEFAULT_AGENT_AUDIT_CAPTURE: ResolvedAgentAuditCapturePolicy = Obje
80
82
  agent_action: "metadata",
81
83
  thinking: "none",
82
84
  activity: "metadata",
85
+ error: "content",
83
86
  metering: "summary",
84
87
  agent_lifecycle: "metadata",
85
88
  identity: "metadata",
@@ -166,6 +169,7 @@ export function resolveAgentAuditCapture(
166
169
  agent_action: general("agent_action"),
167
170
  thinking: general("thinking"),
168
171
  activity: general("activity"),
172
+ error: general("error"),
169
173
  metering: specialized("metering", ["none", "metadata", "summary", "raw"]),
170
174
  agent_lifecycle: general("agent_lifecycle"),
171
175
  identity: general("identity"),
@@ -90,6 +90,17 @@ function projectRecordPayload(
90
90
  return { ...base, activityId: record.activityId, activityType: record.activityType, state: record.state,
91
91
  ...(level !== "metadata" && record.content !== undefined ? { content: json(record.content) } : {}),
92
92
  ...(level === "raw" && record.data !== undefined ? { data: record.data } : {}) };
93
+ case "error":
94
+ return {
95
+ ...base,
96
+ source: record.source,
97
+ code: record.code,
98
+ recoverability: record.recoverability,
99
+ ...(record.transitionId ? { transitionId: record.transitionId } : {}),
100
+ ...(record.internalSessionId ? { internalSessionId: record.internalSessionId } : {}),
101
+ ...(level !== "metadata" && record.message ? { message: record.message } : {}),
102
+ ...(level === "raw" && record.details ? { details: json(record.details) } : {}),
103
+ };
93
104
  case "metering": {
94
105
  const metering = observation.meteringRecord;
95
106
  if (level === "raw" && metering) return json(metering);
@@ -1,5 +1,8 @@
1
1
  import type { AgentConversationId } from "../agent-ids.ts";
2
- import type { ConversationMessagePersistence } from "../persistence/backend.ts";
2
+ import type {
3
+ ConversationErrorRecoverability,
4
+ ConversationMessagePersistence,
5
+ } from "../persistence/backend.ts";
3
6
  import type { ConversationRecoveryCheckpoint } from "./contracts.ts";
4
7
  import type { ResolvedConversationRecoveryConfig } from "./config.ts";
5
8
 
@@ -51,6 +54,25 @@ function isRecord(value: unknown): value is Record<string, unknown> {
51
54
  return typeof value === "object" && value !== null && !Array.isArray(value);
52
55
  }
53
56
 
57
+ export interface ProviderSessionLoadClassification {
58
+ readonly missing: boolean;
59
+ readonly code: "provider_session_missing" | "provider_session_load_failed";
60
+ readonly recoverability: ConversationErrorRecoverability;
61
+ }
62
+
63
+ /**
64
+ * Classify a failed `session/load` conservatively. A recognized missing-session signal is
65
+ * recoverable from a checkpoint; anything else stays `unknown` rather than guessing.
66
+ */
67
+ export function classifyProviderSessionLoadError(
68
+ error: unknown,
69
+ override?: (error: unknown) => boolean,
70
+ ): ProviderSessionLoadClassification {
71
+ return isMissingProviderSessionError(error, override)
72
+ ? { missing: true, code: "provider_session_missing", recoverability: "recoverable" }
73
+ : { missing: false, code: "provider_session_load_failed", recoverability: "unknown" };
74
+ }
75
+
54
76
  export async function buildRecoverySeed(
55
77
  messages: ConversationMessagePersistence,
56
78
  conversationId: AgentConversationId,