@qlairoslabs/acp-client 0.8.0 → 0.9.3

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,72 @@ 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 11 adds stable assistant-message identities and migrates version-8,
169
+ version-9, and version-10 agent databases in place. Version 10 added message consumer
170
+ metadata. Pre-release version-7 SQLite files are not migrated because
171
+ they were used only by development smoke tests; opening one gives a recreate instruction.
172
+
173
+ ### Read SQLite conversation history and previews
174
+
175
+ `records.listRecent()` returns the newest matching records at a fixed conversation
176
+ sequence snapshot. Each page is oldest-first for rendering; its `olderCursor` stays
177
+ bound to that snapshot and kind filter even if new records arrive:
178
+
179
+ ```ts
180
+ import { reconcileConversationTimeline } from "@qlairoslabs/acp-client";
181
+
182
+ const first = await agent.persistence.records.listRecent!(conversation.id, { limit: 50 });
183
+ let items = reconcileConversationTimeline([], first.records);
184
+ const older = first.olderCursor
185
+ ? await agent.persistence.records.listRecent!(conversation.id, {
186
+ limit: 50,
187
+ olderCursor: first.olderCursor,
188
+ })
189
+ : null;
190
+ if (older) items = reconcileConversationTimeline(items, older.records);
191
+ ```
192
+
193
+ Every physical record has a stable `recordId` and a conversation-local `sequence`.
194
+ The reconciliation helper keeps distinct messages separate and groups revisions of an
195
+ assistant message, tool call, permission, thinking block, activity, or transition by its
196
+ logical ID. Assistant snapshots take their position from the first streamed text; the
197
+ completed revision supplies their final content and status. Providers that expose a
198
+ message only in the final prompt result cannot supply an earlier position. Records
199
+ written before schema version 11 have no such boundaries to reconstruct. The helper's
200
+ items retain every revision, carry the latest merged fields in `current`, and sort by
201
+ the earliest loaded sequence. Loading an older page may move an item to its true
202
+ earlier position when its first revision arrives. Configuration, protocol, agent
203
+ actions, and metering references remain individual records unless they have an
204
+ explicit logical identity; metering details are read from `persistence.metering`.
205
+
206
+ For live reconciliation, subscribe before the initial read if immediate UI feedback
207
+ matters, but treat subscription notifications as hints. The authoritative catch-up is
208
+ `records.list(conversation.id, { afterSequence: lastSeenSequence, limit: 100 })`.
209
+ Advance `lastSeenSequence` to the last returned record and repeat until the page is
210
+ short. Upsert by `recordId` through `reconcileConversationTimeline`; after a process
211
+ restart, catch up from the last sequence the consumer retained. Subscription sequence
212
+ numbers are **not** SQLite conversation sequences.
213
+
214
+ Use one batched preview read for a conversation list:
215
+
216
+ ```ts
217
+ const page = await agent.conversations.listPreviews({ limit: 50 });
218
+ for (const { conversation, latestMessage, lastHumanMessageAt } of page.previews) {
219
+ renderConversationRow(conversation.id, latestMessage?.text, lastHumanMessageAt);
220
+ }
221
+ ```
222
+
223
+ `latestMessage` has its stable record ID, role, participant ID, timestamp, sequence,
224
+ and up to 240 characters of preview text. `lastHumanMessageAt` includes only messages
225
+ whose participant kind is `user`, not agent-to-agent prompts whose message role is
226
+ also `user`. SQLite maintains that timestamp on conversation writes and backfills it
227
+ once for pre-version-10 databases; preview reads do not rescan long message histories.
228
+ Preview paging follows conversation `updatedAt` order; that list may
229
+ reorder as conversations advance, so consumers should refresh it rather than treat
230
+ offset cursors as a frozen snapshot. `messages.list()` returns the latest visible
231
+ revision per logical message; `records.list()` and `records.listRecent()` retain all
232
+ physical revisions for timeline reconstruction and audit. `listRecent` and `listPreviews` are SQLite
233
+ capabilities; custom persistence backends may not implement them.
144
234
 
145
235
  ### Agent audit log
146
236
 
@@ -483,6 +573,42 @@ Checkpointing requires message capture at `"content"` or `"raw"`. The checkpoint
483
573
  continuation aid, not the authoritative transcript: complete messages and other records
484
574
  remain independently queryable from SQLite.
485
575
 
