@qlairoslabs/acp-client 0.8.0 → 0.9.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/CONSUMER_GUIDE.md CHANGED
@@ -93,6 +93,34 @@ The user message and each assistant-message boundary are stored as separate type
93
93
  Reopen the same database with `Agent.open()` and call
94
94
  `agent.conversations.open(agentConversationId)` to continue its active provider thread.
95
95
 
96
+ ### Attach consumer data to a prompt message
97
+
98
+ The object-form prompt APIs attach opaque JSON to the submitted **user message**:
99
+
100
+ ```ts
101
+ await conversation.prompt({
102
+ text: "hello",
103
+ consumerMetadata: { deliveryId: "delivery-42", submittedBy: "relay" },
104
+ });
105
+ await conversation.promptFrom({
106
+ participantId: "agent-bob",
107
+ text: "Can you review this?",
108
+ consumerMetadata: { deliveryId: "delivery-43" },
109
+ });
110
+
111
+ const messages = await agent.persistence.messages.list(conversation.id);
112
+ console.log(messages.messages[0]?.consumerMetadata);
113
+ ```
114
+
115
+ The older positional `prompt(text, handlers?, attachments?)` and
116
+ `promptFrom(participantId, text, handlers?, attachments?)` calls remain valid.
117
+ `consumerMetadata` is stored in `conversation_messages.consumer_metadata_json` and
118
+ returned as `MessageRecord.consumerMetadata`; it is not copied onto assistant messages,
119
+ sent to the provider, added to identity context, or indexed for search. The library does
120
+ not interpret its fields. The separate envelope `metadata` field still carries older
121
+ library-owned operation correlation. A raw audit capture includes consumer metadata;
122
+ content/metadata audit capture omits it.
123
+
96
124
  SQLite keeps ordering and type-specific content separate. `conversation_records` is a
97
125
  narrow canonical envelope containing the conversation-local sequence, kind, timestamp,
98
126
  operation correlation, and optional metadata. Every envelope has exactly one typed detail
@@ -137,10 +165,65 @@ FTS5 indexes deliberately extracted searchable text rather than serialized recor
137
165
  The initial indexes cover messages, tool calls, and activities. Consumer metadata and raw
138
166
  protocol bodies are not searched implicitly.
139
167
 
140
- Schema version 8 adds the durable Agent audit outbox to the typed layout. Pre-release
141
- version-7 SQLite files are not migrated because they were used only by development smoke
142
- tests. Opening one fails with a clear recreate instruction; remove the old smoke-test
143
- database and run the scenario again.
168
+ Schema version 10 adds message consumer metadata and migrates version-8 and version-9
169
+ agent databases in place. Pre-release version-7 SQLite files are not migrated because
170
+ they were used only by development smoke tests; opening one gives a recreate instruction.
171
+
172
+ ### Read SQLite conversation history and previews
173
+
174
+ `records.listRecent()` returns the newest matching records at a fixed conversation
175
+ sequence snapshot. Each page is oldest-first for rendering; its `olderCursor` stays
176
+ bound to that snapshot and kind filter even if new records arrive:
177
+
178
+ ```ts
179
+ import { reconcileConversationTimeline } from "@qlairoslabs/acp-client";
180
+
181
+ const first = await agent.persistence.records.listRecent!(conversation.id, { limit: 50 });
182
+ let items = reconcileConversationTimeline([], first.records);
183
+ const older = first.olderCursor
184
+ ? await agent.persistence.records.listRecent!(conversation.id, {
185
+ limit: 50,
186
+ olderCursor: first.olderCursor,
187
+ })
188
+ : null;
189
+ if (older) items = reconcileConversationTimeline(items, older.records);
190
+ ```
191
+
192
+ Every physical record has a stable `recordId` and a conversation-local `sequence`.
193
+ The reconciliation helper keeps distinct messages separate and groups revisions of a
194
+ tool call, permission, thinking block, activity, or transition by its logical ID. Its
195
+ items retain every revision, carry the latest merged fields in `current`, and sort by
196
+ the earliest loaded sequence. Loading an older page may move an item to its true
197
+ earlier position when its first revision arrives. Configuration, protocol, agent
198
+ actions, and metering references remain individual records unless they have an
199
+ explicit logical identity; metering details are read from `persistence.metering`.
200
+
201
+ For live reconciliation, subscribe before the initial read if immediate UI feedback
202
+ matters, but treat subscription notifications as hints. The authoritative catch-up is
203
+ `records.list(conversation.id, { afterSequence: lastSeenSequence, limit: 100 })`.
204
+ Advance `lastSeenSequence` to the last returned record and repeat until the page is
205
+ short. Upsert by `recordId` through `reconcileConversationTimeline`; after a process
206
+ restart, catch up from the last sequence the consumer retained. Subscription sequence
207
+ numbers are **not** SQLite conversation sequences.
208
+
209
+ Use one batched preview read for a conversation list:
210
+
211
+ ```ts
212
+ const page = await agent.conversations.listPreviews({ limit: 50 });
213
+ for (const { conversation, latestMessage, lastHumanMessageAt } of page.previews) {
214
+ renderConversationRow(conversation.id, latestMessage?.text, lastHumanMessageAt);
215
+ }
216
+ ```
217
+
218
+ `latestMessage` has its stable record ID, role, participant ID, timestamp, sequence,
219
+ and up to 240 characters of preview text. `lastHumanMessageAt` includes only messages
220
+ whose participant kind is `user`, not agent-to-agent prompts whose message role is
221
+ also `user`. SQLite maintains that timestamp on conversation writes and backfills it
222
+ once for pre-version-10 databases; preview reads do not rescan long message histories.
223
+ Preview paging follows conversation `updatedAt` order; that list may
224
+ reorder as conversations advance, so consumers should refresh it rather than treat
225
+ offset cursors as a frozen snapshot. `listRecent` and `listPreviews` are SQLite
226
+ capabilities; custom persistence backends may not implement them.
144
227
 
