@qlairoslabs/acp-client 0.7.4 → 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.
Files changed (55) hide show
  1. package/CHANGELOG-audit.md +58 -0
  2. package/CONSUMER_GUIDE.md +571 -19
  3. package/package.json +6 -1
  4. package/src/agent-adapter-registry.ts +66 -0
  5. package/src/agent-conversation-continuation.ts +121 -0
  6. package/src/agent-conversation-contracts.ts +279 -0
  7. package/src/agent-conversation-errors.ts +31 -0
  8. package/src/agent-conversation-owner.ts +60 -0
  9. package/src/agent-conversation-presentation.ts +217 -0
  10. package/src/agent-conversation-queue.ts +44 -0
  11. package/src/agent-conversation.ts +41 -0
  12. package/src/agent-ids.ts +50 -0
  13. package/src/agent-session.ts +1032 -674
  14. package/src/agent.ts +1223 -0
  15. package/src/audit/config.ts +186 -0
  16. package/src/audit/contracts.ts +59 -0
  17. package/src/audit/index.ts +50 -0
  18. package/src/audit/projection.ts +127 -0
  19. package/src/audit/reader.ts +371 -0
  20. package/src/audit/runtime.ts +1060 -0
  21. package/src/checkpointing/config.ts +91 -0
  22. package/src/checkpointing/contracts.ts +45 -0
  23. package/src/checkpointing/coordinator.ts +100 -0
  24. package/src/checkpointing/ids.ts +5 -0
  25. package/src/checkpointing/index.ts +6 -0
  26. package/src/checkpointing/persistence/sqlite-repository.ts +159 -0
  27. package/src/checkpointing/recovery.ts +114 -0
  28. package/src/checkpointing/strategy.ts +139 -0
  29. package/src/identity/checkpoint-backed.ts +248 -0
  30. package/src/identity.ts +76 -0
  31. package/src/index.ts +132 -0
  32. package/src/internal-inference/config.ts +68 -0
  33. package/src/internal-inference/contracts.ts +218 -0
  34. package/src/internal-inference/coordination/handles.ts +133 -0
  35. package/src/internal-inference/coordination/manager.ts +487 -0
  36. package/src/internal-inference/ids.ts +10 -0
  37. package/src/internal-inference/index.ts +10 -0
  38. package/src/internal-inference/persistence/records.ts +132 -0
  39. package/src/internal-inference/persistence/repository.ts +35 -0
  40. package/src/internal-inference/persistence/sqlite-repository.ts +551 -0
  41. package/src/internal-inference/runtime/harness-runtime.ts +78 -0
  42. package/src/internal-inference/strategy/registry.ts +42 -0
  43. package/src/metering/engine.ts +47 -0
  44. package/src/metering/record.ts +4 -1
  45. package/src/observation/contracts.ts +10 -0
  46. package/src/observation/index.ts +8 -0
  47. package/src/observation/subscription-hub.ts +43 -0
  48. package/src/persistence/activity-projection.ts +26 -12
  49. package/src/persistence/backend.ts +839 -0
  50. package/src/persistence/index.ts +113 -0
  51. package/src/persistence/sqlite-backend.ts +2192 -0
  52. package/src/persistence/sqlite-conversation-records.ts +430 -0
  53. package/src/persistence/sqlite-owner-lock.ts +106 -0
  54. package/src/persistence/sqlite-schema.ts +589 -0
  55. package/src/persistence/timeline-reconcile.ts +72 -0
