@qlairoslabs/acp-client 0.10.0 → 0.10.2

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,
@@ -954,7 +1186,16 @@ class PersistedConversationLifecycle implements AgentConversationOwnerLifecycle
954
1186
  ) {}
955
1187
 
956
1188
  async beforePrompt(input: OwnedPromptInput) {
957
- const participant = await this.resolveParticipant(input.participantId);
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]!;
958
1199
  const identity = await this.agent.identity.load({
959
1200
  agentSessionId: this.agent.id,
960
1201
  agentConversationId: this.conversationId,
@@ -966,23 +1207,33 @@ class PersistedConversationLifecycle implements AgentConversationOwnerLifecycle
966
1207
  ? { timeoutMs: this.settings.identityTimeoutMs }
967
1208
  : {}),
968
1209
  });
969
- const records = await this.appendMessages([{
970
- recordId: `${input.operationId}:user`,
1210
+ const records = await this.appendMessages(parts.map((part, index): NewConversationRecord => ({
1211
+ recordId: index === 0 ? `${input.operationId}:user` : `${input.operationId}:user:${index + 1}`,
971
1212
  agentSessionId: this.agent.id,
972
1213
  agentConversationId: this.conversationId,
973
1214
  kind: "message",
974
1215
  timestamp: new Date().toISOString(),
975
1216
  role: "user",
976
- participantId: participant.id,
977
- ...(input.consumerMetadata !== undefined ? { consumerMetadata: input.consumerMetadata } : {}),
978
- content: input.text,
1217
+ participantId: participants[index]!.id,
1218
+ ...(part.consumerMetadata !== undefined ? { consumerMetadata: part.consumerMetadata } : {}),
1219
+ content: part.text,
979
1220
  status: "completed",
980
1221
  metadata: JSON.stringify({ operationId: input.operationId }),
981
- }]);
1222
+ })));
982
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
+ : [];
983
1233
  return Object.freeze({
984
- providerText: composeIdentityPrompt(input.text, identity),
1234
+ providerText: composeProviderPrompt(input.text, identity.promptPreamble, outOfBand),
985
1235
  participant,
1236
+ participants: Object.freeze(participants),
986
1237
  ...(identity.deliveryReceipt ? { identityDeliveryReceipt: identity.deliveryReceipt } : {}),
987
1238
  });
988
1239
  }
@@ -1174,19 +1425,7 @@ class PersistedConversationLifecycle implements AgentConversationOwnerLifecycle
1174
1425
  records: readonly NewConversationRecord[],
1175
1426
  audit = true,
1176
1427
  ): 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);
1428
+ return await persistConversationObservations(this.agent, this.settings, records, audit);
1190
1429
  }
1191
1430
 
1192
1431
  private async persistObservationsInTransaction(
@@ -1195,35 +1434,76 @@ class PersistedConversationLifecycle implements AgentConversationOwnerLifecycle
1195
1434
  audit: boolean,
1196
1435
  persisted: ConversationRecord[],
1197
1436
  ): 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
- }
1437
+ await persistObservationsInTransaction(this.settings, persistence, records, audit, persisted);
1218
1438
  }
1219
1439
 
1220
1440
  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);
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
+ }
1227
1507
  }
1228
1508
  }
1229
1509
 
@@ -1252,6 +1532,15 @@ function captureRuntimeRecord(
1252
1532
  record: NewConversationRecord,
1253
1533
  level: RecordCaptureLevel,
1254
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
+ }
1255
1544
  if (level !== "metadata") return record;
1256
1545
  switch (record.kind) {
1257
1546
  case "message":
@@ -1319,6 +1608,21 @@ async function enqueueAuditObservation(
1319
1608
  });
1320
1609
  }
1321
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
+
1322
1626
  function operationIdFromMetadata(metadata: string | undefined): string | undefined {
1323
1627
  if (!metadata) return undefined;
1324
1628
  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);