145
228
  ### Agent audit log
146
229
 
@@ -483,6 +566,42 @@ Checkpointing requires message capture at `"content"` or `"raw"`. The checkpoint
483
566
  continuation aid, not the authoritative transcript: complete messages and other records
484
567
  remain independently queryable from SQLite.
485
568
 
569
+ ### Share a basic identity across conversations
570
+
571
+ Checkpoint-backed identity is opt-in. It privately delivers knowledge from an agent's
572
+ other conversations to each provider thread, using the existing per-conversation
573
+ checkpoint summaries and messages after those checkpoints:
574
+
575
+ ```ts
576
+ const agent = await Agent.open({
577
+ persistence: { kind: "sqlite", path: "/state/atlas.sqlite" },
578
+ adapters: { codex: ADAPTERS.codex },
579
+ defaultAdapterId: "codex",
580
+ checkpointing: {},
581
+ identity: {
582
+ kind: "checkpoint-backed",
583
+ maxContextChars: 32_000,
584
+ maxSourceChars: 8_000,
585
+ },
586
+ });
587
+ ```
588
+
589
+ The first prompt to a provider thread receives each other conversation's latest
590
+ checkpoint summary plus its uncovered messages. Later prompts receive only messages
591
+ not yet delivered to that thread. Successful prompts advance sparse, durable cursors;
592
+ failed prompts do not. A new provider thread gets a fresh identity view, while loading
593
+ the same provider thread reuses its cursors. The current conversation never receives
594
+ its own history through identity; normal provider continuity and recovery handle that.
595
+
596
+ The character budgets are hard limits, not claims that all agent knowledge fits. When
597
+ the backlog is too large, the runtime delivers an ordered prefix and leaves the rest
598
+ pending. It may request a checkpoint in the background to compress an oversized gap.
599
+ `identityConsistency: "through-current"` rejects a prompt whose available cross-
600
+ conversation messages cannot all fit; the default `"eventual"` permits partial delivery.
601
+ All non-deleted conversations are shared in v1, including conversations with different
602
+ users, so consumers should enable this only where such cross-conversation visibility is
603
+ appropriate. A custom `AgentIdentityRuntime` remains available for other policies.
604
+
486
605
  ## Legacy direct and managed sessions
487
606
 
488
607
  The remaining sections describe the compatibility `AgentSession` and
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@qlairoslabs/acp-client",
3
- "version": "0.8.0",
3
+ "version": "0.9.2",
4
4
  "description": "Embeddable Agent Client Protocol (ACP) client library with degraded PTY fallback.",
5
5
  "type": "module",
6
6
  "module": "src/index.ts",
@@ -1,27 +1,32 @@
1
1
  import type { AgentConversationId, AgentSessionId } from "./agent-ids.ts";
2
2
  import type { Adapter } from "./adapters.ts";
