@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.
@@ -16,6 +16,7 @@ import {
16
16
  isConversationRecordKind,
17
17
  normalizeParticipantRef,
18
18
  type AgentConversationSummary,
19
+ type AgentConversationPreview,
19
20
  type AgentAuditState,
20
21
  type AgentMeteringCommitInput,
21
22
  type AgentPersistenceIdentity,
@@ -26,6 +27,7 @@ import {
26
27
  type ConversationListOptions,
27
28
  type ConversationMessagePersistence,
28
29
  type ConversationPage,
30
+ type ConversationPreviewPage,
29
31
  type ConversationPersistence,
30
32
  type ConversationRecord,
31
33
  type ConversationRecordPage,
@@ -33,6 +35,9 @@ import {
33
35
  type ConversationRuntimeCheckpoint,
34
36
  type CreateAgentConversationInput,
35
37
  type IdentityMemoryObservation,
38
+ type IdentityDeliveryAdvance,
39
+ type IdentityDeliveryCursor,
40
+ type IdentityDeliveryPersistence,
36
41
  type IdentityPersistence,
37
42
  type IdentityProjectionState,
38
43
  type MessageListOptions,
@@ -60,6 +65,8 @@ import {
60
65
  type ProviderSessionPersistence,
61
66
  type ProviderSessionRecord,
62
67
  type RecordListOptions,
68
+ type RecentRecordPage,
69
+ type RecentRecordPageOptions,
63
70
  type SearchMatch,
64
71
  type SearchPersistence,
65
72
  type SearchQuery,
@@ -91,6 +98,7 @@ interface ConversationRow {
91
98
  created_at: string;
92
99
  updated_at: string;
93
100
  latest_sequence: number;
101
+ last_human_message_at: string | null;
94
102
  deleted_at: string | null;
95
103
  metadata: string | null;
96
104
  }
@@ -138,6 +146,7 @@ export class SqliteAgentPersistence implements PersistenceBackend {
138
146
  readonly internalInferences: InternalInferenceRepository;
139
147
  readonly recoveryCheckpoints: ConversationRecoveryCheckpointRepository;
140
148
  readonly identity: IdentityPersistence;
149
+ readonly identityDelivery: IdentityDeliveryPersistence;
141
150
  readonly search?: SearchPersistence;
142
151
  readonly auditOutbox: AuditOutboxPersistence;
143
152
  readonly extensions: PersistenceExtensionCatalog;
@@ -176,6 +185,7 @@ export class SqliteAgentPersistence implements PersistenceBackend {
176
185
  this.internalInferences = scope.internalInferences!;
177
186
  this.recoveryCheckpoints = scope.recoveryCheckpoints!;
178
187
  this.identity = scope.identity!;
188
+ this.identityDelivery = scope.identityDelivery!;
179
189
  this.search = fullTextSearch ? new SqliteSearchPersistence(database) : undefined;
180
190
  this.auditOutbox = scope.auditOutbox!;
181
191
  this.extensions = scope.extensions!;
@@ -302,6 +312,7 @@ export class SqliteAgentPersistence implements PersistenceBackend {
302
312
  this.identityRecord.agentSessionId,
303
313
  runWrite,
304
314
  ),
315
+ identityDelivery: new SqliteIdentityDeliveryPersistence(this.database, runWrite),
305
316
  ...(this.capabilities.fullTextSearch
306
317
  ? { search: new SqliteSearchPersistence(this.database) }
307
318
  : {}),
@@ -434,6 +445,88 @@ class SqliteConversationPersistence implements ConversationPersistence {
434
445
  }
435
446
 
436
447
  async list(options: ConversationListOptions = {}): Promise<ConversationPage> {
448
+ const page = this.listRows(options);
449
+ return Object.freeze({
450
+ conversations: Object.freeze(page.rows.map((row) => summaryFromRow(this.database, row))),
451
+ ...(page.nextCursor ? { nextCursor: page.nextCursor } : {}),
452
+ });
453
+ }
454
+
455
+ async listPreviews(options: ConversationListOptions = {}): Promise<ConversationPreviewPage> {
456
+ const page = this.listRows(options);
457
+ if (page.rows.length === 0) return Object.freeze({ previews: Object.freeze([]) });
458
+ const ids = page.rows.map((row) => row.agent_conversation_id);
459
+ const placeholders = ids.map(() => "?").join(", ");
460
+ const participantRows = this.database.query<{
461
+ agent_conversation_id: string;
462
+ participant_id: string;
463
+ kind: string;
464
+ name: string | null;
465
+ }, string[]>(
466
+ `SELECT cp.agent_conversation_id, p.participant_id, p.kind, p.name
467
+ FROM conversation_participants cp
468
+ JOIN participants p ON p.participant_id = cp.participant_id
469
+ WHERE cp.agent_conversation_id IN (${placeholders})
470
+ ORDER BY cp.agent_conversation_id, cp.joined_at, p.participant_id`,
471
+ ).all(...ids);
472
+ const participants = new Map<string, ParticipantRef[]>();
473
+ for (const row of participantRows) {
474
+ const group = participants.get(row.agent_conversation_id) ?? [];
475
+ group.push(Object.freeze({
476
+ id: row.participant_id,
477
+ kind: row.kind as ParticipantRef["kind"],
478
+ ...(row.name !== null ? { name: row.name } : {}),
479
+ }));
480
+ participants.set(row.agent_conversation_id, group);
481
+ }
482
+ const previewRows = this.database.query<{
483
+ agent_conversation_id: string;
484
+ record_id: string | null;
485
+ sequence: number | null;
486
+ timestamp: string | null;
487
+ role: string | null;
488
+ participant_id: string | null;
489
+ preview_text: string | null;
490
+ last_human_message_at: string | null;
491
+ }, string[]>(
492
+ `SELECT c.agent_conversation_id, r.record_id, r.sequence, r.timestamp,
493
+ m.role, m.participant_id,
494
+ substr(COALESCE(m.content_text, m.search_text), 1, 240) AS preview_text,
495
+ c.last_human_message_at
496
+ FROM conversations c
497
+ LEFT JOIN conversation_records r ON r.row_id = (
498
+ SELECT latest_r.row_id FROM conversation_records latest_r
499
+ WHERE latest_r.agent_conversation_id = c.agent_conversation_id AND latest_r.kind = 'message'
500
+ ORDER BY latest_r.sequence DESC LIMIT 1
501
+ )
502
+ LEFT JOIN conversation_messages m ON m.record_row_id = r.row_id
503
+ WHERE c.agent_conversation_id IN (${placeholders})`,
504
+ ).all(...ids);
505
+ const previewsById = new Map(previewRows.map((row) => [row.agent_conversation_id, row]));
506
+ const previews: AgentConversationPreview[] = page.rows.map((row) => {
507
+ const preview = previewsById.get(row.agent_conversation_id)!;
508
+ return Object.freeze({
509
+ conversation: summaryFromRowWithParticipants(row, participants.get(row.agent_conversation_id) ?? []),
510
+ ...(preview.record_id !== null ? { latestMessage: Object.freeze({
511
+ recordId: preview.record_id,
512
+ sequence: Number(preview.sequence),
513
+ timestamp: preview.timestamp!,
514
+ role: preview.role as "assistant" | "user",
515
+ ...(preview.participant_id !== null ? { participantId: preview.participant_id } : {}),
516
+ text: preview.preview_text ?? "",
517
+ }) } : {}),
518
+ ...(preview.last_human_message_at !== null
519
+ ? { lastHumanMessageAt: preview.last_human_message_at }
520
+ : {}),
521
+ });
522
+ });
523
+ return Object.freeze({
524
+ previews: Object.freeze(previews),
525
+ ...(page.nextCursor ? { nextCursor: page.nextCursor } : {}),
526
+ });
527
+ }
528
+
529
+ private listRows(options: ConversationListOptions): { readonly rows: readonly ConversationRow[]; readonly nextCursor?: string } {
437
530
  const limit = boundedInteger(options.limit ?? 50, 1, 500, "conversation limit");
438
531
  const offset = decodeOffset(options.cursor);
439
532
  const where: string[] = ["c.agent_session_id = ?"];
@@ -455,9 +548,9 @@ class SqliteConversationPersistence implements ConversationPersistence {
455
548
  LIMIT ? OFFSET ?`,
456
549
  ).all(...parameters);
457
550
  const hasMore = rows.length > limit;
458
- const selected = rows.slice(0, limit).map((row) => summaryFromRow(this.database, row));
551
+ const selected = rows.slice(0, limit);
459
552
  return Object.freeze({
460
- conversations: Object.freeze(selected),
553
+ rows: Object.freeze(selected),
461
554
  ...(hasMore ? { nextCursor: encodeOffset(offset + limit) } : {}),
462
555
  });
463
556
  }
@@ -575,6 +668,48 @@ class SqliteConversationRecordPersistence implements ConversationRecordPersisten
575
668
  });
576
669
  }
577
670
 
671
+ async listRecent(
672
+ agentConversationId: AgentConversationId,
673
+ options: RecentRecordPageOptions = {},
674
+ ): Promise<RecentRecordPage> {
675
+ const conversation = requireConversation(this.database, agentConversationId);
676
+ const limit = boundedInteger(options.limit ?? 50, 1, 500, "recent record limit");
677
+ const kinds = [...new Set(options.kinds ?? [])].sort();
678
+ for (const kind of kinds) {
679
+ if (!isConversationRecordKind(kind)) throw new Error(`unknown record kind: ${kind}`);
680
+ }
681
+ const cursor = options.olderCursor
682
+ ? decodeRecentCursor(options.olderCursor, agentConversationId, kinds)
683
+ : null;
684
+ const snapshotSequence = cursor?.snapshotSequence ?? Number(conversation.latest_sequence);
685
+ const beforeSequence = cursor?.beforeSequence ?? snapshotSequence + 1;
686
+ const where = ["agent_conversation_id = ?", "sequence <= ?", "sequence < ?"];
687
+ const parameters: SqlValue[] = [agentConversationId, snapshotSequence, beforeSequence];
688
+ if (kinds.length) {
689
+ where.push(`kind IN (${kinds.map(() => "?").join(", ")})`);
690
+ parameters.push(...kinds);
691
+ }
692
+ parameters.push(limit + 1);
693
+ const rows = this.database.query<ConversationRecordRow, SqlValue[]>(
694
+ `SELECT * FROM conversation_records WHERE ${where.join(" AND ")}
695
+ ORDER BY sequence DESC LIMIT ?`,
696
+ ).all(...parameters);
697
+ const selected = rows.slice(0, limit);
698
+ const oldest = selected.at(-1);
699
+ return Object.freeze({
700
+ records: hydrateConversationRecords(this.database, selected.reverse()),
701
+ snapshotSequence,
702
+ ...(rows.length > limit && oldest
703
+ ? { olderCursor: encodeRecentCursor({
704
+ conversationId: agentConversationId,
705
+ snapshotSequence,
706
+ beforeSequence: Number(oldest.sequence),
707
+ kinds,
708
+ }) }
709
+ : {}),
710
+ });
711
+ }
712
+
578
713
  private appendDirect(input: NewConversationRecord): ConversationRecord {
579
714
  if (input.agentSessionId !== this.agentSessionId) {
580
715
  throw new Error("record agentSessionId does not match the SQLite agent database");
@@ -587,6 +722,7 @@ class SqliteConversationRecordPersistence implements ConversationRecordPersisten
587
722
  const normalized = input.kind === "message" && input.role === "user" && !input.participantId
588
723
  ? { ...input, participantId: IMPLICIT_USER_PARTICIPANT_ID }
589
724
  : input;
725
+ let humanMessageAt: string | null = null;
590
726
  if (normalized.kind === "message" && normalized.participantId) {
591
727
  const known = this.database.query<{ kind: ParticipantRef["kind"]; name: string | null }, [string]>(
592
728
  "SELECT kind, name FROM participants WHERE participant_id = ?",
@@ -596,6 +732,9 @@ class SqliteConversationRecordPersistence implements ConversationRecordPersisten
596
732
  kind: known?.kind ?? (normalized.role === "user" ? "user" : "agent"),
597
733
  ...(known?.name ? { name: known.name } : {}),
598
734
  }, normalized.timestamp);
735
+ if (normalized.role === "user" && (known?.kind ?? "user") === "user") {
736
+ humanMessageAt = normalized.timestamp;
737
+ }
599
738
  }
600
739
  const existing = this.database.query<ConversationRecordRow, [string]>(
601
740
  "SELECT * FROM conversation_records WHERE record_id = ?",
@@ -633,6 +772,11 @@ class SqliteConversationRecordPersistence implements ConversationRecordPersisten
633
772
  );
634
773
  if (!inserted) throw new Error(`could not persist conversation record: ${normalized.recordId}`);
635
774
  insertConversationRecordDetail(this.database, Number(inserted.row_id), normalized);
775
+ if (humanMessageAt) {
776
+ runSql(this.database,
777
+ "UPDATE conversations SET last_human_message_at = ? WHERE agent_conversation_id = ?",
778
+ humanMessageAt, normalized.agentConversationId);
779
+ }
636
780
  return Object.freeze({ ...normalized, sequence: next.sequence }) as ConversationRecord;
637
781
  }
638
782
  }
@@ -1264,6 +1408,85 @@ class SqliteIdentityPersistence implements IdentityPersistence {
1264
1408
  }
1265
1409
  }
1266
1410
 
1411
+ class SqliteIdentityDeliveryPersistence implements IdentityDeliveryPersistence {
1412
+ constructor(private readonly database: Database, private readonly runWrite: WriteRunner) {}
1413
+
1414
+ async get(
1415
+ targetConversationId: AgentConversationId,
1416
+ targetProviderContextId: string,
1417
+ sourceConversationId: AgentConversationId,
1418
+ ): Promise<IdentityDeliveryCursor | null> {
1419
+ const row = this.database.query<{
1420
+ delivered_through_sequence: number;
1421
+ updated_at: string;
1422
+ }, [string, string, string]>(
1423
+ `SELECT delivered_through_sequence, updated_at FROM identity_delivery_cursors
1424
+ WHERE target_conversation_id = ? AND target_provider_context_id = ?
1425
+ AND source_conversation_id = ?`,
1426
+ ).get(targetConversationId, targetProviderContextId, sourceConversationId);
1427
+ return row ? Object.freeze({
1428
+ targetConversationId,
1429
+ targetProviderContextId,
1430
+ sourceConversationId,
1431
+ deliveredThroughSequence: Number(row.delivered_through_sequence),
1432
+ updatedAt: row.updated_at,
1433
+ }) : null;
1434
+ }
1435
+
1436
+ async advance(updates: readonly IdentityDeliveryAdvance[]): Promise<void> {
1437
+ if (updates.length === 0) return;
1438
+ await this.runWrite(() => {
1439
+ const now = new Date().toISOString();
1440
+ const statement = this.database.query<unknown, [string, string, string, number, string]>(
1441
+ `INSERT INTO identity_delivery_cursors(
1442
+ target_conversation_id, target_provider_context_id,
1443
+ source_conversation_id, delivered_through_sequence, updated_at
1444
+ ) VALUES (?, ?, ?, ?, ?)
1445
+ ON CONFLICT(target_conversation_id, target_provider_context_id, source_conversation_id)
1446
+ DO UPDATE SET
1447
+ delivered_through_sequence = MAX(
1448
+ identity_delivery_cursors.delivered_through_sequence,
1449
+ excluded.delivered_through_sequence
1450
+ ),
1451
+ updated_at = excluded.updated_at`,
1452
+ );
1453
+ for (const update of updates) {
1454
+ if (update.targetConversationId === update.sourceConversationId) {
1455
+ throw new Error("identity cannot deliver a conversation to itself");
1456
+ }
1457
+ if (!update.targetProviderContextId.trim()) {
1458
+ throw new Error("identity target provider context id cannot be blank");
1459
+ }
1460
+ const through = nonNegativeInteger(update.deliveredThroughSequence, "identity delivered sequence");
1461
+ if (through === 0) continue;
1462
+ requireConversation(this.database, update.targetConversationId);
1463
+ const source = requireConversation(this.database, update.sourceConversationId);
1464
+ if (through > source.latest_sequence) {
1465
+ throw new Error("identity cursor cannot exceed source conversation sequence");
1466
+ }
1467
+ statement.run(
1468
+ update.targetConversationId,
1469
+ update.targetProviderContextId,
1470
+ update.sourceConversationId,
1471
+ through,
1472
+ now,
1473
+ );
1474
+ }
1475
+ });
1476
+ }
1477
+
1478
+ async reset(targetConversationId: AgentConversationId, targetProviderContextId: string): Promise<void> {
1479
+ if (!targetProviderContextId.trim()) throw new Error("identity target provider context id cannot be blank");
1480
+ await this.runWrite(() => {
1481
+ requireConversation(this.database, targetConversationId);
1482
+ this.database.query<unknown, [string, string]>(
1483
+ `DELETE FROM identity_delivery_cursors
1484
+ WHERE target_conversation_id = ? AND target_provider_context_id = ?`,
1485
+ ).run(targetConversationId, targetProviderContextId);
1486
+ });
1487
+ }
1488
+ }
1489
+
1267
1490
  class SqliteSearchPersistence implements SearchPersistence {
1268
1491
  constructor(private readonly database: Database) {}
1269
1492
 
@@ -1646,6 +1869,13 @@ function summaryFromRow(database: Database, row: ConversationRow): AgentConversa
1646
1869
  kind: participant.kind as ParticipantRef["kind"],
1647
1870
  ...(participant.name !== null ? { name: participant.name } : {}),
1648
1871
  }));
1872
+ return summaryFromRowWithParticipants(row, participants);
1873
+ }
1874
+
1875
+ function summaryFromRowWithParticipants(
1876
+ row: ConversationRow,
1877
+ participants: readonly ParticipantRef[],
1878
+ ): AgentConversationSummary {
1649
1879
  return Object.freeze({
1650
1880
  agentConversationId: row.agent_conversation_id as AgentConversationId,
1651
1881
  agentSessionId: row.agent_session_id as AgentSessionId,
@@ -1858,6 +2088,41 @@ function decodeOffset(cursor: string | undefined): number {
1858
2088
  return nonNegativeInteger(Number(match[1]), "persistence cursor");
1859
2089
  }
1860
2090
 
2091
+ interface RecentCursor {
2092
+ readonly conversationId: AgentConversationId;
2093
+ readonly snapshotSequence: number;
2094
+ readonly beforeSequence: number;
2095
+ readonly kinds: readonly string[];
2096
+ }
2097
+
2098
+ function encodeRecentCursor(cursor: RecentCursor): string {
2099
+ return Buffer.from(JSON.stringify({ v: 1, ...cursor }), "utf8").toString("base64url");
2100
+ }
2101
+
2102
+ function decodeRecentCursor(
2103
+ encoded: string,
2104
+ conversationId: AgentConversationId,
2105
+ kinds: readonly string[],
2106
+ ): RecentCursor {
2107
+ try {
2108
+ if (encoded.length > 4_096) throw new Error();
2109
+ const value = JSON.parse(Buffer.from(encoded, "base64url").toString("utf8")) as Record<string, unknown>;
2110
+ if (value.v !== 1 || value.conversationId !== conversationId
2111
+ || !Number.isSafeInteger(value.snapshotSequence) || Number(value.snapshotSequence) < 0
2112
+ || !Number.isSafeInteger(value.beforeSequence) || Number(value.beforeSequence) < 1
2113
+ || Number(value.beforeSequence) > Number(value.snapshotSequence) + 1
2114
+ || JSON.stringify(value.kinds) !== JSON.stringify(kinds)) throw new Error();
2115
+ return {
2116
+ conversationId,
2117
+ snapshotSequence: Number(value.snapshotSequence),
2118
+ beforeSequence: Number(value.beforeSequence),
2119
+ kinds,
2120
+ };
2121
+ } catch {
2122
+ throw new Error("invalid or mismatched recent-record cursor");
2123
+ }
2124
+ }
2125
+
1861
2126
  async function canonicalSqlitePath(input: string): Promise<string> {
1862
2127
  const resolved = resolve(input);
1863
2128
  const parent = dirname(resolved);
@@ -45,8 +45,9 @@ export function insertConversationRecordDetail(
45
45
  const content = encodeContent(record.content);
46
46
  run(database,
47
47
  `INSERT INTO conversation_messages(
48
- record_row_id, role, participant_id, content_text, content_json, status, search_text
49
- ) VALUES (?, ?, ?, ?, ?, ?, ?)`,
48
+ record_row_id, role, participant_id, content_text, content_json, status, search_text,
49
+ consumer_metadata_json
50
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
50
51
  rowId,
51
52
  record.role,
52
53
  record.participantId ?? null,
@@ -54,6 +55,7 @@ export function insertConversationRecordDetail(
54
55
  content.json,
55
56
  record.status ?? null,
56
57
  searchableContent(record.content),
58
+ encodeJson(record.consumerMetadata),
57
59
  );
58
60
  return;
59
61
  }
@@ -259,6 +261,9 @@ function recordFromRows(
259
261
  kind: "message",
260
262
  role: string(detail.role) as "assistant" | "user",
261
263
  ...(detail.participant_id !== null ? { participantId: string(detail.participant_id) } : {}),
264
+ ...(detail.consumer_metadata_json !== null
265
+ ? { consumerMetadata: decodeJson(detail.consumer_metadata_json) }
266
+ : {}),
262
267
  content: decodeContent(detail.content_text, detail.content_json),
263
268
  ...(detail.status !== null ? { status: string(detail.status) as "in_progress" | "completed" | "cancelled" | "failed" } : {}),
264
269
  });
@@ -1,6 +1,6 @@
1
1
  import type { Database } from "bun:sqlite";
2
2
 
3
- export const SQLITE_AGENT_SCHEMA_VERSION = 8;
3
+ export const SQLITE_AGENT_SCHEMA_VERSION = 10;
4
4
 
5
5
  const BASE_SCHEMA = `
6
6
  CREATE TABLE IF NOT EXISTS schema_migrations (
@@ -23,6 +23,7 @@ CREATE TABLE IF NOT EXISTS conversations (
23
23
  created_at TEXT NOT NULL,
24
24
  updated_at TEXT NOT NULL,
25
25
  latest_sequence INTEGER NOT NULL DEFAULT 0 CHECK (latest_sequence >= 0),
26
+ last_human_message_at TEXT,
26
27
  deleted_at TEXT,
27
28
  metadata TEXT
28
29
  );
@@ -88,6 +89,7 @@ CREATE TABLE IF NOT EXISTS conversation_messages (
88
89
  content_json TEXT,
89
90
  status TEXT CHECK (status IS NULL OR status IN ('in_progress', 'completed', 'cancelled', 'failed')),
90
91
  search_text TEXT NOT NULL,
92
+ consumer_metadata_json TEXT CHECK (consumer_metadata_json IS NULL OR json_valid(consumer_metadata_json)),
91
93
  CHECK ((content_text IS NULL) <> (content_json IS NULL)),
92
94
  CHECK (content_json IS NULL OR json_valid(content_json))
93
95
  );
@@ -399,6 +401,19 @@ CREATE TABLE IF NOT EXISTS identity_snapshots (
399
401
  created_at TEXT NOT NULL
400
402
  );
401
403
 
404
+ CREATE TABLE IF NOT EXISTS identity_delivery_cursors (
405
+ target_conversation_id TEXT NOT NULL REFERENCES conversations(agent_conversation_id),
406
+ target_provider_context_id TEXT NOT NULL CHECK (length(target_provider_context_id) > 0),
407
+ source_conversation_id TEXT NOT NULL REFERENCES conversations(agent_conversation_id),
408
+ delivered_through_sequence INTEGER NOT NULL CHECK (delivered_through_sequence > 0),
409
+ updated_at TEXT NOT NULL,
410
+ PRIMARY KEY (target_conversation_id, target_provider_context_id, source_conversation_id),
411
+ CHECK (target_conversation_id <> source_conversation_id)
412
+ );
413
+
414
+ CREATE INDEX IF NOT EXISTS identity_delivery_cursors_source_idx
415
+ ON identity_delivery_cursors(source_conversation_id);
416
+
402
417
  CREATE TABLE IF NOT EXISTS agent_audit_state (
403
418
  singleton INTEGER PRIMARY KEY CHECK (singleton = 1),
404
419
  audit_log_id TEXT NOT NULL UNIQUE,
@@ -511,7 +526,7 @@ export function migrateSqliteAgentSchema(database: Database): void {
511
526
  const existing = Number(database.query<{ version: number }, []>(
512
527
  "SELECT COALESCE(MAX(version), 0) AS version FROM schema_migrations",
513
528
  ).get()?.version ?? 0);
514
- if (existing !== 0 && existing !== SQLITE_AGENT_SCHEMA_VERSION) {
529
+ if (existing !== 0 && existing !== 8 && existing !== 9 && existing !== SQLITE_AGENT_SCHEMA_VERSION) {
515
530
  throw new Error(
516
531
  `SQLite agent schema ${existing} is incompatible with ${SQLITE_AGENT_SCHEMA_VERSION}; recreate the database`,
517
532
  );
@@ -522,6 +537,19 @@ export function migrateSqliteAgentSchema(database: Database): void {
522
537
  "SELECT COALESCE(MAX(version), 0) AS version FROM schema_migrations",
523
538
  ).get();
524
539
  const version = Number(row?.version ?? 0);
540
+ if (version > 0 && version < 10) {
541
+ database.exec(`ALTER TABLE conversation_messages ADD COLUMN consumer_metadata_json TEXT
542
+ CHECK (consumer_metadata_json IS NULL OR json_valid(consumer_metadata_json))`);
543
+ database.exec("ALTER TABLE conversations ADD COLUMN last_human_message_at TEXT");
544
+ database.exec(`UPDATE conversations SET last_human_message_at = (
545
+ SELECT r.timestamp FROM conversation_records r
546
+ JOIN conversation_messages m ON m.record_row_id = r.row_id
547
+ JOIN participants p ON p.participant_id = m.participant_id
548
+ WHERE r.agent_conversation_id = conversations.agent_conversation_id
549
+ AND r.kind = 'message' AND m.role = 'user' AND p.kind = 'user'
550
+ ORDER BY r.sequence DESC LIMIT 1
551
+ )`);
552
+ }
525
553
  if (version < SQLITE_AGENT_SCHEMA_VERSION) {
526
554
  database.query<unknown, [number, string]>(
527
555
  "INSERT INTO schema_migrations(version, applied_at) VALUES (?, ?)",
@@ -0,0 +1,72 @@
1
+ import type { ConversationRecord, ConversationRecordKind } from "./backend.ts";
2
+
3
+ /** One logical chat item, possibly assembled from several immutable lifecycle records. */
4
+ export interface ConversationTimelineItem {
5
+ readonly id: string;
6
+ readonly kind: ConversationRecordKind;
7
+ readonly firstSequence: number;
8
+ readonly lastSequence: number;
9
+ /** Records in canonical order; retain these when rendering lifecycle details. */
10
+ readonly revisions: readonly ConversationRecord[];
11
+ /** Later fields override earlier ones, while omitted fields are retained. */
12
+ readonly current: ConversationRecord;
13
+ }
14
+
15
+ /**
16
+ * Reconcile older pages and live catch-up in any arrival order. Physical record IDs
17
+ * deduplicate replay; logical IDs keep lifecycle updates at the original item position.
18
+ */
19
+ export function reconcileConversationTimeline(
20
+ existing: readonly ConversationTimelineItem[],
21
+ incoming: readonly ConversationRecord[],
22
+ ): readonly ConversationTimelineItem[] {
23
+ const grouped = new Map<string, Map<string, ConversationRecord>>();
24
+ for (const item of existing) {
25
+ grouped.set(item.id, new Map(item.revisions.map((record) => [record.recordId, record])));
26
+ }
27
+ for (const record of incoming) {
28
+ const id = conversationTimelineItemId(record);
29
+ const revisions = grouped.get(id) ?? new Map<string, ConversationRecord>();
30
+ revisions.set(record.recordId, record);
31
+ grouped.set(id, revisions);
32
+ }
33
+ const items: ConversationTimelineItem[] = [];
34
+ for (const [id, records] of grouped) {
35
+ const revisions = [...records.values()].sort((left, right) => left.sequence - right.sequence);
36
+ if (revisions.length === 0) continue;
37
+ items.push(Object.freeze({
38
+ id,
39
+ kind: revisions[0]!.kind,
40
+ firstSequence: revisions[0]!.sequence,
41
+ lastSequence: revisions.at(-1)!.sequence,
42
+ revisions: Object.freeze(revisions),
43
+ current: Object.freeze(Object.assign({}, ...revisions)) as ConversationRecord,
44
+ }));
45
+ }
46
+ items.sort((left, right) => left.firstSequence - right.firstSequence || left.id.localeCompare(right.id));
47
+ return Object.freeze(items);
48
+ }
49
+
50
+ /** Stable within a conversation. Independent messages are never combined. */
51
+ export function conversationTimelineItemId(record: ConversationRecord): string {
52
+ const prefix = `${record.agentConversationId}:${record.kind}:`;
53
+ const scope = operationScope(record);
54
+ switch (record.kind) {
55
+ case "tool_call": return `${prefix}${JSON.stringify([scope, record.toolCallId])}`;
56
+ case "permission": return `${prefix}${JSON.stringify([scope, record.permissionId])}`;
57
+ case "thinking": return `${prefix}${JSON.stringify([scope, record.thinkingId])}`;
58
+ case "activity": return `${prefix}${JSON.stringify([scope, record.activityId])}`;
59
+ case "native_action": return `${prefix}${JSON.stringify([record.transitionId ?? record.recordId])}`;
60
+ default: return `${prefix}${JSON.stringify([record.recordId])}`;
61
+ }
62
+ }
63
+
64
+ function operationScope(record: ConversationRecord): string {
65
+ if (!record.metadata) return "";
66
+ try {
67
+ const parsed = JSON.parse(record.metadata) as { operationId?: unknown };
68
+ return typeof parsed.operationId === "string" ? `${parsed.operationId}:` : "";
69
+ } catch {
70
+ return "";
71
+ }
72
+ }