576
+ ### Share a basic identity across conversations
577
+
578
+ Checkpoint-backed identity is opt-in. It privately delivers knowledge from an agent's
579
+ other conversations to each provider thread, using the existing per-conversation
580
+ checkpoint summaries and messages after those checkpoints:
581
+
582
+ ```ts
583
+ const agent = await Agent.open({
584
+ persistence: { kind: "sqlite", path: "/state/atlas.sqlite" },
585
+ adapters: { codex: ADAPTERS.codex },
586
+ defaultAdapterId: "codex",
587
+ checkpointing: {},
588
+ identity: {
589
+ kind: "checkpoint-backed",
590
+ maxContextChars: 32_000,
591
+ maxSourceChars: 8_000,
592
+ },
593
+ });
594
+ ```
595
+
596
+ The first prompt to a provider thread receives each other conversation's latest
597
+ checkpoint summary plus its uncovered messages. Later prompts receive only messages
598
+ not yet delivered to that thread. Successful prompts advance sparse, durable cursors;
599
+ failed prompts do not. A new provider thread gets a fresh identity view, while loading
600
+ the same provider thread reuses its cursors. The current conversation never receives
601
+ its own history through identity; normal provider continuity and recovery handle that.
602
+
603
+ The character budgets are hard limits, not claims that all agent knowledge fits. When
604
+ the backlog is too large, the runtime delivers an ordered prefix and leaves the rest
605
+ pending. It may request a checkpoint in the background to compress an oversized gap.
606
+ `identityConsistency: "through-current"` rejects a prompt whose available cross-
607
+ conversation messages cannot all fit; the default `"eventual"` permits partial delivery.
608
+ All non-deleted conversations are shared in v1, including conversations with different
609
+ users, so consumers should enable this only where such cross-conversation visibility is
610
+ appropriate. A custom `AgentIdentityRuntime` remains available for other policies.
611
+
486
612
  ## Legacy direct and managed sessions
487
613
 
