@qlairoslabs/acp-client 0.9.4 → 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,
@@ -59,12 +63,30 @@ import {
59
63
  type NormalizedAgentObservation,
60
64
  type ResolvedAgentAuditLogConfig,
61
65
  } from "./audit/index.ts";
66
+ import { noopLogger } from "./logger.ts";
67
+ import {
68
+ CommittedRecordEventBus,
69
+ type AgentEventBus,
70
+ } from "./observation/agent-event-bus.ts";
62
71
  import type {
63
72
  AgentConversationOwnerLifecycle,
73
+ OwnedPromptCommitResult,
64
74
  OwnedPromptCompleted,
65
75
  OwnedPromptFailed,
66
76
  OwnedPromptInput,
67
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";
68
90
  import {
69
91
  resolveInternalInferenceConfig,
70
92
  type InternalInferenceConfig,
@@ -81,7 +103,7 @@ import {
81
103
  ConversationCheckpointStrategy,
82
104
  CONVERSATION_CHECKPOINT_STRATEGY_ID,
83
105
  buildRecoverySeed,
84
- isMissingProviderSessionError,
106
+ classifyProviderSessionLoadError,
85
107
  resolveConversationCheckpointingConfig,
86
108
  type ConversationCheckpointingConfig,
87
109
  type ConversationRecoveryProgress,
@@ -176,6 +198,15 @@ export interface AgentConversationManager {
176
198
  list(options?: ConversationListOptions): Promise<ConversationPage>;
177
199
  listPreviews(options?: ConversationListOptions): Promise<ConversationPreviewPage>;
178
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>;
179
210
  }
180
211
 
181
212
  /** Durable owner of one agent identity, its adapters, identity runtime, and conversations. */
@@ -188,7 +219,10 @@ export class Agent {
188
219
  readonly internalInferences?: InternalInferenceManager;
189
220
  readonly checkpointing?: ConversationCheckpointCoordinator;
190
221
  readonly audit?: AgentAuditRuntime;
222
+ /** Process-local stream of committed canonical conversation records. */
223
+ readonly events: AgentEventBus;
191
224
 
225
+ private readonly eventBus: CommittedRecordEventBus;
192
226
  private readonly manager: DefaultAgentConversationManager;
193
227
  private auditObservationTail: Promise<void> = Promise.resolve();
194
228
  private auditObservationError: unknown;
@@ -208,6 +242,19 @@ export class Agent {
208
242
  this.persistence = persistence;
209
243
  this.adapters = adapters;
210
244
  this.audit = audit;
245
+ const logger = config.conversationDefaults?.logger ?? noopLogger;
246
+ this.eventBus = new CommittedRecordEventBus({
247
+ agentSessionId: id,
248
+ onListenerError: ({ error, event }) => {
249
+ // A subscriber is observation, never operation authority: log and move on. It must
250
+ // not become an error record, which would recursively emit another event.
251
+ logger.warn("agent_event_listener_failed", {
252
+ error: error instanceof Error ? error.message : String(error),
253
+ deliverySequence: event.deliverySequence,
254
+ });
255
+ },
256
+ });
257
+ this.events = this.eventBus;
211
258
  const checkpointing = config.checkpointing
212
259
  ? resolveConversationCheckpointingConfig(config.checkpointing)
213
260
  : null;
@@ -309,6 +356,7 @@ export class Agent {
309
356
  beginMetering: async (attempt, session) => {
310
357
  return await this.manager.beginInternalInferenceMetering(attempt, session);
311
358
  },
359
+ onCommittedRecords: (records) => this.publishCommittedRecords(records),
312
360
  resolveAdapterId: async (requestedAdapterId, agentConversationId) => {
313
361
  if (requestedAdapterId) {
314
362
  adapters.require(requestedAdapterId);
@@ -427,6 +475,19 @@ export class Agent {
427
475
  return await Agent.open(config);
428
476
  }
429
477
 
478
+ /**
479
+ * Publish records whose persistence transaction has already committed.
480
+ *
481
+ * Internal to the Agent-owned persistence boundary; it is not a public write API. Keeping
482
+ * publication here is what makes "an event requires an assigned canonical sequence"
483
+ * mechanically true rather than a convention each producer must remember.
484
+ *
485
+ * @internal
486
+ */
487
+ publishCommittedRecords(records: readonly ConversationRecord[]): void {
488
+ this.eventBus.publish(records);
489
+ }
490
+
430
491
  async close(): Promise<void> {
431
492
  if (this.closed) return;
432
493
  this.closed = true;
@@ -439,6 +500,8 @@ export class Agent {
439
500
  await this.auditObservationTail;
440
501
  const observationError = this.auditObservationError;
441
502
  await this.manager.stopAll();
503
+ // Every authorized shutdown write has finished; nothing may be observed after this.
504
+ this.eventBus.close();
442
505
  await this.recordAgentAuditObservation("agent_lifecycle", "closed");
443
506
  if (observationError !== undefined) throw observationError;
444
507
  } catch (error) {
@@ -529,6 +592,9 @@ class DefaultAgentConversationManager implements AgentConversationManager {
529
592
  async create(config: CreateAgentConversationConfig = {}): Promise<AgentConversation> {
530
593
  const id = config.id ?? createAgentConversationId();
531
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" });
532
598
  await this.agent.persistence.conversations.create({
533
599
  agentSessionId: this.agent.id,
534
600
  agentConversationId: id,
@@ -536,10 +602,15 @@ class DefaultAgentConversationManager implements AgentConversationManager {
536
602
  ...(config.title !== undefined ? { title: config.title } : {}),
537
603
  ...(config.metadata !== undefined ? { metadata: config.metadata } : {}),
538
604
  });
539
- return await this.start(id, participants, {
540
- ...config,
541
- providerSession: "new",
542
- });
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
+ }
543
614
  }
544
615
 
545
616
  async open(
@@ -581,6 +652,10 @@ class DefaultAgentConversationManager implements AgentConversationManager {
581
652
  },
582
653
  adapterId: config.adapterId ?? active?.adapterId,
583
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()}`;
584
659
  try {
585
660
  const conversation = await this.start(id, summary.participants, {
586
661
  ...startConfig,
@@ -592,55 +667,106 @@ class DefaultAgentConversationManager implements AgentConversationManager {
592
667
  providerSession: active ? "loaded" : "new",
593
668
  });
594
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);
595
672
  const recovery = this.settings.checkpointing?.recovery;
596
- if (
597
- !active
598
- || recovery?.onLoadFailure !== "recover"
599
- || !isMissingProviderSessionError(error, recovery.isMissingProviderSession)
600
- ) 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();
601
698
  config.onRecoveryProgress?.({ stage: "load_failed" });
602
699
  config.onRecoveryProgress?.({ stage: "loading_checkpoint" });
603
700
  const checkpoint = await this.agent.persistence.recoveryCheckpoints?.latest(id);
604
- if (!checkpoint) throw error;
701
+ if (!checkpoint) throw structuredError();
605
702
  config.onRecoveryProgress?.({ stage: "loading_checkpoint", checkpointId: checkpoint.checkpointId });
606
- const seed = await buildRecoverySeed(
607
- this.agent.persistence.messages,
608
- id,
609
- checkpoint,
610
- summary.latestSequence,
611
- recovery,
612
- );
613
- config.onRecoveryProgress?.({ stage: "creating_session", checkpointId: checkpoint.checkpointId });
614
- const conversation = await this.start(id, summary.participants, {
615
- ...startConfig,
616
- providerSession: "new",
617
- deferProviderSessionPersistence: true,
618
- });
703
+ const recoveryAttemptId = `recovery-${randomUUID()}`;
619
704
  try {
620
- config.onRecoveryProgress?.({ stage: "seeding", checkpointId: checkpoint.checkpointId });
621
- await conversation.seedRecoveryContext(seed.prompt);
622
- await this.persistProviderSession(conversation, id, conversation.adapterId, {
623
- transitionId: `recovery-${randomUUID()}`,
624
- metadata: JSON.stringify({
625
- recoveryCheckpointId: checkpoint.checkpointId,
626
- previousInternalSessionId: active.internalSessionId,
627
- recoveredThroughSequence: seed.recoveredThroughSequence,
628
- }),
629
- }, true);
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 });
630
743
  } catch (recoveryError) {
631
- this.live.delete(id);
632
- await conversation.stop().catch(() => undefined);
633
- 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
+ });
634
769
  }
635
- const result: ConversationRecoveryResult = Object.freeze({
636
- checkpointId: checkpoint.checkpointId,
637
- coveredSequence: checkpoint.coveredSequence,
638
- recoveredThroughSequence: seed.recoveredThroughSequence,
639
- previousInternalSessionId: active.internalSessionId,
640
- newInternalSessionId: conversation.internalSessionId!,
641
- });
642
- config.onRecoveryProgress?.({ stage: "completed", checkpointId: checkpoint.checkpointId });
643
- return Object.freeze({ conversation, providerSession: "recovered", recovery: result });
644
770
  }
645
771
  }
646
772
 
@@ -666,6 +792,40 @@ class DefaultAgentConversationManager implements AgentConversationManager {
666
792
  await this.agent.persistence.conversations.delete(id, deletedAt);
667
793
  }
668
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
+
669
829
  async stopAll(): Promise<void> {
670
830
  await Promise.allSettled([...this.openings.values()]);
671
831
  const conversations = [...this.live.values()];
@@ -787,7 +947,6 @@ class DefaultAgentConversationManager implements AgentConversationManager {
787
947
  config: (CreateAgentConversationConfig | OpenAgentConversationConfig) & {
788
948
  readonly providerSession: "new" | "load";
789
949
  readonly internalSessionId?: string;
790
- readonly deferProviderSessionPersistence?: boolean;
791
950
  },
792
951
  ): Promise<AgentConversation> {
793
952
  const releaseSetup = await this.acquireMeteringSetupLock(id);
@@ -838,9 +997,6 @@ class DefaultAgentConversationManager implements AgentConversationManager {
838
997
  });
839
998
  }
840
999
  });
841
- if (conversation.internalSessionId && !config.deferProviderSessionPersistence) {
842
- await this.persistProviderSession(conversation, id, adapterId, {}, config.providerSession === "new");
843
- }
844
1000
  return conversation;
845
1001
  } catch (error) {
846
1002
  this.live.delete(id);
@@ -875,27 +1031,149 @@ class DefaultAgentConversationManager implements AgentConversationManager {
875
1031
  throw new Error("adapterId is required when an Agent has no unique default adapter");
876
1032
  }
877
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
+
878
1148
  private async persistProviderSession(
879
1149
  conversation: AgentConversation,
880
1150
  id: AgentConversationId,
881
- adapterId: string,
882
1151
  extra: { readonly transitionId?: string; readonly metadata?: string } = {},
883
1152
  newContext = false,
884
- ): Promise<void> {
885
- if (!conversation.internalSessionId) throw new Error("provider session has no internal session id");
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()}`;
886
1160
  await this.agent.persistence.transaction(async (persistence) => {
887
- if (newContext) await persistence.identityDelivery?.reset(id, conversation.internalSessionId!);
1161
+ if (newContext) await persistence.identityDelivery?.reset(id, descriptor.internalSessionId);
888
1162
  await persistence.providerSessions.append({
889
- providerSessionRecordId: `provider-${randomUUID()}`,
1163
+ providerSessionRecordId,
890
1164
  agentConversationId: id,
891
- internalSessionId: conversation.internalSessionId!,
892
- adapterId,
893
- mode: conversation.mode,
894
- ...(conversation.model ? { model: conversation.model } : {}),
895
- activatedAt: new Date().toISOString(),
1165
+ internalSessionId: descriptor.internalSessionId,
1166
+ adapterId: descriptor.adapterId,
1167
+ mode: descriptor.mode,
1168
+ ...(descriptor.model ? { model: descriptor.model } : {}),
1169
+ activatedAt: descriptor.acquiredAt,
896
1170
  ...extra,
897
1171
  });
898
1172
  });
1173
+ return Object.freeze({
1174
+ attachmentAttemptId: descriptor.attachmentAttemptId,
1175
+ providerSessionRecordId,
1176
+ });
899
1177
  }
900
1178
  }
901
1179
 
@@ -934,14 +1212,23 @@ class PersistedConversationLifecycle implements AgentConversationOwnerLifecycle
934
1212
  metadata: JSON.stringify({ operationId: input.operationId }),
935
1213
  }]);
936
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
+ : [];
937
1224
  return Object.freeze({
938
- providerText: composeIdentityPrompt(input.text, identity),
1225
+ providerText: composeProviderPrompt(input.text, identity.promptPreamble, outOfBand),
939
1226
  participant,
940
1227
  ...(identity.deliveryReceipt ? { identityDeliveryReceipt: identity.deliveryReceipt } : {}),
941
1228
  });
942
1229
  }
943
1230
 
944
- async afterPrompt(input: OwnedPromptCompleted): Promise<void> {
1231
+ async afterPrompt(input: OwnedPromptCompleted): Promise<OwnedPromptCommitResult> {
945
1232
  const timestamp = new Date().toISOString();
946
1233
  const status = input.result.status === "error" ? "failed" : input.result.status;
947
1234
  const records = input.result.messages.map((message, index): NewConversationRecord => ({
@@ -959,13 +1246,50 @@ class PersistedConversationLifecycle implements AgentConversationOwnerLifecycle
959
1246
  ...(message.messageId ? { providerMessageId: message.messageId } : {}),
960
1247
  }),
961
1248
  }));
962
- await this.updateIdentity(await this.appendMessages(records));
963
- if (status === "completed" && input.identityDeliveryReceipt) {
964
- await this.agent.identity.delivered?.(input.identityDeliveryReceipt);
965
- }
966
- if (status === "completed") {
967
- await this.agent.checkpointing?.afterSuccessfulResponse(this.conversationId);
1249
+ const persisted: ConversationRecord[] = [];
1250
+ let providerAttachment: ProviderAttachmentCommitAcknowledgement | undefined;
1251
+ await this.agent.persistence.transaction(async (persistence) => {
1252
+ await this.persistObservationsInTransaction(persistence, records, true, persisted);
1253
+ if (status === "completed" && input.providerAttachment.kind === "runtime_only") {
1254
+ const descriptor = input.providerAttachment.descriptor;
1255
+ const providerSessionRecordId = `provider-${randomUUID()}`;
1256
+ await persistence.identityDelivery?.reset(
1257
+ this.conversationId,
1258
+ descriptor.internalSessionId,
1259
+ );
1260
+ await persistence.providerSessions.append({
1261
+ providerSessionRecordId,
1262
+ agentConversationId: this.conversationId,
1263
+ internalSessionId: descriptor.internalSessionId,
1264
+ adapterId: descriptor.adapterId,
1265
+ mode: descriptor.mode,
1266
+ ...(descriptor.model ? { model: descriptor.model } : {}),
1267
+ activatedAt: descriptor.acquiredAt,
1268
+ ...(descriptor.transitionId ? { transitionId: descriptor.transitionId } : {}),
1269
+ });
1270
+ providerAttachment = Object.freeze({
1271
+ attachmentAttemptId: descriptor.attachmentAttemptId,
1272
+ providerSessionRecordId,
1273
+ });
1274
+ }
1275
+ });
1276
+ this.agent.publishCommittedRecords(persisted);
1277
+ if (this.settings.auditLog) this.agent.audit?.notifyPending();
1278
+ const commit: OwnedPromptCommitResult = Object.freeze({
1279
+ ...(providerAttachment ? { providerAttachment } : {}),
1280
+ });
1281
+ try {
1282
+ await this.updateIdentity(Object.freeze(persisted));
1283
+ if (status === "completed" && input.identityDeliveryReceipt) {
1284
+ await this.agent.identity.delivered?.(input.identityDeliveryReceipt);
1285
+ }
1286
+ if (status === "completed") {
1287
+ await this.agent.checkpointing?.afterSuccessfulResponse(this.conversationId);
1288
+ }
1289
+ } catch (error) {
1290
+ throw new OwnedPromptPostCommitError(commit, error);
968
1291
  }
1292
+ return commit;
969
1293
  }
970
1294
 
971
1295
  async promptFailed(input: OwnedPromptFailed): Promise<void> {
@@ -1058,6 +1382,7 @@ class PersistedConversationLifecycle implements AgentConversationOwnerLifecycle
1058
1382
  }, this.settings.auditLog);
1059
1383
  }
1060
1384
  });
1385
+ if (reference) this.agent.publishCommittedRecords([reference]);
1061
1386
  if (this.settings.auditLog) this.agent.audit?.notifyPending();
1062
1387
  if (reference) await this.updateIdentity([reference]);
1063
1388
  }
