@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 +130 -4
- package/package.json +1 -1
- package/src/agent-conversation-owner.ts +6 -1
- package/src/agent-session.ts +84 -6
- package/src/agent.ts +84 -28
- package/src/audit/projection.ts +3 -1
- package/src/identity/checkpoint-backed.ts +248 -0
- package/src/identity.ts +14 -0
- package/src/index.ts +15 -0
- package/src/persistence/backend.ts +68 -1
- package/src/persistence/index.ts +14 -0
- package/src/persistence/sqlite-backend.ts +280 -2
- package/src/persistence/sqlite-conversation-records.ts +11 -2
- package/src/persistence/sqlite-schema.ts +38 -2
- package/src/persistence/timeline-reconcile.ts +73 -0
|
@@ -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)
|
|
551
|
+
const selected = rows.slice(0, limit);
|
|
459
552
|
return Object.freeze({
|
|
460
|
-
|
|
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
|
}
|
|
@@ -661,6 +805,19 @@ class SqliteConversationMessagePersistence implements ConversationMessagePersist
|
|
|
661
805
|
where.push(`m.participant_id IN (${options.participantIds.map(() => "?").join(", ")})`);
|
|
662
806
|
parameters.push(...options.participantIds);
|
|
663
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
|
+
}
|
|
664
821
|
parameters.push(limit + 1, offset);
|
|
665
822
|
const rows = this.database.query<ConversationRecordRow, SqlValue[]>(
|
|
666
823
|
`SELECT r.* FROM conversation_records r
|
|
@@ -1264,6 +1421,85 @@ class SqliteIdentityPersistence implements IdentityPersistence {
|
|
|
1264
1421
|
}
|
|
1265
1422
|
}
|
|
1266
1423
|
|
|
1424
|
+
class SqliteIdentityDeliveryPersistence implements IdentityDeliveryPersistence {
|
|
1425
|
+
constructor(private readonly database: Database, private readonly runWrite: WriteRunner) {}
|
|
1426
|
+
|
|
1427
|
+
async get(
|
|
1428
|
+
targetConversationId: AgentConversationId,
|
|
1429
|
+
targetProviderContextId: string,
|
|
1430
|
+
sourceConversationId: AgentConversationId,
|
|
1431
|
+
): Promise<IdentityDeliveryCursor | null> {
|
|
1432
|
+
const row = this.database.query<{
|
|
1433
|
+
delivered_through_sequence: number;
|
|
1434
|
+
updated_at: string;
|
|
1435
|
+
}, [string, string, string]>(
|
|
1436
|
+
`SELECT delivered_through_sequence, updated_at FROM identity_delivery_cursors
|
|
1437
|
+
WHERE target_conversation_id = ? AND target_provider_context_id = ?
|
|
1438
|
+
AND source_conversation_id = ?`,
|
|
1439
|
+
).get(targetConversationId, targetProviderContextId, sourceConversationId);
|
|
1440
|
+
return row ? Object.freeze({
|
|
1441
|
+
targetConversationId,
|
|
1442
|
+
targetProviderContextId,
|
|
1443
|
+
sourceConversationId,
|
|
1444
|
+
deliveredThroughSequence: Number(row.delivered_through_sequence),
|
|
1445
|
+
updatedAt: row.updated_at,
|
|
1446
|
+
}) : null;
|
|
1447
|
+
}
|
|
1448
|
+
|
|
1449
|
+
async advance(updates: readonly IdentityDeliveryAdvance[]): Promise<void> {
|
|
1450
|
+
if (updates.length === 0) return;
|
|
1451
|
+
await this.runWrite(() => {
|
|
1452
|
+
const now = new Date().toISOString();
|
|
1453
|
+
const statement = this.database.query<unknown, [string, string, string, number, string]>(
|
|
1454
|
+
`INSERT INTO identity_delivery_cursors(
|
|
1455
|
+
target_conversation_id, target_provider_context_id,
|
|
1456
|
+
source_conversation_id, delivered_through_sequence, updated_at
|
|
1457
|
+
) VALUES (?, ?, ?, ?, ?)
|
|
1458
|
+
ON CONFLICT(target_conversation_id, target_provider_context_id, source_conversation_id)
|
|
1459
|
+
DO UPDATE SET
|
|
1460
|
+
delivered_through_sequence = MAX(
|
|
1461
|
+
identity_delivery_cursors.delivered_through_sequence,
|
|
1462
|
+
excluded.delivered_through_sequence
|
|
1463
|
+
),
|
|
1464
|
+
updated_at = excluded.updated_at`,
|
|
1465
|
+
);
|
|
1466
|
+
for (const update of updates) {
|
|
1467
|
+
if (update.targetConversationId === update.sourceConversationId) {
|
|
1468
|
+
throw new Error("identity cannot deliver a conversation to itself");
|
|
1469
|
+
}
|
|
1470
|
+
if (!update.targetProviderContextId.trim()) {
|
|
1471
|
+
throw new Error("identity target provider context id cannot be blank");
|
|
1472
|
+
}
|
|
1473
|
+
const through = nonNegativeInteger(update.deliveredThroughSequence, "identity delivered sequence");
|
|
1474
|
+
if (through === 0) continue;
|
|
1475
|
+
requireConversation(this.database, update.targetConversationId);
|
|
1476
|
+
const source = requireConversation(this.database, update.sourceConversationId);
|
|
1477
|
+
if (through > source.latest_sequence) {
|
|
1478
|
+
throw new Error("identity cursor cannot exceed source conversation sequence");
|
|
1479
|
+
}
|
|
1480
|
+
statement.run(
|
|
1481
|
+
update.targetConversationId,
|
|
1482
|
+
update.targetProviderContextId,
|
|
1483
|
+
update.sourceConversationId,
|
|
1484
|
+
through,
|
|
1485
|
+
now,
|
|
1486
|
+
);
|
|
1487
|
+
}
|
|
1488
|
+
});
|
|
1489
|
+
}
|
|
1490
|
+
|
|
1491
|
+
async reset(targetConversationId: AgentConversationId, targetProviderContextId: string): Promise<void> {
|
|
1492
|
+
if (!targetProviderContextId.trim()) throw new Error("identity target provider context id cannot be blank");
|
|
1493
|
+
await this.runWrite(() => {
|
|
1494
|
+
requireConversation(this.database, targetConversationId);
|
|
1495
|
+
this.database.query<unknown, [string, string]>(
|
|
1496
|
+
`DELETE FROM identity_delivery_cursors
|
|
1497
|
+
WHERE target_conversation_id = ? AND target_provider_context_id = ?`,
|
|
1498
|
+
).run(targetConversationId, targetProviderContextId);
|
|
1499
|
+
});
|
|
1500
|
+
}
|
|
1501
|
+
}
|
|
1502
|
+
|
|
1267
1503
|
class SqliteSearchPersistence implements SearchPersistence {
|
|
1268
1504
|
constructor(private readonly database: Database) {}
|
|
1269
1505
|
|
|
@@ -1646,6 +1882,13 @@ function summaryFromRow(database: Database, row: ConversationRow): AgentConversa
|
|
|
1646
1882
|
kind: participant.kind as ParticipantRef["kind"],
|
|
1647
1883
|
...(participant.name !== null ? { name: participant.name } : {}),
|
|
1648
1884
|
}));
|
|
1885
|
+
return summaryFromRowWithParticipants(row, participants);
|
|
1886
|
+
}
|
|
1887
|
+
|
|
1888
|
+
function summaryFromRowWithParticipants(
|
|
1889
|
+
row: ConversationRow,
|
|
1890
|
+
participants: readonly ParticipantRef[],
|
|
1891
|
+
): AgentConversationSummary {
|
|
1649
1892
|
return Object.freeze({
|
|
1650
1893
|
agentConversationId: row.agent_conversation_id as AgentConversationId,
|
|
1651
1894
|
agentSessionId: row.agent_session_id as AgentSessionId,
|
|
@@ -1858,6 +2101,41 @@ function decodeOffset(cursor: string | undefined): number {
|
|
|
1858
2101
|
return nonNegativeInteger(Number(match[1]), "persistence cursor");
|
|
1859
2102
|
}
|
|
1860
2103
|
|
|
2104
|
+
interface RecentCursor {
|
|
2105
|
+
readonly conversationId: AgentConversationId;
|
|
2106
|
+
readonly snapshotSequence: number;
|
|
2107
|
+
readonly beforeSequence: number;
|
|
2108
|
+
readonly kinds: readonly string[];
|
|
2109
|
+
}
|
|
2110
|
+
|
|
2111
|
+
function encodeRecentCursor(cursor: RecentCursor): string {
|
|
2112
|
+
return Buffer.from(JSON.stringify({ v: 1, ...cursor }), "utf8").toString("base64url");
|
|
2113
|
+
}
|
|
2114
|
+
|
|
2115
|
+
function decodeRecentCursor(
|
|
2116
|
+
encoded: string,
|
|
2117
|
+
conversationId: AgentConversationId,
|
|
2118
|
+
kinds: readonly string[],
|
|
2119
|
+
): RecentCursor {
|
|
2120
|
+
try {
|
|
2121
|
+
if (encoded.length > 4_096) throw new Error();
|
|
2122
|
+
const value = JSON.parse(Buffer.from(encoded, "base64url").toString("utf8")) as Record<string, unknown>;
|
|
2123
|
+
if (value.v !== 1 || value.conversationId !== conversationId
|
|
2124
|
+
|| !Number.isSafeInteger(value.snapshotSequence) || Number(value.snapshotSequence) < 0
|
|
2125
|
+
|| !Number.isSafeInteger(value.beforeSequence) || Number(value.beforeSequence) < 1
|
|
2126
|
+
|| Number(value.beforeSequence) > Number(value.snapshotSequence) + 1
|
|
2127
|
+
|| JSON.stringify(value.kinds) !== JSON.stringify(kinds)) throw new Error();
|
|
2128
|
+
return {
|
|
2129
|
+
conversationId,
|
|
2130
|
+
snapshotSequence: Number(value.snapshotSequence),
|
|
2131
|
+
beforeSequence: Number(value.beforeSequence),
|
|
2132
|
+
kinds,
|
|
2133
|
+
};
|
|
2134
|
+
} catch {
|
|
2135
|
+
throw new Error("invalid or mismatched recent-record cursor");
|
|
2136
|
+
}
|
|
2137
|
+
}
|
|
2138
|
+
|
|
1861
2139
|
async function canonicalSqlitePath(input: string): Promise<string> {
|
|
1862
2140
|
const resolved = resolve(input);
|
|
1863
2141
|
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
|
-
|
|
48
|
+
record_row_id, role, participant_id, content_text, content_json, status, search_text,
|
|
49
|
+
consumer_metadata_json, logical_message_id
|
|
50
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
50
51
|
rowId,
|
|
51
52
|
record.role,
|
|
52
53
|
record.participantId ?? null,
|
|
@@ -54,6 +55,8 @@ export function insertConversationRecordDetail(
|
|
|
54
55
|
content.json,
|
|
55
56
|
record.status ?? null,
|
|
56
57
|
searchableContent(record.content),
|
|
58
|
+
encodeJson(record.consumerMetadata),
|
|
59
|
+
record.logicalMessageId ?? null,
|
|
57
60
|
);
|
|
58
61
|
return;
|
|
59
62
|
}
|
|
@@ -259,6 +262,12 @@ function recordFromRows(
|
|
|
259
262
|
kind: "message",
|
|
260
263
|
role: string(detail.role) as "assistant" | "user",
|
|
261
264
|
...(detail.participant_id !== null ? { participantId: string(detail.participant_id) } : {}),
|
|
265
|
+
...(detail.consumer_metadata_json !== null
|
|
266
|
+
? { consumerMetadata: decodeJson(detail.consumer_metadata_json) }
|
|
267
|
+
: {}),
|
|
268
|
+
...(detail.logical_message_id != null
|
|
269
|
+
? { logicalMessageId: string(detail.logical_message_id) }
|
|
270
|
+
: {}),
|
|
262
271
|
content: decodeContent(detail.content_text, detail.content_json),
|
|
263
272
|
...(detail.status !== null ? { status: string(detail.status) as "in_progress" | "completed" | "cancelled" | "failed" } : {}),
|
|
264
273
|
});
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { Database } from "bun:sqlite";
|
|
2
2
|
|
|
3
|
-
export const SQLITE_AGENT_SCHEMA_VERSION =
|
|
3
|
+
export const SQLITE_AGENT_SCHEMA_VERSION = 11;
|
|
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,8 @@ 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)),
|
|
93
|
+
logical_message_id TEXT,
|
|
91
94
|
CHECK ((content_text IS NULL) <> (content_json IS NULL)),
|
|
92
95
|
CHECK (content_json IS NULL OR json_valid(content_json))
|
|
93
96
|
);
|
|
@@ -399,6 +402,19 @@ CREATE TABLE IF NOT EXISTS identity_snapshots (
|
|
|
399
402
|
created_at TEXT NOT NULL
|
|
400
403
|
);
|
|
401
404
|
|
|
405
|
+
CREATE TABLE IF NOT EXISTS identity_delivery_cursors (
|
|
406
|
+
target_conversation_id TEXT NOT NULL REFERENCES conversations(agent_conversation_id),
|
|
407
|
+
target_provider_context_id TEXT NOT NULL CHECK (length(target_provider_context_id) > 0),
|
|
408
|
+
source_conversation_id TEXT NOT NULL REFERENCES conversations(agent_conversation_id),
|
|
409
|
+
delivered_through_sequence INTEGER NOT NULL CHECK (delivered_through_sequence > 0),
|
|
410
|
+
updated_at TEXT NOT NULL,
|
|
411
|
+
PRIMARY KEY (target_conversation_id, target_provider_context_id, source_conversation_id),
|
|
412
|
+
CHECK (target_conversation_id <> source_conversation_id)
|
|
413
|
+
);
|
|
414
|
+
|
|
415
|
+
CREATE INDEX IF NOT EXISTS identity_delivery_cursors_source_idx
|
|
416
|
+
ON identity_delivery_cursors(source_conversation_id);
|
|
417
|
+
|
|
402
418
|
CREATE TABLE IF NOT EXISTS agent_audit_state (
|
|
403
419
|
singleton INTEGER PRIMARY KEY CHECK (singleton = 1),
|
|
404
420
|
audit_log_id TEXT NOT NULL UNIQUE,
|
|
@@ -511,7 +527,8 @@ export function migrateSqliteAgentSchema(database: Database): void {
|
|
|
511
527
|
const existing = Number(database.query<{ version: number }, []>(
|
|
512
528
|
"SELECT COALESCE(MAX(version), 0) AS version FROM schema_migrations",
|
|
513
529
|
).get()?.version ?? 0);
|
|
514
|
-
if (existing !== 0 && existing !==
|
|
530
|
+
if (existing !== 0 && existing !== 8 && existing !== 9 && existing !== 10
|
|
531
|
+
&& existing !== SQLITE_AGENT_SCHEMA_VERSION) {
|
|
515
532
|
throw new Error(
|
|
516
533
|
`SQLite agent schema ${existing} is incompatible with ${SQLITE_AGENT_SCHEMA_VERSION}; recreate the database`,
|
|
517
534
|
);
|
|
@@ -522,6 +539,25 @@ export function migrateSqliteAgentSchema(database: Database): void {
|
|
|
522
539
|
"SELECT COALESCE(MAX(version), 0) AS version FROM schema_migrations",
|
|
523
540
|
).get();
|
|
524
541
|
const version = Number(row?.version ?? 0);
|
|
542
|
+
if (version > 0 && version < 10) {
|
|
543
|
+
database.exec(`ALTER TABLE conversation_messages ADD COLUMN consumer_metadata_json TEXT
|
|
544
|
+
CHECK (consumer_metadata_json IS NULL OR json_valid(consumer_metadata_json))`);
|
|
545
|
+
database.exec("ALTER TABLE conversations ADD COLUMN last_human_message_at TEXT");
|
|
546
|
+
database.exec(`UPDATE conversations SET last_human_message_at = (
|
|
547
|
+
SELECT r.timestamp FROM conversation_records r
|
|
548
|
+
JOIN conversation_messages m ON m.record_row_id = r.row_id
|
|
549
|
+
JOIN participants p ON p.participant_id = m.participant_id
|
|
550
|
+
WHERE r.agent_conversation_id = conversations.agent_conversation_id
|
|
551
|
+
AND r.kind = 'message' AND m.role = 'user' AND p.kind = 'user'
|
|
552
|
+
ORDER BY r.sequence DESC LIMIT 1
|
|
553
|
+
)`);
|
|
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`);
|
|
525
561
|
if (version < SQLITE_AGENT_SCHEMA_VERSION) {
|
|
526
562
|
database.query<unknown, [number, string]>(
|
|
527
563
|
"INSERT INTO schema_migrations(version, applied_at) VALUES (?, ?)",
|
|
@@ -0,0 +1,73 @@
|
|
|
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 "message": return `${prefix}${JSON.stringify([record.logicalMessageId ?? record.recordId])}`;
|
|
56
|
+
case "tool_call": return `${prefix}${JSON.stringify([scope, record.toolCallId])}`;
|
|
57
|
+
case "permission": return `${prefix}${JSON.stringify([scope, record.permissionId])}`;
|
|
58
|
+
case "thinking": return `${prefix}${JSON.stringify([scope, record.thinkingId])}`;
|
|
59
|
+
case "activity": return `${prefix}${JSON.stringify([scope, record.activityId])}`;
|
|
60
|
+
case "native_action": return `${prefix}${JSON.stringify([record.transitionId ?? record.recordId])}`;
|
|
61
|
+
default: return `${prefix}${JSON.stringify([record.recordId])}`;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function operationScope(record: ConversationRecord): string {
|
|
66
|
+
if (!record.metadata) return "";
|
|
67
|
+
try {
|
|
68
|
+
const parsed = JSON.parse(record.metadata) as { operationId?: unknown };
|
|
69
|
+
return typeof parsed.operationId === "string" ? `${parsed.operationId}:` : "";
|
|
70
|
+
} catch {
|
|
71
|
+
return "";
|
|
72
|
+
}
|
|
73
|
+
}
|