3
3
  import type { AgentMode } from "./controller.ts";
4
- import type { NewConversationRecord, ParticipantRef } from "./persistence/backend.ts";
4
+ import type { NewConversationRecord, ParticipantRef, PersistenceJsonValue } from "./persistence/backend.ts";
5
5
  import type { AgentSessionPromptResult } from "./agent-conversation-contracts.ts";
6
6
  import type { ResponseMessage } from "./types.ts";
7
7
  import type { OperationMeteringRecord } from "./metering/record.ts";
8
8
  import type { AgentSessionMeteringState } from "./metering/state.ts";
9
+ import type { IdentityDeliveryReceipt } from "./identity.ts";
9
10
 
10
11
  export interface OwnedPromptInput {
11
12
  readonly operationId: string;
12
13
  readonly agentSessionId: AgentSessionId;
13
14
  readonly agentConversationId: AgentConversationId;
15
+ readonly targetProviderContextId?: string;
14
16
  readonly participantId?: string;
17
+ readonly consumerMetadata?: PersistenceJsonValue;
15
18
  readonly text: string;
16
19
  }
17
20
 
18
21
  export interface OwnedPromptPreparation {
19
22
  readonly providerText?: string;
20
23
  readonly participant?: ParticipantRef;
24
+ readonly identityDeliveryReceipt?: IdentityDeliveryReceipt;
21
25
  }
22
26
 
23
27
  export interface OwnedPromptCompleted extends OwnedPromptInput {
24
28
  readonly result: AgentSessionPromptResult;
29
+ readonly identityDeliveryReceipt?: IdentityDeliveryReceipt;
25
30
  }
26
31
 