488
614
  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.3",
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;
@@ -2852,11 +2905,27 @@ export class AgentConversation implements AgentClient, Bridgeable {
2852
2905
  stopReason?: string,
2853
2906
  force = false,
2854
2907
  ) => {
2855
- if (!this.v2Transcript || !assistantMessage || (!assistantMessage.dirty && !force)) return;
2908
+ if ((!this.v2Transcript && !this.ownerLifecycle) || !assistantMessage
2909
+ || (!assistantMessage.dirty && !force)) return;
2856
2910
  assistantMessage.revision++;
2857
2911
  assistantMessage.dirty = false;
2858
2912
  const message = assistantMessage;
2859
- this.presentation.queuePresentation({
2913
+ if (this.ownerAgentSessionId && status === "in_progress") {
2914
+ this.queueOwnedRecord({
2915
+ recordId: `${message.id}:snapshot:${message.revision}`,
2916
+ agentSessionId: this.ownerAgentSessionId,
2917
+ agentConversationId: this.agentConversationId,
2918
+ kind: "message",
2919
+ timestamp: new Date().toISOString(),
2920
+ role: "assistant",
2921
+ logicalMessageId: message.id,
2922
+ content: message.text,
2923
+ status,
2924
+ metadata: JSON.stringify({ operationId: item.turnId,
2925
+ ...(message.providerMessageId ? { providerMessageId: message.providerMessageId } : {}) }),
2926
+ });
2927
+ }
2928
+ if (this.v2Transcript) this.presentation.queuePresentation({
2860
2929
  kind: "message",
2861
2930
  operationId: item.turnId,
2862
2931
  role: "assistant",
@@ -2889,7 +2958,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
2889
2958
  item.handlers?.onRecord?.({ current: null, delta: null, emitted: [settledReasoning] });
2890
2959
  }
2891
2960
  response.append(chunk);
2892
- if (this.v2Transcript) {
2961
+ if (this.v2Transcript || this.ownerLifecycle) {
2893
2962
  if (chunk.startsMessage) {
2894
2963
  flushAssistantMessage("completed", undefined, assistantMessage !== null);
2895
2964
  beginAssistantMessage(chunk.messageId);
@@ -3009,10 +3078,15 @@ export class AgentConversation implements AgentClient, Bridgeable {
3009
3078
  });
3010
3079
  }
3011
3080
  const result = Object.freeze({ ...res, operationId: item.turnId, metering: record });
3081
+ await this.ownerRecordWrite;
3012
3082
  await this.ownerLifecycle?.afterPrompt({
3013
3083
  operationId: item.turnId,
3014
3084
  agentSessionId: this.ownerAgentSessionId!,
3015
3085
  agentConversationId: this.agentConversationId,
3086
+ targetProviderContextId,
3087
+ ...(owned?.identityDeliveryReceipt
3088
+ ? { identityDeliveryReceipt: owned.identityDeliveryReceipt }
3089
+ : {}),
3016
3090
  ...(item.participantId ? { participantId: item.participantId } : {}),
3017
3091
  text: item.text,
3018
3092
  result,
@@ -3031,6 +3105,9 @@ export class AgentConversation implements AgentClient, Bridgeable {
3031
3105
  ? Object.freeze([{ text }])
3032
3106
  : Object.freeze([]);
3033
3107
  if (!providerSettled) {
3108
+ await this.ownerRecordWrite.catch((persistenceError) => {
3109
+ this.log.warn("owned_runtime_persistence_failed", { error: String(persistenceError) });
3110
+ });
3034
3111
  await this.ownerLifecycle?.promptFailed({
3035
3112
  operationId: item.turnId,
3036
3113
  agentSessionId: this.ownerAgentSessionId!,
@@ -3602,6 +3679,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
3602
3679
  private setInternalSessionId(next: string | null, created = true): void {
3603
3680
  if (next === this._internalSessionId) return;
3604
3681
  this._internalSessionId = next;
3682
+ if (this.ownerLifecycle) this.ownerContextNonce = null;
3605
3683
  // The new thread's counters restart, so the old baseline no longer describes them.
3606
3684
  this.metering.onThreadReplaced(next, created);
3607
3685
  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
 
@@ -901,6 +943,7 @@ class PersistedConversationLifecycle implements AgentConversationOwnerLifecycle
901
943
  kind: "message",
902
944
  timestamp,
903
945
  role: "assistant",
946
+ logicalMessageId: `message:${input.operationId}:assistant:${index + 1}`,
904
947
  content: message.text,
905
948
  status,
906
949
  metadata: JSON.stringify({
@@ -909,6 +952,9 @@ class PersistedConversationLifecycle implements AgentConversationOwnerLifecycle
909
952
  }),
910
953
  }));
911
954
  await this.updateIdentity(await this.appendMessages(records));
955
+ if (status === "completed" && input.identityDeliveryReceipt) {
956
+ await this.agent.identity.delivered?.(input.identityDeliveryReceipt);
957
+ }
912
958
  if (status === "completed") {
913
959
  await this.agent.checkpointing?.afterSuccessfulResponse(this.conversationId);
914
960
  }
@@ -923,6 +969,7 @@ class PersistedConversationLifecycle implements AgentConversationOwnerLifecycle
923
969
  kind: "message",
924
970
  timestamp,
925
971
  role: "assistant",
972
+ logicalMessageId: `message:${input.operationId}:assistant:${index + 1}`,
926
973
  content: message.text,
927
974
  status: "failed",
928
975
  metadata: JSON.stringify({
@@ -946,20 +993,28 @@ class PersistedConversationLifecycle implements AgentConversationOwnerLifecycle
946
993
  readonly model?: string;
947
994
  readonly activatedAt: string;
948
995
  }): 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,
996
+ await this.agent.persistence.transaction(async (persistence) => {
997
+ await persistence.identityDelivery?.reset(input.agentConversationId, input.internalSessionId);
998
+ await persistence.providerSessions.append({
999
+ providerSessionRecordId: `provider-${randomUUID()}`,
1000
+ agentConversationId: input.agentConversationId,
1001
+ internalSessionId: input.internalSessionId,
1002
+ adapterId: input.adapterId,
1003
+ mode: input.mode,
1004
+ ...(input.model ? { model: input.model } : {}),
1005
+ activatedAt: input.activatedAt,
1006
+ transitionId: input.transitionId,
1007
+ });
958
1008
  });
959
1009
  }
960
1010
 
961
1011
  async record(record: NewConversationRecord): Promise<void> {
962
- await this.updateIdentity(await this.persistObservations([record]));
1012
+ const streamingSnapshot = record.kind === "message" && record.status === "in_progress";
1013
+ const persisted = await this.persistObservations([record], !streamingSnapshot);
1014
+ // A streaming snapshot is a display revision, not a second completed response.
1015
+ if (!streamingSnapshot) {
1016
+ await this.updateIdentity(persisted);
1017
+ }
963
1018
  }
964
1019
 
965
1020
  async meteringRecorded(record: OperationMeteringRecord): Promise<void> {
@@ -1025,9 +1080,10 @@ class PersistedConversationLifecycle implements AgentConversationOwnerLifecycle
1025
1080
 
1026
1081
  private async persistObservations(
1027
1082
  records: readonly NewConversationRecord[],
1083
+ audit = true,
1028
1084
  ): Promise<readonly ConversationRecord[]> {
1029
1085
  if (records.length === 0) return Object.freeze([]);
1030
- if (!this.settings.auditLog && records.every((record) => {
1086
+ if ((!audit || !this.settings.auditLog) && records.every((record) => {
1031
1087
  if (record.kind !== "protocol") return this.settings.capture[record.kind] === "none";
1032
1088
  return this.settings.capture.protocol.level === "none"
1033
1089
  || !shouldCaptureProtocolMethod(this.settings.capture.protocol, record.method);
@@ -1045,7 +1101,7 @@ class PersistedConversationLifecycle implements AgentConversationOwnerLifecycle
1045
1101
  if (canonicalAccepted) {
1046
1102
  persisted.push(await persistence.records.append(captureRuntimeRecord(record, level)));
1047
1103
  }
1048
- if (this.settings.auditLog) {
1104
+ if (audit && this.settings.auditLog) {
1049
1105
  await enqueueAuditObservation(persistence, {
1050
1106
  scope: "conversation",
1051
1107
  sourceObservationId: record.recordId,
@@ -1055,7 +1111,7 @@ class PersistedConversationLifecycle implements AgentConversationOwnerLifecycle
1055
1111
  }
1056
1112
  }
1057
1113
  });
1058
- if (this.settings.auditLog) this.agent.audit?.notifyPending();
1114
+ if (audit && this.settings.auditLog) this.agent.audit?.notifyPending();
1059
1115
  return Object.freeze(persisted);
1060
1116
  }
1061
1117