@qlairoslabs/acp-client 0.9.2 → 0.9.4

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
@@ -92,6 +92,8 @@ try {
92
92
  The user message and each assistant-message boundary are stored as separate typed rows.
93
93
  Reopen the same database with `Agent.open()` and call
94
94
  `agent.conversations.open(agentConversationId)` to continue its active provider thread.
95
+ `Agent.close()` interrupts live prompts and waits for their finalization and queued
96
+ conversation writes before closing the SQLite backend; an interrupted prompt may reject.
95
97
 
96
98
  ### Attach consumer data to a prompt message
97
99
 
@@ -165,8 +167,9 @@ FTS5 indexes deliberately extracted searchable text rather than serialized recor
165
167
  The initial indexes cover messages, tool calls, and activities. Consumer metadata and raw
166
168
  protocol bodies are not searched implicitly.
167
169
 
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
+ Schema version 11 adds stable assistant-message identities and migrates version-8,
171
+ version-9, and version-10 agent databases in place. Version 10 added message consumer
172
+ metadata. Pre-release version-7 SQLite files are not migrated because
170
173
  they were used only by development smoke tests; opening one gives a recreate instruction.
171
174
 
172
175
  ### Read SQLite conversation history and previews
@@ -190,8 +193,12 @@ if (older) items = reconcileConversationTimeline(items, older.records);
190
193
  ```
191
194
 
192
195
  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
196
+ The reconciliation helper keeps distinct messages separate and groups revisions of an
197
+ assistant message, tool call, permission, thinking block, activity, or transition by its
198
+ logical ID. Assistant snapshots take their position from the first streamed text; the
199
+ completed revision supplies their final content and status. Providers that expose a
200
+ message only in the final prompt result cannot supply an earlier position. Records
201
+ written before schema version 11 have no such boundaries to reconstruct. The helper's
195
202
  items retain every revision, carry the latest merged fields in `current`, and sort by
196
203
  the earliest loaded sequence. Loading an older page may move an item to its true
197
204
  earlier position when its first revision arrives. Configuration, protocol, agent
@@ -222,7 +229,9 @@ also `user`. SQLite maintains that timestamp on conversation writes and backfill
222
229
  once for pre-version-10 databases; preview reads do not rescan long message histories.
223
230
  Preview paging follows conversation `updatedAt` order; that list may
224
231
  reorder as conversations advance, so consumers should refresh it rather than treat
225
- offset cursors as a frozen snapshot. `listRecent` and `listPreviews` are SQLite
232
+ offset cursors as a frozen snapshot. `messages.list()` returns the latest visible
233
+ revision per logical message; `records.list()` and `records.listRecent()` retain all
234
+ physical revisions for timeline reconstruction and audit. `listRecent` and `listPreviews` are SQLite
226
235
  capabilities; custom persistence backends may not implement them.
227
236
 
228
237
  ### Agent audit log
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@qlairoslabs/acp-client",
3
- "version": "0.9.2",
3
+ "version": "0.9.4",
4
4
  "description": "Embeddable Agent Client Protocol (ACP) client library with degraded PTY fallback.",
5
5
  "type": "module",
6
6
  "module": "src/index.ts",
@@ -6,6 +6,7 @@
6
6
  export class AgentConversationQueue<T> {
7
7
  readonly #items: T[] = [];
8
8
  #draining = false;
9
+ #activeDrain: Promise<void> | null = null;
9
10
 
10
11
  get queuedCount(): number {
11
12
  return this.#items.length;
@@ -25,20 +26,37 @@ export class AgentConversationQueue<T> {
25
26
  }
26
27
 
27
28
  /**
28
- * Drain every item serially. Concurrent calls share the active drain by becoming
29
- * no-ops; an item enqueued by an active operation is observed by the same loop.
29
+ * Drain every item serially. Concurrent calls share the active drain; an item
30
+ * enqueued by an active operation is observed by the same loop.
30
31
  */
31
- async drain(execute: (item: T) => Promise<void>): Promise<void> {
32
- if (this.#draining) return;
32
+ drain(execute: (item: T) => Promise<void>): Promise<void> {
33
+ if (this.#activeDrain) return this.#activeDrain;
33
34
  this.#draining = true;
34
- try {
35
- while (this.#items.length > 0) {
36
- const item = this.#items.shift()!;
37
- await execute(item);
35
+ let resolveDrain!: () => void;
36
+ let rejectDrain!: (error: unknown) => void;
37
+ const active = new Promise<void>((resolve, reject) => {
38
+ resolveDrain = resolve;
39
+ rejectDrain = reject;
40
+ });
41
+ // Install the waitable promise before invoking execute: callbacks may call
42
+ // stop() synchronously while the first item is being started.
43
+ this.#activeDrain = active;
44
+ void (async () => {
45
+ try {
46
+ while (this.#items.length > 0) {
47
+ const item = this.#items.shift()!;
48
+ await execute(item);
49
+ }
50
+ } finally {
51
+ this.#draining = false;
52
+ this.#activeDrain = null;
38
53
  }
39
- } finally {
40
- this.#draining = false;
41
- }
54
+ })().then(resolveDrain, rejectDrain);
55
+ return active;
42
56
  }
43
- }
44
57
 
58
+ /** Wait for the active executor, including its current item's finalization. */
59
+ waitForIdle(): Promise<void> {
60
+ return this.#activeDrain ?? Promise.resolve();
61
+ }
62
+ }
@@ -423,6 +423,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
423
423
  private readonly log: Logger;
424
424
  private transcriptWrite: Promise<void> = Promise.resolve();
425
425
  private readonly operations = new AgentConversationQueue<QueueItem>();
426
+ private stopPromise: Promise<void> | null = null;
426
427
  private phase: AgentSessionPhase = "idle";
427
428
  private notificationSeq = 0;
428
429
  private readonly listeners = new Set<AgentSessionListener>();
@@ -2905,11 +2906,27 @@ export class AgentConversation implements AgentClient, Bridgeable {
2905
2906
  stopReason?: string,
2906
2907
  force = false,
2907
2908
  ) => {
2908
- if (!this.v2Transcript || !assistantMessage || (!assistantMessage.dirty && !force)) return;
2909
+ if ((!this.v2Transcript && !this.ownerLifecycle) || !assistantMessage
2910
+ || (!assistantMessage.dirty && !force)) return;
2909
2911
  assistantMessage.revision++;
2910
2912
  assistantMessage.dirty = false;
2911
2913
  const message = assistantMessage;
2912
- this.presentation.queuePresentation({
2914
+ if (this.ownerAgentSessionId && status === "in_progress") {
2915
+ this.queueOwnedRecord({
2916
+ recordId: `${message.id}:snapshot:${message.revision}`,
2917
+ agentSessionId: this.ownerAgentSessionId,
2918
+ agentConversationId: this.agentConversationId,
2919
+ kind: "message",
2920
+ timestamp: new Date().toISOString(),
2921
+ role: "assistant",
2922
+ logicalMessageId: message.id,
2923
+ content: message.text,
2924
+ status,
2925
+ metadata: JSON.stringify({ operationId: item.turnId,
2926
+ ...(message.providerMessageId ? { providerMessageId: message.providerMessageId } : {}) }),
2927
+ });
2928
+ }
2929
+ if (this.v2Transcript) this.presentation.queuePresentation({
2913
2930
  kind: "message",
2914
2931
  operationId: item.turnId,
2915
2932
  role: "assistant",
@@ -2942,7 +2959,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
2942
2959
  item.handlers?.onRecord?.({ current: null, delta: null, emitted: [settledReasoning] });
2943
2960
  }
2944
2961
  response.append(chunk);
2945
- if (this.v2Transcript) {
2962
+ if (this.v2Transcript || this.ownerLifecycle) {
2946
2963
  if (chunk.startsMessage) {
2947
2964
  flushAssistantMessage("completed", undefined, assistantMessage !== null);
2948
2965
  beginAssistantMessage(chunk.messageId);
@@ -3062,6 +3079,7 @@ export class AgentConversation implements AgentClient, Bridgeable {
3062
3079
  });
3063
3080
  }
3064
3081
  const result = Object.freeze({ ...res, operationId: item.turnId, metering: record });
3082
+ await this.ownerRecordWrite;
3065
3083
  await this.ownerLifecycle?.afterPrompt({
3066
3084
  operationId: item.turnId,
3067
3085
  agentSessionId: this.ownerAgentSessionId!,
@@ -3088,6 +3106,9 @@ export class AgentConversation implements AgentClient, Bridgeable {
3088
3106
  ? Object.freeze([{ text }])
3089
3107
  : Object.freeze([]);
3090
3108
  if (!providerSettled) {
3109
+ await this.ownerRecordWrite.catch((persistenceError) => {
3110
+ this.log.warn("owned_runtime_persistence_failed", { error: String(persistenceError) });
3111
+ });
3091
3112
  await this.ownerLifecycle?.promptFailed({
3092
3113
  operationId: item.turnId,
3093
3114
  agentSessionId: this.ownerAgentSessionId!,
@@ -3455,20 +3476,51 @@ export class AgentConversation implements AgentClient, Bridgeable {
3455
3476
  this.controller.interrupt(options);
3456
3477
  }
3457
3478
 
3458
- async stop(): Promise<void> {
3459
- if (this.phase === "stopped") return;
3460
- // Stop is terminal for this stable object. Drop work that never started, interrupt the
3461
- // active turn, and publish stopped before awaiting process teardown so a concurrent
3462
- // prompt cannot slip into a controller that is going away.
3463
- this.interrupt({ clearQueue: true });
3479
+ stop(): Promise<void> {
3480
+ if (this.stopPromise) return this.stopPromise;
3481
+ // Publish the terminal state synchronously. All callers then share the same
3482
+ // completion promise, including callers arriving while teardown is in progress.
3464
3483
  this.phase = "stopped";
3465
- this.emitStateIfChanged();
3466
- await this.controller.stop();
3467
- await this.ownerRecordWrite.catch((error) => {
3468
- this.log.warn("owned_runtime_persistence_failed", { error: String(error) });
3484
+ const failures: unknown[] = [];
3485
+ const completion = Promise.resolve().then(async () => {
3486
+ try {
3487
+ await this.controller.stop();
3488
+ } catch (error) {
3489
+ failures.push(error);
3490
+ }
3491
+ // Closing the provider can reject an active prompt. Its catch/finally path may
3492
+ // enqueue final message and metering writes, so the pre-stop write tail is not
3493
+ // sufficient evidence that persistence is quiescent.
3494
+ try {
3495
+ await this.operations.waitForIdle();
3496
+ } catch (error) {
3497
+ failures.push(error);
3498
+ }
3499
+ await this.ownerRecordWrite.catch((error) => {
3500
+ this.log.warn("owned_runtime_persistence_failed", { error: String(error) });
3501
+ });
3502
+ await this.presentation.drain().catch(() => undefined);
3503
+ try {
3504
+ await this.transcriptWrite;
3505
+ } catch (error) {
3506
+ failures.push(error);
3507
+ }
3508
+ try {
3509
+ await this.v2Transcript?.close();
3510
+ } catch (error) {
3511
+ failures.push(error);
3512
+ }
3513
+ if (failures.length === 1) throw failures[0];
3514
+ if (failures.length > 1) throw new AggregateError(failures, "AgentSession shutdown failed");
3469
3515
  });
3470
- await this.presentation.drain().catch(() => undefined);
3471
- await this.v2Transcript?.close();
3516
+ this.stopPromise = completion;
3517
+ try {
3518
+ this.interrupt({ clearQueue: true });
3519
+ } catch (error) {
3520
+ failures.push(error);
3521
+ }
3522
+ this.emitStateIfChanged();
3523
+ return completion;
3472
3524
  }
3473
3525
 
3474
3526
  // --- mode swap (catalog-affecting) -------------------------------------------
package/src/agent.ts CHANGED
@@ -824,10 +824,18 @@ class DefaultAgentConversationManager implements AgentConversationManager {
824
824
  : { kind: "new" },
825
825
  persistence: false,
826
826
  });
827
- this.live.set(id, conversation);
828
- conversation.subscribe((notification) => {
827
+ const openedConversation = conversation;
828
+ this.live.set(id, openedConversation);
829
+ openedConversation.subscribe((notification) => {
829
830
  if (notification.event.kind === "state_changed" && notification.event.state.phase === "stopped") {
830
- if (this.live.get(id) === conversation) this.live.delete(id);
831
+ // The stopped state is published before the active turn finishes its
832
+ // error/finalization path. Keep it discoverable to stopAll() until stop()
833
+ // has drained those writes, or Agent.close() may close SQLite too early.
834
+ void openedConversation.stop().then(() => {
835
+ if (this.live.get(id) === openedConversation) this.live.delete(id);
836
+ }, () => {
837
+ if (this.live.get(id) === openedConversation) this.live.delete(id);
838
+ });
831
839
  }
832
840
  });
833
841
  if (conversation.internalSessionId && !config.deferProviderSessionPersistence) {
@@ -943,6 +951,7 @@ class PersistedConversationLifecycle implements AgentConversationOwnerLifecycle
943
951
  kind: "message",
944
952
  timestamp,
945
953
  role: "assistant",
954
+ logicalMessageId: `message:${input.operationId}:assistant:${index + 1}`,
946
955
  content: message.text,
947
956
  status,
948
957
  metadata: JSON.stringify({
@@ -968,6 +977,7 @@ class PersistedConversationLifecycle implements AgentConversationOwnerLifecycle
968
977
  kind: "message",
969
978
  timestamp,
970
979
  role: "assistant",
980
+ logicalMessageId: `message:${input.operationId}:assistant:${index + 1}`,
971
981
  content: message.text,
972
982
  status: "failed",
973
983
  metadata: JSON.stringify({
@@ -1007,7 +1017,12 @@ class PersistedConversationLifecycle implements AgentConversationOwnerLifecycle
1007
1017
  }
1008
1018
 
1009
1019
  async record(record: NewConversationRecord): Promise<void> {
1010
- await this.updateIdentity(await this.persistObservations([record]));
1020
+ const streamingSnapshot = record.kind === "message" && record.status === "in_progress";
1021
+ const persisted = await this.persistObservations([record], !streamingSnapshot);
1022
+ // A streaming snapshot is a display revision, not a second completed response.
1023
+ if (!streamingSnapshot) {
1024
+ await this.updateIdentity(persisted);
1025
+ }
1011
1026
  }
1012
1027
 
1013
1028
  async meteringRecorded(record: OperationMeteringRecord): Promise<void> {
@@ -1073,9 +1088,10 @@ class PersistedConversationLifecycle implements AgentConversationOwnerLifecycle
1073
1088
 
1074
1089
  private async persistObservations(
1075
1090
  records: readonly NewConversationRecord[],
1091
+ audit = true,
1076
1092
  ): Promise<readonly ConversationRecord[]> {
1077
1093
  if (records.length === 0) return Object.freeze([]);
1078
- if (!this.settings.auditLog && records.every((record) => {
1094
+ if ((!audit || !this.settings.auditLog) && records.every((record) => {
1079
1095
  if (record.kind !== "protocol") return this.settings.capture[record.kind] === "none";
1080
1096
  return this.settings.capture.protocol.level === "none"
1081
1097
  || !shouldCaptureProtocolMethod(this.settings.capture.protocol, record.method);
@@ -1093,7 +1109,7 @@ class PersistedConversationLifecycle implements AgentConversationOwnerLifecycle
1093
1109
  if (canonicalAccepted) {
1094
1110
  persisted.push(await persistence.records.append(captureRuntimeRecord(record, level)));
1095
1111
  }
1096
- if (this.settings.auditLog) {
1112
+ if (audit && this.settings.auditLog) {
1097
1113
  await enqueueAuditObservation(persistence, {
1098
1114
  scope: "conversation",
1099
1115
  sourceObservationId: record.recordId,
@@ -1103,7 +1119,7 @@ class PersistedConversationLifecycle implements AgentConversationOwnerLifecycle
1103
1119
  }
1104
1120
  }
1105
1121
  });
1106
- if (this.settings.auditLog) this.agent.audit?.notifyPending();
1122
+ if (audit && this.settings.auditLog) this.agent.audit?.notifyPending();
1107
1123
  return Object.freeze(persisted);
1108
1124
  }
1109
1125
 
@@ -72,6 +72,8 @@ export type PersistedContent = string | readonly PersistedContentBlock[];
72
72
 
73
73
  export interface MessageRecord extends ConversationRecordEnvelope<"message"> {
74
74
  readonly role: "assistant" | "user";
75
+ /** Stable identity shared by the snapshots and final revision of one assistant message. */
76
+ readonly logicalMessageId?: string;
75
77
  /** The local agent is implied when omitted on an assistant message. */
76
78
  readonly participantId?: string;
77
79
  /** Opaque JSON supplied by the consumer for this message only. */
@@ -805,6 +805,19 @@ class SqliteConversationMessagePersistence implements ConversationMessagePersist
805
805
  where.push(`m.participant_id IN (${options.participantIds.map(() => "?").join(", ")})`);
806
806
  parameters.push(...options.participantIds);
807
807
  }
808
+ // Message snapshots remain in the ordered record stream, but the message API
809
+ // returns only the latest revision visible at the requested sequence boundary.
810
+ where.push(`(m.logical_message_id IS NULL OR NOT EXISTS (
811
+ SELECT 1 FROM conversation_messages newer_m
812
+ JOIN conversation_records newer_r ON newer_r.row_id = newer_m.record_row_id
813
+ WHERE newer_r.agent_conversation_id = r.agent_conversation_id
814
+ AND newer_m.logical_message_id = m.logical_message_id
815
+ AND newer_r.sequence > r.sequence
816
+ ${options.throughSequence === undefined ? "" : "AND newer_r.sequence <= ?"}
817
+ ))`);
818
+ if (options.throughSequence !== undefined) {
819
+ parameters.push(nonNegativeInteger(options.throughSequence, "throughSequence"));
820
+ }
808
821
  parameters.push(limit + 1, offset);
809
822
  const rows = this.database.query<ConversationRecordRow, SqlValue[]>(
810
823
  `SELECT r.* FROM conversation_records r
@@ -46,8 +46,8 @@ export function insertConversationRecordDetail(
46
46
  run(database,
47
47
  `INSERT INTO conversation_messages(
48
48
  record_row_id, role, participant_id, content_text, content_json, status, search_text,
49
- consumer_metadata_json
50
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
49
+ consumer_metadata_json, logical_message_id
50
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
51
51
  rowId,
52
52
  record.role,
53
53
  record.participantId ?? null,
@@ -56,6 +56,7 @@ export function insertConversationRecordDetail(
56
56
  record.status ?? null,
57
57
  searchableContent(record.content),
58
58
  encodeJson(record.consumerMetadata),
59
+ record.logicalMessageId ?? null,
59
60
  );
60
61
  return;
61
62
  }
@@ -264,6 +265,9 @@ function recordFromRows(
264
265
  ...(detail.consumer_metadata_json !== null
265
266
  ? { consumerMetadata: decodeJson(detail.consumer_metadata_json) }
266
267
  : {}),
268
+ ...(detail.logical_message_id != null
269
+ ? { logicalMessageId: string(detail.logical_message_id) }
270
+ : {}),
267
271
  content: decodeContent(detail.content_text, detail.content_json),
268
272
  ...(detail.status !== null ? { status: string(detail.status) as "in_progress" | "completed" | "cancelled" | "failed" } : {}),
269
273
  });
@@ -1,6 +1,6 @@
1
1
  import type { Database } from "bun:sqlite";
2
2
 
3
- export const SQLITE_AGENT_SCHEMA_VERSION = 10;
3
+ export const SQLITE_AGENT_SCHEMA_VERSION = 11;
4
4
 
5
5
  const BASE_SCHEMA = `
6
6
  CREATE TABLE IF NOT EXISTS schema_migrations (
@@ -90,6 +90,7 @@ CREATE TABLE IF NOT EXISTS conversation_messages (
90
90
  status TEXT CHECK (status IS NULL OR status IN ('in_progress', 'completed', 'cancelled', 'failed')),
91
91
  search_text TEXT NOT NULL,
92
92
  consumer_metadata_json TEXT CHECK (consumer_metadata_json IS NULL OR json_valid(consumer_metadata_json)),
93
+ logical_message_id TEXT,
93
94
  CHECK ((content_text IS NULL) <> (content_json IS NULL)),
94
95
  CHECK (content_json IS NULL OR json_valid(content_json))
95
96
  );
@@ -526,7 +527,8 @@ export function migrateSqliteAgentSchema(database: Database): void {
526
527
  const existing = Number(database.query<{ version: number }, []>(
527
528
  "SELECT COALESCE(MAX(version), 0) AS version FROM schema_migrations",
528
529
  ).get()?.version ?? 0);
529
- if (existing !== 0 && existing !== 8 && existing !== 9 && existing !== SQLITE_AGENT_SCHEMA_VERSION) {
530
+ if (existing !== 0 && existing !== 8 && existing !== 9 && existing !== 10
531
+ && existing !== SQLITE_AGENT_SCHEMA_VERSION) {
530
532
  throw new Error(
531
533
  `SQLite agent schema ${existing} is incompatible with ${SQLITE_AGENT_SCHEMA_VERSION}; recreate the database`,
532
534
  );
@@ -550,6 +552,12 @@ export function migrateSqliteAgentSchema(database: Database): void {
550
552
  ORDER BY r.sequence DESC LIMIT 1
551
553
  )`);
552
554
  }
555
+ if (version > 0 && version < 11) {
556
+ database.exec("ALTER TABLE conversation_messages ADD COLUMN logical_message_id TEXT");
557
+ }
558
+ database.exec(`CREATE INDEX IF NOT EXISTS conversation_messages_logical_idx
559
+ ON conversation_messages(logical_message_id, record_row_id)
560
+ WHERE logical_message_id IS NOT NULL`);
553
561
  if (version < SQLITE_AGENT_SCHEMA_VERSION) {
554
562
  database.query<unknown, [number, string]>(
555
563
  "INSERT INTO schema_migrations(version, applied_at) VALUES (?, ?)",
@@ -52,6 +52,7 @@ export function conversationTimelineItemId(record: ConversationRecord): string {
52
52
  const prefix = `${record.agentConversationId}:${record.kind}:`;
53
53
  const scope = operationScope(record);
54
54
  switch (record.kind) {
55
+ case "message": return `${prefix}${JSON.stringify([record.logicalMessageId ?? record.recordId])}`;
55
56
  case "tool_call": return `${prefix}${JSON.stringify([scope, record.toolCallId])}`;
56
57
  case "permission": return `${prefix}${JSON.stringify([scope, record.permissionId])}`;
57
58
  case "thinking": return `${prefix}${JSON.stringify([scope, record.thinkingId])}`;