27
32
  export interface OwnedPromptFailed extends OwnedPromptInput {
@@ -210,12 +210,25 @@ interface PromptQueueItem {
210
210
  operationKind: MeteredOperationKind;
211
211
  text: string;
212
212
  participantId?: string;
213
+ consumerMetadata?: PersistenceJsonValue;
213
214
  handlers?: PromptHandlers;
214
215
  attachments?: Attachment[];
215
216
  resolve: (r: AgentSessionPromptResult) => void;
216
217
  reject: (e: unknown) => void;
217
218
  }
218
219
 
220
+ /** Object-form prompt input for per-message consumer metadata on Agent-owned conversations. */
221
+ export interface AgentConversationPromptInput {
222
+ readonly text: string;
223
+ readonly consumerMetadata?: PersistenceJsonValue;
224
+ readonly handlers?: PromptHandlers;
225
+ readonly attachments?: Attachment[];
226
+ }
227
+
228
+ export interface AgentConversationAttributedPromptInput extends AgentConversationPromptInput {
229
+ readonly participantId: string;
230
+ }
231
+
219
232
  interface HandoffQueueItem {
220
233
  kind: "handoff";
221
234
  handoffId: string;
@@ -415,6 +428,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
415
428
  private readonly listeners = new Set<AgentSessionListener>();
416
429
  private lastStateKey = "";
417
430
  private _internalSessionId: string | null;
431
+ private ownerContextNonce: string | null = null;
418
432
  private metering: MeteringEngine;
419
433
  private readonly meteringConfig: MeteringConfig;
420
434
  private _contextWindow: ContextWindowStatus | null = null;
@@ -1659,23 +1673,46 @@ export class AgentConversation implements AgentClient, Bridgeable {
1659
1673
  }
1660
1674
 
1661
1675
  // --- AgentClient -------------------------------------------------------------
1662
- async prompt(
1676
+ prompt(input: AgentConversationPromptInput): Promise<AgentSessionPromptResult>;
1677
+ prompt(
1663
1678
  text: string,
1664
1679
  handlers?: PromptHandlers,
1665
1680
  attachments?: Attachment[],
1681
+ ): Promise<AgentSessionPromptResult>;
1682
+ async prompt(
1683
+ input: string | AgentConversationPromptInput,
1684
+ handlers?: PromptHandlers,
1685
+ attachments?: Attachment[],
1666
1686
  ): Promise<AgentSessionPromptResult> {
1667
- return this.enqueuePrompt(text, "prompt", handlers, attachments);
1687
+ return typeof input === "string"
1688
+ ? this.enqueuePrompt(input, "prompt", handlers, attachments)
1689
+ : this.enqueuePrompt(input.text, "prompt", input.handlers, input.attachments, undefined, input.consumerMetadata);
1668
1690
  }
1669
1691
 
1670
1692
  /** Prompt while attributing the caller to a stable participant identity. */
1693
+ promptFrom(input: AgentConversationAttributedPromptInput): Promise<AgentSessionPromptResult>;
1671
1694
  promptFrom(
1672
1695
  participantId: string,
1673
1696
  text: string,
1674
1697
  handlers?: PromptHandlers,
1675
1698
  attachments?: Attachment[],
1699
+ ): Promise<AgentSessionPromptResult>;
1700
+ promptFrom(
1701
+ input: string | AgentConversationAttributedPromptInput,
1702
+ text?: string,
1703
+ handlers?: PromptHandlers,
1704
+ attachments?: Attachment[],
1676
1705
  ): Promise<AgentSessionPromptResult> {
1706
+ if (typeof input !== "string") {
1707
+ if (!input.participantId.trim()) return Promise.reject(new Error("participant id cannot be blank"));
1708
+ return this.enqueuePrompt(
1709
+ input.text, "prompt", input.handlers, input.attachments,
1710
+ input.participantId.trim(), input.consumerMetadata,
1711
+ );
1712
+ }
1713
+ const participantId = input;
1677
1714
  if (!participantId.trim()) return Promise.reject(new Error("participant id cannot be blank"));
1678
- return this.enqueuePrompt(text, "prompt", handlers, attachments, participantId.trim());
1715
+ return this.enqueuePrompt(text!, "prompt", handlers, attachments, participantId.trim());
1679
1716
  }
1680
1717
 
1681
1718
  private enqueuePrompt(
@@ -1684,14 +1721,24 @@ export class AgentConversation implements AgentClient, Bridgeable {
1684
1721
  handlers?: PromptHandlers,
1685
1722
  attachments?: Attachment[],
1686
1723
  participantId?: string,
1724
+ consumerMetadata?: PersistenceJsonValue,
1687
1725
  ): Promise<AgentSessionPromptResult> {
1688
1726
  return new Promise<AgentSessionPromptResult>((resolve, reject) => {
1689
1727
  if (this.phase === "stopped") {
1690
1728
  reject(new Error("AgentSession is stopped"));
1691
1729
  return;
1692
1730
  }
1731
+ let stableConsumerMetadata: PersistenceJsonValue | undefined;
1693
1732
  try {
1694
1733
  this.assertPromptable();
1734
+ if (consumerMetadata !== undefined && !this.ownerLifecycle) {
1735
+ throw new Error("consumerMetadata requires an Agent-owned conversation");
1736
+ }
1737
+ if (consumerMetadata !== undefined) {
1738
+ const serialized = JSON.stringify(consumerMetadata);
1739
+ if (serialized === undefined) throw new Error("consumerMetadata must be a JSON value");
1740
+ stableConsumerMetadata = JSON.parse(serialized) as PersistenceJsonValue;
1741
+ }
1695
1742
  } catch (error) {
1696
1743
  reject(error);
1697
1744
  return;
@@ -1702,6 +1749,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
1702
1749
  operationKind,
1703
1750
  text,
1704
1751
  ...(participantId ? { participantId } : {}),
1752
+ ...(stableConsumerMetadata !== undefined ? { consumerMetadata: stableConsumerMetadata } : {}),
1705
1753
  handlers,
1706
1754
  attachments,
1707
1755
  resolve,
@@ -2773,12 +2821,17 @@ export class AgentConversation implements AgentClient, Bridgeable {
2773
2821
  }
2774
2822
 
2775
2823
  private async runPrompt(item: PromptQueueItem): Promise<AgentSessionPromptResult> {
2824
+ const targetProviderContextId = this.ownerLifecycle
2825
+ ? this._internalSessionId ?? `runtime:${this.ownerContextNonce ??= crypto.randomUUID()}`
2826
+ : undefined;
2776
2827
  const owned = this.ownerLifecycle
2777
2828
  ? await this.ownerLifecycle.beforePrompt({
2778
2829
  operationId: item.turnId,
2779
2830
  agentSessionId: this.ownerAgentSessionId!,
2780
2831
  agentConversationId: this.agentConversationId,
2832
+ targetProviderContextId,
2781
2833
  ...(item.participantId ? { participantId: item.participantId } : {}),
2834
+ ...(item.consumerMetadata !== undefined ? { consumerMetadata: item.consumerMetadata } : {}),
2782
2835
  text: item.text,
2783
2836
  })
2784
2837
  : undefined;
@@ -3013,6 +3066,10 @@ export class AgentConversation implements AgentClient, Bridgeable {
3013
3066
  operationId: item.turnId,
3014
3067
  agentSessionId: this.ownerAgentSessionId!,
3015
3068
  agentConversationId: this.agentConversationId,
3069
+ targetProviderContextId,
3070
+ ...(owned?.identityDeliveryReceipt
3071
+ ? { identityDeliveryReceipt: owned.identityDeliveryReceipt }
3072
+ : {}),
3016
3073
  ...(item.participantId ? { participantId: item.participantId } : {}),
3017
3074
  text: item.text,
3018
3075
  result,
@@ -3602,6 +3659,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
3602
3659
  private setInternalSessionId(next: string | null, created = true): void {
3603
3660
  if (next === this._internalSessionId) return;
3604
3661
  this._internalSessionId = next;
3662
+ if (this.ownerLifecycle) this.ownerContextNonce = null;
3605
3663
  // The new thread's counters restart, so the old baseline no longer describes them.
3606
3664
  this.metering.onThreadReplaced(next, created);
3607
3665
  if (this._contextWindow !== null) {
package/src/agent.ts CHANGED
@@ -25,6 +25,10 @@ import {
25
25
  type AgentIdentityRuntime,
26
26
  type IdentityConsistency,
27
27
  } from "./identity.ts";
28
+ import {
29
+ CheckpointBackedIdentityRuntime,
30
+ type CheckpointBackedIdentityConfig,
31
+ } from "./identity/checkpoint-backed.ts";
28
32
  import {
29
33
  IMPLICIT_USER_PARTICIPANT_ID,
30
34
  PersistenceCapabilityError,
@@ -34,6 +38,7 @@ import {
34
38
  type AgentConversationSummary,
35
39
  type ConversationListOptions,
36
40
  type ConversationPage,
41
+ type ConversationPreviewPage,
37
42
  type ConversationRecord,
38
43
  type ConversationRecordCaptureConfig,
39
44
  type ConversationRecordCapturePolicy,
@@ -120,7 +125,7 @@ export interface AgentConfig {
120
125
  readonly adapters: Readonly<Record<string, import("./adapters.ts").Adapter>>
121
126
  | readonly AgentAdapterRegistration[];
122
127
  readonly defaultAdapterId?: string;
123
- readonly identity?: AgentIdentityRuntime;
128
+ readonly identity?: AgentIdentityRuntime | CheckpointBackedIdentityConfig;
124
129
  readonly identityConsistency?: IdentityConsistency;
125
130
  readonly identityTimeoutMs?: number;
126
131
  readonly capture?: ConversationRecordCaptureConfig;
@@ -169,6 +174,7 @@ export interface AgentConversationManager {
169
174
  ): Promise<OpenOwnedAgentConversationResult>;
170
175
  get(id: AgentConversationId): Promise<AgentConversationSummary | null>;
171
176
  list(options?: ConversationListOptions): Promise<ConversationPage>;
177
+ listPreviews(options?: ConversationListOptions): Promise<ConversationPreviewPage>;
172
178
  delete(id: AgentConversationId, deletedAt?: string): Promise<void>;
173
179
  }
174
180
 
@@ -192,7 +198,7 @@ export class Agent {
192
198
  private constructor(
193
199
  id: AgentSessionId,
194
200
  persistence: PersistenceBackend,
195
- identity: AgentIdentityRuntime,
201
+ identity: AgentIdentityRuntime | CheckpointBackedIdentityConfig | undefined,
196
202
  adapters: AgentAdapterRegistry,
197
203
  config: AgentConfig,
198
204
  private readonly auditLog: ResolvedAgentAuditLogConfig | null,
@@ -200,12 +206,34 @@ export class Agent {
200
206
  ) {
201
207
  this.id = id;
202
208
  this.persistence = persistence;
203
- this.identity = identity;
204
209
  this.adapters = adapters;
205
210
  this.audit = audit;
206
211
  const checkpointing = config.checkpointing
207
212
  ? resolveConversationCheckpointingConfig(config.checkpointing)
208
213
  : null;
214
+ const checkpointBackedIdentity = identity && !("load" in identity) && identity.kind === "checkpoint-backed"
215
+ ? identity
216
+ : null;
217
+ if (identity && !("load" in identity) && !checkpointBackedIdentity) {
218
+ throw new Error("unknown built-in identity configuration");
219
+ }
220
+ if (checkpointBackedIdentity) {
221
+ if (!checkpointing?.enabled) {
222
+ throw new Error("checkpoint-backed identity requires enabled conversation checkpointing");
223
+ }
224
+ if (!persistence.identityDelivery || !persistence.recoveryCheckpoints) {
225
+ throw new Error("checkpoint-backed identity requires delivery cursor persistence");
226
+ }
227
+ }
228
+ this.identity = checkpointBackedIdentity
229
+ ? new CheckpointBackedIdentityRuntime(
230
+ persistence,
231
+ checkpointBackedIdentity,
232
+ async (source) => { await this.checkpointing?.request(source); },
233
+ )
234
+ : identity && "load" in identity
235
+ ? identity
236
+ : new NoopAgentIdentityRuntime();
209
237
  this.manager = new DefaultAgentConversationManager(this, {
210
238
  defaultAdapterId: config.defaultAdapterId,
211
239
  identityConsistency: config.identityConsistency ?? "eventual",
@@ -380,7 +408,7 @@ export class Agent {
380
408
  const agent = new Agent(
381
409
  id,
382
410
  persistence,
383
- config.identity ?? new NoopAgentIdentityRuntime(),
411
+ config.identity,
384
412
  adapters,
385
413
  config,
386
414
  auditLog || null,
@@ -598,7 +626,7 @@ class DefaultAgentConversationManager implements AgentConversationManager {
598
626
  previousInternalSessionId: active.internalSessionId,
599
627
  recoveredThroughSequence: seed.recoveredThroughSequence,
600
628
  }),
601
- });
629
+ }, true);
602
630
  } catch (recoveryError) {
603
631
  this.live.delete(id);
604
632
  await conversation.stop().catch(() => undefined);
@@ -624,6 +652,13 @@ class DefaultAgentConversationManager implements AgentConversationManager {
624
652
  return await this.agent.persistence.conversations.list(options);
625
653
  }
626
654
 
655
+ async listPreviews(options?: ConversationListOptions): Promise<ConversationPreviewPage> {
656
+ if (!this.agent.persistence.conversations.listPreviews) {
657
+ throw new Error("conversation previews are unavailable on this persistence backend");
658
+ }
659
+ return await this.agent.persistence.conversations.listPreviews(options);
660
+ }
661
+
627
662
  async delete(id: AgentConversationId, deletedAt?: string): Promise<void> {
628
663
  const live = this.live.get(id);
629
664
  if (live) await live.stop();
@@ -796,7 +831,7 @@ class DefaultAgentConversationManager implements AgentConversationManager {
796
831
  }
797
832
  });
798
833
  if (conversation.internalSessionId && !config.deferProviderSessionPersistence) {
799
- await this.persistProviderSession(conversation, id, adapterId);
834
+ await this.persistProviderSession(conversation, id, adapterId, {}, config.providerSession === "new");
800
835
  }
801
836
  return conversation;
802
837
  } catch (error) {
@@ -837,17 +872,21 @@ class DefaultAgentConversationManager implements AgentConversationManager {
837
872
  id: AgentConversationId,
838
873
  adapterId: string,
839
874
  extra: { readonly transitionId?: string; readonly metadata?: string } = {},
875
+ newContext = false,
840
876
  ): Promise<void> {
841
877
  if (!conversation.internalSessionId) throw new Error("provider session has no internal session id");
842
- await this.agent.persistence.providerSessions.append({
843
- providerSessionRecordId: `provider-${randomUUID()}`,
844
- agentConversationId: id,
845
- internalSessionId: conversation.internalSessionId,
846
- adapterId,
847
- mode: conversation.mode,
848
- ...(conversation.model ? { model: conversation.model } : {}),
849
- activatedAt: new Date().toISOString(),
850
- ...extra,
878
+ await this.agent.persistence.transaction(async (persistence) => {
879
+ if (newContext) await persistence.identityDelivery?.reset(id, conversation.internalSessionId!);
880
+ await persistence.providerSessions.append({
881
+ providerSessionRecordId: `provider-${randomUUID()}`,
882
+ agentConversationId: id,
883
+ internalSessionId: conversation.internalSessionId!,
884
+ adapterId,
885
+ mode: conversation.mode,
886
+ ...(conversation.model ? { model: conversation.model } : {}),
887
+ activatedAt: new Date().toISOString(),
888
+ ...extra,
889
+ });
851
890
  });
852
891
  }
853
892
  }
@@ -865,6 +904,7 @@ class PersistedConversationLifecycle implements AgentConversationOwnerLifecycle
865
904
  const identity = await this.agent.identity.load({
866
905
  agentSessionId: this.agent.id,
867
906
  agentConversationId: this.conversationId,
907
+ targetProviderContextId: input.targetProviderContextId,
868
908
  participant,
869
909
  prompt: input.text,
870
910
  consistency: this.settings.identityConsistency,
@@ -880,6 +920,7 @@ class PersistedConversationLifecycle implements AgentConversationOwnerLifecycle
880
920
  timestamp: new Date().toISOString(),
881
921
  role: "user",
882
922
  participantId: participant.id,
923
+ ...(input.consumerMetadata !== undefined ? { consumerMetadata: input.consumerMetadata } : {}),
883
924
  content: input.text,
884
925
  status: "completed",
885
926
  metadata: JSON.stringify({ operationId: input.operationId }),
@@ -888,6 +929,7 @@ class PersistedConversationLifecycle implements AgentConversationOwnerLifecycle
888
929
  return Object.freeze({
889
930
  providerText: composeIdentityPrompt(input.text, identity),
890
931
  participant,
932
+ ...(identity.deliveryReceipt ? { identityDeliveryReceipt: identity.deliveryReceipt } : {}),
891
933
  });
892
934
  }
893
935
 
@@ -909,6 +951,9 @@ class PersistedConversationLifecycle implements AgentConversationOwnerLifecycle
909
951
  }),
910
952
  }));
911
953
  await this.updateIdentity(await this.appendMessages(records));
954
+ if (status === "completed" && input.identityDeliveryReceipt) {
955
+ await this.agent.identity.delivered?.(input.identityDeliveryReceipt);
956
+ }
912
957
  if (status === "completed") {
913
958
  await this.agent.checkpointing?.afterSuccessfulResponse(this.conversationId);
914
959
  }
@@ -946,15 +991,18 @@ class PersistedConversationLifecycle implements AgentConversationOwnerLifecycle
946
991
  readonly model?: string;
947
992
  readonly activatedAt: string;
948
993
  }): Promise<void> {
949
- await this.agent.persistence.providerSessions.append({
950
- providerSessionRecordId: `provider-${randomUUID()}`,
951
- agentConversationId: input.agentConversationId,
952
- internalSessionId: input.internalSessionId,
953
- adapterId: input.adapterId,
954
- mode: input.mode,
955
- ...(input.model ? { model: input.model } : {}),
956
- activatedAt: input.activatedAt,
957
- transitionId: input.transitionId,
994
+ await this.agent.persistence.transaction(async (persistence) => {
995
+ await persistence.identityDelivery?.reset(input.agentConversationId, input.internalSessionId);
996
+ await persistence.providerSessions.append({
997
+ providerSessionRecordId: `provider-${randomUUID()}`,
998
+ agentConversationId: input.agentConversationId,
999
+ internalSessionId: input.internalSessionId,
1000
+ adapterId: input.adapterId,
1001
+ mode: input.mode,
1002
+ ...(input.model ? { model: input.model } : {}),
1003
+ activatedAt: input.activatedAt,
1004
+ transitionId: input.transitionId,
1005
+ });
958
1006
  });
959
1007
  }
960
1008
 
@@ -58,7 +58,9 @@ function projectRecordPayload(
58
58
  switch (record.kind) {
59
59
  case "message":
60
60
  return { ...base, role: record.role, ...(record.participantId ? { participantId: record.participantId } : {}),
61
- ...(record.status ? { status: record.status } : {}), ...(level !== "metadata" ? { content: json(record.content) } : {}) };
61
+ ...(record.status ? { status: record.status } : {}), ...(level !== "metadata" ? { content: json(record.content) } : {}),
62
+ ...(level === "raw" && record.consumerMetadata !== undefined
63
+ ? { consumerMetadata: record.consumerMetadata } : {}) };
62
64
  case "tool_call":
63
65
  return { ...base, toolCallId: record.toolCallId, state: record.state, ...(record.name ? { name: record.name } : {}),
64
66
  ...(["input", "content", "raw"].includes(level) && record.input !== undefined ? { input: record.input } : {}),