@@ -1090,46 +1415,85 @@ class PersistedConversationLifecycle implements AgentConversationOwnerLifecycle
1090
1415
  records: readonly NewConversationRecord[],
1091
1416
  audit = true,
1092
1417
  ): Promise<readonly ConversationRecord[]> {
1093
- if (records.length === 0) return Object.freeze([]);
1094
- if ((!audit || !this.settings.auditLog) && records.every((record) => {
1095
- if (record.kind !== "protocol") return this.settings.capture[record.kind] === "none";
1096
- return this.settings.capture.protocol.level === "none"
1097
- || !shouldCaptureProtocolMethod(this.settings.capture.protocol, record.method);
1098
- })) return Object.freeze([]);
1099
- const persisted: ConversationRecord[] = [];
1100
- await this.agent.persistence.transaction(async (persistence) => {
1101
- for (const record of records) {
1102
- const level = record.kind === "protocol"
1103
- ? this.settings.capture.protocol.level
1104
- : this.settings.capture[record.kind];
1105
- const canonicalAccepted = level !== "none" && (
1106
- record.kind !== "protocol"
1107
- || shouldCaptureProtocolMethod(this.settings.capture.protocol, record.method)
1108
- );
1109
- if (canonicalAccepted) {
1110
- persisted.push(await persistence.records.append(captureRuntimeRecord(record, level)));
1111
- }
1112
- if (audit && this.settings.auditLog) {
1113
- await enqueueAuditObservation(persistence, {
1114
- scope: "conversation",
1115
- sourceObservationId: record.recordId,
1116
- operationId: operationIdFromMetadata(record.metadata),
1117
- record,
1118
- }, this.settings.auditLog);
1119
- }
1120
- }
1121
- });
1122
- if (audit && this.settings.auditLog) this.agent.audit?.notifyPending();
1123
- return Object.freeze(persisted);
1418
+ return await persistConversationObservations(this.agent, this.settings, records, audit);
1419
+ }
1420
+
1421
+ private async persistObservationsInTransaction(
1422
+ persistence: PersistenceScope,
1423
+ records: readonly NewConversationRecord[],
1424
+ audit: boolean,
1425
+ persisted: ConversationRecord[],
1426
+ ): Promise<void> {
1427
+ await persistObservationsInTransaction(this.settings, persistence, records, audit, persisted);
1124
1428
  }
1125
1429
 
1126
1430
  private async updateIdentity(records: readonly ConversationRecord[]): Promise<void> {
1127
- await this.agent.identity.update({
1128
- agentSessionId: this.agent.id,
1129
- agentConversationId: this.conversationId,
1130
- records,
1131
- });
1132
- 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
+ }
1133
1497
  }
1134
1498
  }
1135
1499
 
@@ -1158,6 +1522,15 @@ function captureRuntimeRecord(
1158
1522
  record: NewConversationRecord,
1159
1523
  level: RecordCaptureLevel,
1160
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
+ }
1161
1534
  if (level !== "metadata") return record;
1162
1535
  switch (record.kind) {
1163
1536
  case "message":
@@ -1225,6 +1598,21 @@ async function enqueueAuditObservation(
1225
1598
  });
1226
1599
  }
1227
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
+
1228
1616
  function operationIdFromMetadata(metadata: string | undefined): string | undefined {
1229
1617
  if (!metadata) return undefined;
1230
1618
  try {