@@ -0,0 +1,589 @@
1
+ import type { Database } from "bun:sqlite";
2
+
3
+ export const SQLITE_AGENT_SCHEMA_VERSION = 10;
4
+
5
+ const BASE_SCHEMA = `
6
+ CREATE TABLE IF NOT EXISTS schema_migrations (
7
+ version INTEGER PRIMARY KEY,
8
+ applied_at TEXT NOT NULL
9
+ );
10
+
11
+ CREATE TABLE IF NOT EXISTS agent_identity (
12
+ singleton INTEGER PRIMARY KEY CHECK (singleton = 1),
13
+ agent_session_id TEXT NOT NULL UNIQUE,
14
+ created_at TEXT NOT NULL,
15
+ updated_at TEXT NOT NULL,
16
+ metadata TEXT
17
+ );
18
+
19
+ CREATE TABLE IF NOT EXISTS conversations (
20
+ agent_conversation_id TEXT PRIMARY KEY,
21
+ agent_session_id TEXT NOT NULL,
22
+ title TEXT,
23
+ created_at TEXT NOT NULL,
24
+ updated_at TEXT NOT NULL,
25
+ latest_sequence INTEGER NOT NULL DEFAULT 0 CHECK (latest_sequence >= 0),
26
+ last_human_message_at TEXT,
27
+ deleted_at TEXT,
28
+ metadata TEXT
29
+ );
30
+
31
+ CREATE INDEX IF NOT EXISTS conversations_updated_idx
32
+ ON conversations(updated_at DESC, agent_conversation_id);
33
+
34
+ CREATE TABLE IF NOT EXISTS participants (
35
+ participant_id TEXT PRIMARY KEY,
36
+ kind TEXT NOT NULL CHECK (kind IN ('agent', 'user', 'external')),
37
+ name TEXT,
38
+ created_at TEXT NOT NULL,
39
+ updated_at TEXT NOT NULL
40
+ );
41
+
42
+ CREATE TABLE IF NOT EXISTS conversation_participants (
43
+ agent_conversation_id TEXT NOT NULL REFERENCES conversations(agent_conversation_id),
44
+ participant_id TEXT NOT NULL REFERENCES participants(participant_id),
45
+ joined_at TEXT NOT NULL,
46
+ PRIMARY KEY (agent_conversation_id, participant_id)
47
+ );
48
+
49
+ CREATE INDEX IF NOT EXISTS conversation_participants_participant_idx
50
+ ON conversation_participants(participant_id, agent_conversation_id);
51
+
52
+ CREATE TABLE IF NOT EXISTS conversation_records (
53
+ row_id INTEGER PRIMARY KEY,
54
+ record_id TEXT NOT NULL UNIQUE,
55
+ agent_session_id TEXT NOT NULL,
56
+ agent_conversation_id TEXT NOT NULL REFERENCES conversations(agent_conversation_id),
57
+ sequence INTEGER NOT NULL CHECK (sequence > 0),
58
+ kind TEXT NOT NULL CHECK (kind IN (
59
+ 'message',
60
+ 'tool_call',
61
+ 'permission',
62
+ 'configuration',
63
+ 'protocol',
64
+ 'native_action',
65
+ 'agent_action',
66
+ 'thinking',
67
+ 'activity',
68
+ 'metering'
69
+ )),
70
+ timestamp TEXT NOT NULL,
71
+ operation_id TEXT,
72
+ metadata TEXT,
73
+ UNIQUE (agent_conversation_id, sequence)
74
+ );
75
+
76
+ CREATE INDEX IF NOT EXISTS conversation_records_kind_idx
77
+ ON conversation_records(agent_conversation_id, kind, sequence);
78
+ CREATE INDEX IF NOT EXISTS conversation_records_time_idx
79
+ ON conversation_records(timestamp, agent_conversation_id);
80
+ CREATE INDEX IF NOT EXISTS conversation_records_operation_idx
81
+ ON conversation_records(agent_conversation_id, operation_id, sequence)
82
+ WHERE operation_id IS NOT NULL;
83
+
84
+ CREATE TABLE IF NOT EXISTS conversation_messages (
85
+ record_row_id INTEGER PRIMARY KEY REFERENCES conversation_records(row_id) ON DELETE CASCADE,
86
+ role TEXT NOT NULL CHECK (role IN ('assistant', 'user')),
87
+ participant_id TEXT REFERENCES participants(participant_id),
88
+ content_text TEXT,
89
+ content_json TEXT,
90
+ status TEXT CHECK (status IS NULL OR status IN ('in_progress', 'completed', 'cancelled', 'failed')),
91
+ search_text TEXT NOT NULL,
92
+ consumer_metadata_json TEXT CHECK (consumer_metadata_json IS NULL OR json_valid(consumer_metadata_json)),
93
+ CHECK ((content_text IS NULL) <> (content_json IS NULL)),
94
+ CHECK (content_json IS NULL OR json_valid(content_json))
95
+ );
96
+
97
+ CREATE INDEX IF NOT EXISTS conversation_messages_participant_idx
98
+ ON conversation_messages(participant_id, record_row_id)
99
+ WHERE participant_id IS NOT NULL;
100
+
101
+ CREATE TABLE IF NOT EXISTS conversation_tool_call_events (
102
+ record_row_id INTEGER PRIMARY KEY REFERENCES conversation_records(row_id) ON DELETE CASCADE,
103
+ tool_call_id TEXT NOT NULL,
104
+ state TEXT NOT NULL CHECK (state IN ('announced', 'input', 'completed', 'failed')),
105
+ name TEXT,
106
+ input_json TEXT,
107
+ output_text TEXT,
108
+ output_json TEXT,
109
+ error TEXT,
110
+ search_text TEXT NOT NULL,
111
+ CHECK (input_json IS NULL OR json_valid(input_json)),
112
+ CHECK (output_json IS NULL OR json_valid(output_json)),
113
+ CHECK (NOT (output_text IS NOT NULL AND output_json IS NOT NULL))
114
+ );
115
+
116
+ CREATE INDEX IF NOT EXISTS conversation_tool_calls_identity_idx
117
+ ON conversation_tool_call_events(tool_call_id, record_row_id);
118
+
119
+ CREATE TABLE IF NOT EXISTS conversation_permission_events (
120
+ record_row_id INTEGER PRIMARY KEY REFERENCES conversation_records(row_id) ON DELETE CASCADE,
121
+ permission_id TEXT NOT NULL,
122
+ state TEXT NOT NULL CHECK (state IN ('requested', 'resolved')),
123
+ request_json TEXT,
124
+ outcome TEXT CHECK (outcome IS NULL OR outcome IN ('approved', 'denied', 'cancelled')),
125
+ CHECK (request_json IS NULL OR json_valid(request_json))
126
+ );
127
+
128
+ CREATE INDEX IF NOT EXISTS conversation_permissions_identity_idx
129
+ ON conversation_permission_events(permission_id, record_row_id);
130
+
131
+ CREATE TABLE IF NOT EXISTS conversation_configuration_events (
132
+ record_row_id INTEGER PRIMARY KEY REFERENCES conversation_records(row_id) ON DELETE CASCADE,
133
+ operation TEXT NOT NULL CHECK (operation IN ('set', 'restore', 'accept_effective', 'replace')),
134
+ config_id TEXT,
135
+ value_json TEXT,
136
+ status TEXT NOT NULL CHECK (status IN ('started', 'completed', 'failed')),
137
+ error TEXT,
138
+ CHECK (value_json IS NULL OR json_valid(value_json))
139
+ );
140
+
141
+ CREATE TABLE IF NOT EXISTS conversation_protocol_records (
142
+ record_row_id INTEGER PRIMARY KEY REFERENCES conversation_records(row_id) ON DELETE CASCADE,
143
+ direction TEXT NOT NULL CHECK (direction IN ('in', 'out', 'error')),
144
+ method TEXT,
145
+ message_json TEXT,
146
+ CHECK (message_json IS NULL OR json_valid(message_json))
147
+ );
148
+
149
+ CREATE TABLE IF NOT EXISTS conversation_native_action_events (
150
+ record_row_id INTEGER PRIMARY KEY REFERENCES conversation_records(row_id) ON DELETE CASCADE,
151
+ action TEXT NOT NULL,
152
+ transition_id TEXT,
153
+ state TEXT NOT NULL CHECK (state IN ('started', 'checkpoint', 'completed', 'failed')),
154
+ input_json TEXT,
155
+ output_json TEXT,
156
+ error TEXT,
157
+ CHECK (input_json IS NULL OR json_valid(input_json)),
158
+ CHECK (output_json IS NULL OR json_valid(output_json))
159
+ );
160
+
161
+ CREATE TABLE IF NOT EXISTS conversation_agent_action_events (
162
+ record_row_id INTEGER PRIMARY KEY REFERENCES conversation_records(row_id) ON DELETE CASCADE,
163
+ action TEXT NOT NULL,
164
+ state TEXT NOT NULL CHECK (state IN ('requested', 'completed', 'failed')),
165
+ input_json TEXT,
166
+ output_json TEXT,
167
+ error TEXT,
168
+ CHECK (input_json IS NULL OR json_valid(input_json)),
169
+ CHECK (output_json IS NULL OR json_valid(output_json))
170
+ );
171
+
172
+ CREATE TABLE IF NOT EXISTS conversation_thinking_events (
173
+ record_row_id INTEGER PRIMARY KEY REFERENCES conversation_records(row_id) ON DELETE CASCADE,
174
+ thinking_id TEXT NOT NULL,
175
+ state TEXT NOT NULL CHECK (state IN ('in_progress', 'completed', 'failed')),
176
+ content_text TEXT,
177
+ content_json TEXT,
178
+ CHECK ((content_text IS NULL) <> (content_json IS NULL)),
179
+ CHECK (content_json IS NULL OR json_valid(content_json))
180
+ );
181
+
182
+ CREATE INDEX IF NOT EXISTS conversation_thinking_identity_idx
183
+ ON conversation_thinking_events(thinking_id, record_row_id);
184
+
185
+ CREATE TABLE IF NOT EXISTS conversation_activity_events (
186
+ record_row_id INTEGER PRIMARY KEY REFERENCES conversation_records(row_id) ON DELETE CASCADE,
187
+ activity_id TEXT NOT NULL,
188
+ activity_type TEXT NOT NULL,
189
+ state TEXT NOT NULL CHECK (state IN ('in_progress', 'completed', 'failed')),
190
+ content_text TEXT,
191
+ content_json TEXT,
192
+ data_json TEXT,
193
+ search_text TEXT NOT NULL,
194
+ CHECK (NOT (content_text IS NOT NULL AND content_json IS NOT NULL)),
195
+ CHECK (content_json IS NULL OR json_valid(content_json)),
196
+ CHECK (data_json IS NULL OR json_valid(data_json))
197
+ );
198
+
199
+ CREATE INDEX IF NOT EXISTS conversation_activities_identity_idx
200
+ ON conversation_activity_events(activity_id, record_row_id);
201
+
202
+ CREATE TABLE IF NOT EXISTS conversation_metering_references (
203
+ record_row_id INTEGER PRIMARY KEY REFERENCES conversation_records(row_id) ON DELETE CASCADE,
204
+ operation_id TEXT NOT NULL,
205
+ metering_record_id TEXT NOT NULL,
206
+ status TEXT NOT NULL CHECK (status IN ('available', 'partial', 'unavailable'))
207
+ );
208
+
209
+ CREATE INDEX IF NOT EXISTS conversation_metering_operation_idx
210
+ ON conversation_metering_references(operation_id, record_row_id);
211
+
212
+ CREATE TABLE IF NOT EXISTS conversation_checkpoints (
213
+ agent_conversation_id TEXT PRIMARY KEY REFERENCES conversations(agent_conversation_id),
214
+ revision INTEGER NOT NULL CHECK (revision >= 0),
215
+ covered_sequence INTEGER NOT NULL CHECK (covered_sequence >= 0),
216
+ state_json TEXT NOT NULL,
217
+ updated_at TEXT NOT NULL
218
+ );
219
+
220
+ CREATE TABLE IF NOT EXISTS provider_sessions (
221
+ provider_session_record_id TEXT PRIMARY KEY,
222
+ agent_conversation_id TEXT NOT NULL REFERENCES conversations(agent_conversation_id),
223
+ internal_session_id TEXT NOT NULL,
224
+ adapter_id TEXT NOT NULL,
225
+ mode TEXT NOT NULL,
226
+ model TEXT,
227
+ activated_at TEXT NOT NULL,
228
+ deactivated_at TEXT,
229
+ transition_id TEXT,
230
+ metadata TEXT
231
+ );
232
+
233
+ CREATE INDEX IF NOT EXISTS provider_sessions_conversation_idx
234
+ ON provider_sessions(agent_conversation_id, activated_at, provider_session_record_id);
235
+ CREATE UNIQUE INDEX IF NOT EXISTS provider_sessions_one_active_idx
236
+ ON provider_sessions(agent_conversation_id) WHERE deactivated_at IS NULL;
237
+
238
+ CREATE TABLE IF NOT EXISTS metering_records (
239
+ agent_conversation_id TEXT NOT NULL REFERENCES conversations(agent_conversation_id),
240
+ operation_id TEXT NOT NULL,
241
+ internal_session_id TEXT,
242
+ adapter_id TEXT NOT NULL,
243
+ operation_kind TEXT NOT NULL,
244
+ outcome TEXT NOT NULL,
245
+ completed_at INTEGER NOT NULL,
246
+ record_json TEXT,
247
+ PRIMARY KEY (agent_conversation_id, operation_id)
248
+ );
249
+
250
+ CREATE INDEX IF NOT EXISTS metering_records_conversation_idx
251
+ ON metering_records(agent_conversation_id, completed_at, operation_id);
252
+ CREATE INDEX IF NOT EXISTS metering_records_internal_session_idx
253
+ ON metering_records(internal_session_id, completed_at);
254
+
255
+ CREATE TABLE IF NOT EXISTS conversation_metering_state (
256
+ agent_conversation_id TEXT PRIMARY KEY REFERENCES conversations(agent_conversation_id),
257
+ revision INTEGER NOT NULL CHECK (revision >= 1),
258
+ state_json TEXT NOT NULL,
259
+ updated_at TEXT NOT NULL
260
+ );
261
+
262
+ CREATE TABLE IF NOT EXISTS agent_metering_records (
263
+ agent_session_id TEXT NOT NULL,
264
+ operation_id TEXT NOT NULL,
265
+ internal_session_id TEXT,
266
+ adapter_id TEXT NOT NULL,
267
+ operation_kind TEXT NOT NULL,
268
+ outcome TEXT NOT NULL,
269
+ completed_at INTEGER NOT NULL,
270
+ record_json TEXT,
271
+ PRIMARY KEY (agent_session_id, operation_id)
272
+ );
273
+
274
+ CREATE INDEX IF NOT EXISTS agent_metering_records_scope_idx
275
+ ON agent_metering_records(agent_session_id, completed_at, operation_id);
276
+
277
+ CREATE TABLE IF NOT EXISTS agent_metering_state (
278
+ agent_session_id TEXT PRIMARY KEY,
279
+ revision INTEGER NOT NULL CHECK (revision >= 1),
280
+ state_json TEXT NOT NULL,
281
+ updated_at TEXT NOT NULL
282
+ );
283
+
284
+ CREATE TABLE IF NOT EXISTS internal_inference_chains (
285
+ root_internal_inference_id TEXT PRIMARY KEY,
286
+ agent_session_id TEXT NOT NULL,
287
+ agent_conversation_id TEXT REFERENCES conversations(agent_conversation_id),
288
+ purpose TEXT NOT NULL,
289
+ status TEXT NOT NULL CHECK (status IN ('active', 'completed', 'failed', 'cancelled')),
290
+ active_internal_inference_id TEXT,
291
+ requested_through_sequence INTEGER CHECK (
292
+ requested_through_sequence IS NULL OR requested_through_sequence >= 0
293
+ ),
294
+ revision INTEGER NOT NULL DEFAULT 1 CHECK (revision >= 1),
295
+ created_at TEXT NOT NULL,
296
+ updated_at TEXT NOT NULL,
297
+ error TEXT
298
+ );
299
+
300
+ DROP INDEX IF EXISTS internal_inference_one_active_chain_idx;
301
+ CREATE UNIQUE INDEX IF NOT EXISTS internal_inference_one_active_checkpoint_chain_idx
302
+ ON internal_inference_chains(
303
+ agent_session_id,
304
+ COALESCE(agent_conversation_id, ''),
305
+ purpose
306
+ ) WHERE status = 'active' AND purpose = 'conversation_checkpoint';
307
+
308
+ CREATE TABLE IF NOT EXISTS internal_inferences (
309
+ internal_inference_id TEXT PRIMARY KEY,
310
+ root_internal_inference_id TEXT NOT NULL REFERENCES internal_inference_chains(root_internal_inference_id),
311
+ retry_of_internal_inference_id TEXT REFERENCES internal_inferences(internal_inference_id),
312
+ attempt_number INTEGER NOT NULL CHECK (attempt_number >= 1),
313
+ agent_session_id TEXT NOT NULL,
314
+ agent_conversation_id TEXT REFERENCES conversations(agent_conversation_id),
315
+ purpose TEXT NOT NULL,
316
+ status TEXT NOT NULL CHECK (status IN ('queued', 'running', 'completed', 'failed', 'cancelled')),
317
+ adapter_id TEXT NOT NULL,
318
+ execution_profile_id TEXT,
319
+ input_json TEXT NOT NULL,
320
+ model TEXT,
321
+ internal_session_id TEXT,
322
+ source_checkpoint_id TEXT,
323
+ source_from_sequence INTEGER CHECK (source_from_sequence IS NULL OR source_from_sequence >= 0),
324
+ source_through_sequence INTEGER CHECK (source_through_sequence IS NULL OR source_through_sequence >= 0),
325
+ requested_at TEXT NOT NULL,
326
+ started_at TEXT,
327
+ completed_at TEXT,
328
+ next_attempt_at TEXT,
329
+ worker_id TEXT,
330
+ lease_token TEXT,
331
+ lease_expires_at TEXT,
332
+ heartbeat_at TEXT,
333
+ revision INTEGER NOT NULL DEFAULT 1 CHECK (revision >= 1),
334
+ result_json TEXT,
335
+ error TEXT,
336
+ failure_code TEXT,
337
+ metering_operation_id TEXT,
338
+ metadata TEXT,
339
+ UNIQUE (root_internal_inference_id, attempt_number)
340
+ );
341
+
342
+ CREATE INDEX IF NOT EXISTS internal_inferences_claim_idx
343
+ ON internal_inferences(status, next_attempt_at, requested_at, internal_inference_id);
344
+ CREATE INDEX IF NOT EXISTS internal_inferences_chain_idx
345
+ ON internal_inferences(root_internal_inference_id, attempt_number);
346
+ CREATE INDEX IF NOT EXISTS internal_inferences_lease_idx
347
+ ON internal_inferences(status, lease_expires_at);
348
+
349
+ CREATE TABLE IF NOT EXISTS conversation_recovery_checkpoints (
350
+ checkpoint_id TEXT PRIMARY KEY,
351
+ agent_conversation_id TEXT NOT NULL REFERENCES conversations(agent_conversation_id),
352
+ revision INTEGER NOT NULL CHECK (revision >= 1),
353
+ covered_sequence INTEGER NOT NULL CHECK (covered_sequence >= 1),
354
+ previous_checkpoint_id TEXT REFERENCES conversation_recovery_checkpoints(checkpoint_id),
355
+ generator_internal_inference_id TEXT NOT NULL UNIQUE REFERENCES internal_inferences(internal_inference_id),
356
+ summary TEXT NOT NULL CHECK (length(summary) > 0),
357
+ created_at TEXT NOT NULL,
358
+ metadata TEXT,
359
+ UNIQUE (agent_conversation_id, revision),
360
+ UNIQUE (agent_conversation_id, covered_sequence)
361
+ );
362
+
363
+ CREATE INDEX IF NOT EXISTS recovery_checkpoints_latest_idx
364
+ ON conversation_recovery_checkpoints(agent_conversation_id, revision DESC);
365
+
366
+ CREATE TABLE IF NOT EXISTS identity_state (
367
+ singleton INTEGER PRIMARY KEY CHECK (singleton = 1),
368
+ observed_through_sequence INTEGER NOT NULL DEFAULT 0,
369
+ processed_through_sequence INTEGER NOT NULL DEFAULT 0,
370
+ active_snapshot_id TEXT
371
+ );
372
+
373
+ INSERT OR IGNORE INTO identity_state(
374
+ singleton, observed_through_sequence, processed_through_sequence
375
+ ) VALUES (1, 0, 0);
376
+
377
+ CREATE TABLE IF NOT EXISTS identity_memories (
378
+ memory_id TEXT PRIMARY KEY,
379
+ agent_session_id TEXT NOT NULL,
380
+ sequence INTEGER NOT NULL UNIQUE CHECK (sequence > 0),
381
+ source_conversation_id TEXT NOT NULL REFERENCES conversations(agent_conversation_id),
382
+ source_record_ids_json TEXT NOT NULL,
383
+ participant_id TEXT,
384
+ kind TEXT NOT NULL,
385
+ content_json TEXT NOT NULL,
386
+ created_at TEXT NOT NULL,
387
+ metadata TEXT
388
+ );
389
+
390
+ CREATE INDEX IF NOT EXISTS identity_memories_source_idx
391
+ ON identity_memories(source_conversation_id, sequence);
392
+ CREATE INDEX IF NOT EXISTS identity_memories_participant_idx
393
+ ON identity_memories(participant_id, sequence);
394
+
395
+ CREATE TABLE IF NOT EXISTS identity_snapshots (
396
+ snapshot_id TEXT PRIMARY KEY,
397
+ agent_session_id TEXT NOT NULL,
398
+ version INTEGER NOT NULL UNIQUE CHECK (version >= 0),
399
+ processed_through_sequence INTEGER NOT NULL CHECK (processed_through_sequence >= 0),
400
+ value_json TEXT NOT NULL,
401
+ created_at TEXT NOT NULL
402
+ );
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
+
417
+ CREATE TABLE IF NOT EXISTS agent_audit_state (
418
+ singleton INTEGER PRIMARY KEY CHECK (singleton = 1),
419
+ audit_log_id TEXT NOT NULL UNIQUE,
420
+ last_allocated_sequence INTEGER NOT NULL DEFAULT 0 CHECK (last_allocated_sequence >= 0),
421
+ last_delivered_sequence INTEGER NOT NULL DEFAULT 0 CHECK (
422
+ last_delivered_sequence >= 0 AND last_delivered_sequence <= last_allocated_sequence
423
+ ),
424
+ capture_fingerprint TEXT NOT NULL,
425
+ created_at TEXT NOT NULL,
426
+ updated_at TEXT NOT NULL
427
+ );
428
+
429
+ CREATE TABLE IF NOT EXISTS audit_outbox (
430
+ outbox_id TEXT PRIMARY KEY,
431
+ audit_sequence INTEGER NOT NULL UNIQUE CHECK (audit_sequence > 0),
432
+ source_observation_id TEXT NOT NULL UNIQUE,
433
+ source_record_id TEXT,
434
+ operation_id TEXT,
435
+ agent_conversation_id TEXT REFERENCES conversations(agent_conversation_id),
436
+ occurred_at TEXT NOT NULL,
437
+ kind TEXT NOT NULL,
438
+ capture_level TEXT NOT NULL,
439
+ capture_fingerprint TEXT NOT NULL,
440
+ payload_json TEXT NOT NULL CHECK (json_valid(payload_json)),
441
+ payload_sha256 TEXT NOT NULL,
442
+ payload_bytes INTEGER NOT NULL CHECK (payload_bytes >= 0),
443
+ created_at TEXT NOT NULL,
444
+ attempt_count INTEGER NOT NULL DEFAULT 0 CHECK (attempt_count >= 0),
445
+ next_attempt_at TEXT,
446
+ last_error TEXT
447
+ );
448
+
449
+ CREATE INDEX IF NOT EXISTS audit_outbox_pending_idx
450
+ ON audit_outbox(audit_sequence);
451
+
452
+ CREATE TABLE IF NOT EXISTS persistence_extensions (
453
+ extension_id TEXT PRIMARY KEY,
454
+ schema_version INTEGER NOT NULL CHECK (schema_version >= 0),
455
+ installed_at TEXT NOT NULL,
456
+ updated_at TEXT NOT NULL
457
+ );
458
+ `;
459
+
460
+ const FTS_SCHEMA = `
461
+ CREATE VIRTUAL TABLE IF NOT EXISTS conversation_messages_fts USING fts5(
462
+ search_text,
463
+ content = 'conversation_messages',
464
+ content_rowid = 'record_row_id',
465
+ tokenize = 'unicode61'
466
+ );
467
+
468
+ CREATE TRIGGER IF NOT EXISTS conversation_messages_fts_insert
469
+ AFTER INSERT ON conversation_messages BEGIN
470
+ INSERT INTO conversation_messages_fts(rowid, search_text)
471
+ VALUES (new.record_row_id, new.search_text);
472
+ END;
473
+
474
+ CREATE TRIGGER IF NOT EXISTS conversation_messages_fts_delete
475
+ AFTER DELETE ON conversation_messages BEGIN
476
+ INSERT INTO conversation_messages_fts(conversation_messages_fts, rowid, search_text)
477
+ VALUES ('delete', old.record_row_id, old.search_text);
478
+ END;
479
+
480
+ CREATE VIRTUAL TABLE IF NOT EXISTS conversation_tool_calls_fts USING fts5(
481
+ search_text,
482
+ content = 'conversation_tool_call_events',
483
+ content_rowid = 'record_row_id',
484
+ tokenize = 'unicode61'
485
+ );
486
+
487
+ CREATE TRIGGER IF NOT EXISTS conversation_tool_calls_fts_insert
488
+ AFTER INSERT ON conversation_tool_call_events BEGIN
489
+ INSERT INTO conversation_tool_calls_fts(rowid, search_text)
490
+ VALUES (new.record_row_id, new.search_text);
491
+ END;
492
+
493
+ CREATE TRIGGER IF NOT EXISTS conversation_tool_calls_fts_delete
494
+ AFTER DELETE ON conversation_tool_call_events BEGIN
495
+ INSERT INTO conversation_tool_calls_fts(conversation_tool_calls_fts, rowid, search_text)
496
+ VALUES ('delete', old.record_row_id, old.search_text);
497
+ END;
498
+
499
+ CREATE VIRTUAL TABLE IF NOT EXISTS conversation_activities_fts USING fts5(
500
+ search_text,
501
+ content = 'conversation_activity_events',
502
+ content_rowid = 'record_row_id',
503
+ tokenize = 'unicode61'
504
+ );
505
+
506
+ CREATE TRIGGER IF NOT EXISTS conversation_activities_fts_insert
507
+ AFTER INSERT ON conversation_activity_events BEGIN
508
+ INSERT INTO conversation_activities_fts(rowid, search_text)
509
+ VALUES (new.record_row_id, new.search_text);
510
+ END;
511
+
512
+ CREATE TRIGGER IF NOT EXISTS conversation_activities_fts_delete
513
+ AFTER DELETE ON conversation_activity_events BEGIN
514
+ INSERT INTO conversation_activities_fts(conversation_activities_fts, rowid, search_text)
515
+ VALUES ('delete', old.record_row_id, old.search_text);
516
+ END;
517
+ `;
518
+
519
+ export function migrateSqliteAgentSchema(database: Database): void {
520
+ database.exec("BEGIN IMMEDIATE");
521
+ try {
522
+ const hasMigrations = database.query<{ present: number }, []>(
523
+ "SELECT 1 AS present FROM sqlite_master WHERE type = 'table' AND name = 'schema_migrations'",
524
+ ).get() !== null;
525
+ if (hasMigrations) {
526
+ const existing = Number(database.query<{ version: number }, []>(
527
+ "SELECT COALESCE(MAX(version), 0) AS version FROM schema_migrations",
528
+ ).get()?.version ?? 0);
529
+ if (existing !== 0 && existing !== 8 && existing !== 9 && existing !== SQLITE_AGENT_SCHEMA_VERSION) {
530
+ throw new Error(
531
+ `SQLite agent schema ${existing} is incompatible with ${SQLITE_AGENT_SCHEMA_VERSION}; recreate the database`,
532
+ );
533
+ }
534
+ }
535
+ database.exec(BASE_SCHEMA);
536
+ const row = database.query<{ version: number }, []>(
537
+ "SELECT COALESCE(MAX(version), 0) AS version FROM schema_migrations",
538
+ ).get();
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
+ }
553
+ if (version < SQLITE_AGENT_SCHEMA_VERSION) {
554
+ database.query<unknown, [number, string]>(
555
+ "INSERT INTO schema_migrations(version, applied_at) VALUES (?, ?)",
556
+ ).run(SQLITE_AGENT_SCHEMA_VERSION, new Date().toISOString());
557
+ }
558
+ database.exec("COMMIT");
559
+ } catch (error) {
560
+ if (database.inTransaction) database.exec("ROLLBACK");
561
+ throw error;
562
+ }
563
+ }
564
+
565
+ export function installSqliteFts(database: Database): boolean {
566
+ const row = database.query<{ enabled: number }, []>(
567
+ "SELECT sqlite_compileoption_used('ENABLE_FTS5') AS enabled",
568
+ ).get();
569
+ if (Number(row?.enabled ?? 0) !== 1) return false;
570
+
571
+ const existed = ["conversation_messages_fts", "conversation_tool_calls_fts", "conversation_activities_fts"]
572
+ .every((name) => database.query<{ present: number }, [string]>(
573
+ "SELECT 1 AS present FROM sqlite_master WHERE type = 'table' AND name = ?",
574
+ ).get(name) !== null);
575
+ database.exec("BEGIN IMMEDIATE");
576
+ try {
577
+ database.exec(FTS_SCHEMA);
578
+ if (!existed) {
579
+ database.exec("INSERT INTO conversation_messages_fts(conversation_messages_fts) VALUES ('rebuild')");
580
+ database.exec("INSERT INTO conversation_tool_calls_fts(conversation_tool_calls_fts) VALUES ('rebuild')");
581
+ database.exec("INSERT INTO conversation_activities_fts(conversation_activities_fts) VALUES ('rebuild')");
582
+ }
583
+ database.exec("COMMIT");
584
+ return true;
585
+ } catch (error) {
586
+ if (database.inTransaction) database.exec("ROLLBACK");
587
+ throw error;
588
+ }
589
+ }
@@ -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
+ }