@qlairoslabs/acp-client 0.11.0 → 0.12.0
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/CHANGELOG-consumer-fixes.md +55 -0
- package/CHANGELOG-operation-lifecycle.md +64 -0
- package/CONSUMER_GUIDE.md +311 -17
- package/MIGRATION-0.10-to-0.12.md +189 -0
- package/README.md +6 -3
- package/package.json +5 -2
- package/src/adapters.ts +3 -1
- package/src/agent/adoption/checkpoint-floor.ts +47 -0
- package/src/agent/adoption/index.ts +3 -1
- package/src/agent/adoption/replay.ts +15 -0
- package/src/agent/config.ts +4 -0
- package/src/agent/conversation-manager.ts +223 -153
- package/src/agent/error-record-writer.ts +77 -0
- package/src/agent/persisted-lifecycle.ts +152 -35
- package/src/agent/record-capture.ts +18 -18
- package/src/agent-adapter-registry.ts +2 -0
- package/src/agent-client.ts +9 -3
- package/src/agent-conversation-contracts.ts +6 -0
- package/src/agent-conversation-owner.ts +31 -6
- package/src/agent-conversation-presentation.ts +12 -1
- package/src/agent-conversation-queue.ts +3 -2
- package/src/agent-session.ts +537 -96
- package/src/agent.ts +46 -23
- package/src/audit/config.ts +4 -0
- package/src/audit/projection.ts +3 -0
- package/src/checkpointing/contracts.ts +28 -3
- package/src/checkpointing/persistence/sqlite-repository.ts +36 -8
- package/src/checkpointing/recovery.ts +9 -2
- package/src/checkpointing/strategy.ts +27 -2
- package/src/client.ts +120 -30
- package/src/controller.ts +116 -7
- package/src/degraded/pty-client.ts +25 -1
- package/src/identity/checkpoint-backed.ts +2 -2
- package/src/index.ts +17 -0
- package/src/internal-inference/config.ts +7 -0
- package/src/internal-inference/contracts.ts +3 -0
- package/src/internal-inference/coordination/handles.ts +11 -2
- package/src/internal-inference/coordination/manager.ts +20 -3
- package/src/internal-inference/index.ts +2 -0
- package/src/internal-inference/persistence/records.ts +3 -1
- package/src/internal-inference/persistence/sqlite-repository.ts +4 -1
- package/src/internal-inference/runtime/disposable-session-env.ts +84 -0
- package/src/internal-inference/runtime/harness-runtime.ts +19 -2
- package/src/media/acp.ts +118 -0
- package/src/media/capture.ts +15 -0
- package/src/media/content.ts +142 -0
- package/src/media/files.ts +28 -0
- package/src/media/parts.ts +145 -0
- package/src/media/pending.ts +51 -0
- package/src/media/redact.ts +14 -0
- package/src/media/store.ts +127 -0
- package/src/metering/provider.ts +8 -1
- package/src/operations/activity-tracker.ts +31 -0
- package/src/operations/contracts.ts +63 -0
- package/src/operations/errors.ts +31 -0
- package/src/operations/index.ts +6 -0
- package/src/operations/stale-policy.ts +51 -0
- package/src/operations/supervisor.ts +209 -0
- package/src/operations/timers.ts +12 -0
- package/src/out-of-band-messages.ts +49 -32
- package/src/persistence/audit-runtime.ts +14 -2
- package/src/persistence/backend.ts +108 -12
- package/src/persistence/error-records.ts +27 -0
- package/src/persistence/index.ts +8 -0
- package/src/persistence/presentation.ts +9 -1
- package/src/persistence/projection.ts +20 -0
- package/src/persistence/records.ts +45 -6
- package/src/persistence/sqlite-backend.ts +207 -16
- package/src/persistence/sqlite-conversation-records.ts +31 -4
- package/src/persistence/sqlite-files.ts +95 -0
- package/src/persistence/sqlite-media-store.ts +67 -0
- package/src/persistence/sqlite-schema.ts +146 -13
- package/src/persistence/state-runtime.ts +2 -0
- package/src/persistence/timeline-reconcile.ts +21 -4
- package/src/persistence/transcript-reader.ts +11 -4
- package/src/persistence/transcript-runtime.ts +105 -12
- package/src/repl/repl.ts +1 -1
- package/src/response.ts +40 -8
- package/src/steering/combine.ts +11 -4
- package/src/steering/contracts.ts +14 -4
- package/src/steering/controller.ts +96 -21
- package/src/steering/index.ts +1 -0
- package/src/transport/acp-transport.ts +18 -7
- package/src/types.ts +7 -0
- package/src/updates.ts +4 -4
|
@@ -48,6 +48,7 @@ import {
|
|
|
48
48
|
type MeteringRecordListOptions,
|
|
49
49
|
type MeteringRecordPage,
|
|
50
50
|
type NewConversationRecord,
|
|
51
|
+
type OutOfBandDeliveryPersistence,
|
|
51
52
|
type NewAuditOutboxItem,
|
|
52
53
|
type NewIdentityMemoryObservation,
|
|
53
54
|
type ParticipantRef,
|
|
@@ -65,6 +66,8 @@ import {
|
|
|
65
66
|
type ProviderSessionPersistence,
|
|
66
67
|
type ProviderSessionRecord,
|
|
67
68
|
type RecordListOptions,
|
|
69
|
+
type RecentItemPage,
|
|
70
|
+
type RecentItemPageOptions,
|
|
68
71
|
type RecentRecordPage,
|
|
69
72
|
type RecentRecordPageOptions,
|
|
70
73
|
type SearchMatch,
|
|
@@ -88,6 +91,15 @@ import {
|
|
|
88
91
|
} from "./sqlite-conversation-records.ts";
|
|
89
92
|
import { SqliteOwnerLock, SqliteOwnerLockConflictError } from "./sqlite-owner-lock.ts";
|
|
90
93
|
import { canonicalizeJson } from "./integrity.ts";
|
|
94
|
+
import {
|
|
95
|
+
conversationTimelineItemId,
|
|
96
|
+
reconcileConversationTimeline,
|
|
97
|
+
type ConversationTimelineItem,
|
|
98
|
+
} from "./timeline-reconcile.ts";
|
|
99
|
+
import { SqliteSharedFiles } from "./sqlite-files.ts";
|
|
100
|
+
import type { SharedFilesPersistence } from "../media/files.ts";
|
|
101
|
+
import { SqliteMediaStore } from "./sqlite-media-store.ts";
|
|
102
|
+
import type { MediaStore } from "../media/store.ts";
|
|
91
103
|
|
|
92
104
|
type SqlValue = string | number | bigint | boolean | Uint8Array | null;
|
|
93
105
|
type WriteRunner = <T>(work: () => T) => Promise<T>;
|
|
@@ -140,6 +152,9 @@ export class SqliteAgentPersistence implements PersistenceBackend {
|
|
|
140
152
|
readonly identityRecord: AgentPersistenceIdentity;
|
|
141
153
|
readonly capabilities: PersistenceCapabilities;
|
|
142
154
|
|
|
155
|
+
readonly media: MediaStore;
|
|
156
|
+
readonly files: SharedFilesPersistence;
|
|
157
|
+
readonly outOfBandDelivery: OutOfBandDeliveryPersistence;
|
|
143
158
|
readonly conversations: ConversationPersistence;
|
|
144
159
|
readonly records: ConversationRecordPersistence;
|
|
145
160
|
readonly messages: ConversationMessagePersistence;
|
|
@@ -179,6 +194,9 @@ export class SqliteAgentPersistence implements PersistenceBackend {
|
|
|
179
194
|
metering: true,
|
|
180
195
|
});
|
|
181
196
|
const scope = this.createScope((work) => this.autoWrite(work), (records) => this.notifyRecordsCommitted(records));
|
|
197
|
+
this.media = scope.media!;
|
|
198
|
+
this.files = scope.files!;
|
|
199
|
+
this.outOfBandDelivery = scope.outOfBandDelivery!;
|
|
182
200
|
this.conversations = scope.conversations;
|
|
183
201
|
this.records = scope.records;
|
|
184
202
|
this.messages = scope.messages;
|
|
@@ -292,11 +310,32 @@ export class SqliteAgentPersistence implements PersistenceBackend {
|
|
|
292
310
|
}
|
|
293
311
|
}
|
|
294
312
|
|
|
313
|
+
/** How far out-of-band messages were delivered, per conversation and provider context. */
|
|
314
|
+
private createOutOfBandDelivery(runWrite: <T>(work: () => T) => Promise<T>): OutOfBandDeliveryPersistence {
|
|
315
|
+
return {
|
|
316
|
+
get: async (owner, providerContext) => Number(this.database.query<{ through_sequence: number }, [string, string]>(
|
|
317
|
+
"SELECT through_sequence FROM out_of_band_delivery WHERE owner = ? AND provider_context = ?",
|
|
318
|
+
).get(owner, providerContext)?.through_sequence ?? 0),
|
|
319
|
+
advance: async (owner, providerContext, throughSequence) => {
|
|
320
|
+
await runWrite(() => {
|
|
321
|
+
this.database.query(
|
|
322
|
+
`INSERT INTO out_of_band_delivery(owner, provider_context, through_sequence) VALUES (?, ?, ?)
|
|
323
|
+
ON CONFLICT(owner, provider_context)
|
|
324
|
+
DO UPDATE SET through_sequence = MAX(through_sequence, excluded.through_sequence)`,
|
|
325
|
+
).run(owner, providerContext, throughSequence);
|
|
326
|
+
});
|
|
327
|
+
},
|
|
328
|
+
};
|
|
329
|
+
}
|
|
330
|
+
|
|
295
331
|
private createScope(
|
|
296
332
|
runWrite: WriteRunner,
|
|
297
333
|
onAppended: (records: readonly ConversationRecord[]) => void | Promise<void>,
|
|
298
334
|
): PersistenceScope {
|
|
299
335
|
return Object.freeze({
|
|
336
|
+
media: new SqliteMediaStore(this.database, runWrite),
|
|
337
|
+
files: new SqliteSharedFiles(this.database),
|
|
338
|
+
outOfBandDelivery: this.createOutOfBandDelivery(runWrite),
|
|
300
339
|
conversations: new SqliteConversationPersistence(this.database, this.identityRecord.agentSessionId, runWrite),
|
|
301
340
|
records: new SqliteConversationRecordPersistence(
|
|
302
341
|
this.database,
|
|
@@ -638,6 +677,8 @@ class SqliteConversationRecordPersistence implements ConversationRecordPersisten
|
|
|
638
677
|
"SELECT COUNT(*) AS n FROM conversation_records WHERE agent_conversation_id = ?",
|
|
639
678
|
).get(agentConversationId)?.n ?? 0;
|
|
640
679
|
this.database.query("DELETE FROM conversation_records WHERE agent_conversation_id = ?").run(agentConversationId);
|
|
680
|
+
this.database.query("DELETE FROM conversation_media WHERE owner = ?").run(agentConversationId);
|
|
681
|
+
this.database.query("DELETE FROM out_of_band_delivery WHERE owner = ?").run(agentConversationId);
|
|
641
682
|
return Number(count);
|
|
642
683
|
});
|
|
643
684
|
}
|
|
@@ -673,6 +714,10 @@ class SqliteConversationRecordPersistence implements ConversationRecordPersisten
|
|
|
673
714
|
where.push(`kind IN (${options.kinds.map(() => "?").join(", ")})`);
|
|
674
715
|
parameters.push(...options.kinds);
|
|
675
716
|
}
|
|
717
|
+
if (options.operationId !== undefined) {
|
|
718
|
+
where.push("operation_id = ?");
|
|
719
|
+
parameters.push(nonblank(options.operationId, "operationId"));
|
|
720
|
+
}
|
|
676
721
|
parameters.push(limit + 1, offset);
|
|
677
722
|
const rows = this.database.query<ConversationRecordRow, SqlValue[]>(
|
|
678
723
|
`SELECT * FROM conversation_records
|
|
@@ -689,19 +734,66 @@ class SqliteConversationRecordPersistence implements ConversationRecordPersisten
|
|
|
689
734
|
|
|
690
735
|
async listRecent(
|
|
691
736
|
agentConversationId: AgentConversationId,
|
|
692
|
-
options:
|
|
693
|
-
): Promise<
|
|
737
|
+
options: RecentItemPageOptions,
|
|
738
|
+
): Promise<RecentItemPage>;
|
|
739
|
+
async listRecent(
|
|
740
|
+
agentConversationId: AgentConversationId,
|
|
741
|
+
options?: RecentRecordPageOptions,
|
|
742
|
+
): Promise<RecentRecordPage>;
|
|
743
|
+
async listRecent(
|
|
744
|
+
agentConversationId: AgentConversationId,
|
|
745
|
+
options: RecentRecordPageOptions | RecentItemPageOptions = {},
|
|
746
|
+
): Promise<RecentRecordPage | RecentItemPage> {
|
|
694
747
|
const conversation = requireConversation(this.database, agentConversationId);
|
|
695
|
-
const limit = boundedInteger(options.limit ?? 50, 1, 500, "recent record limit");
|
|
696
748
|
const kinds = [...new Set(options.kinds ?? [])].sort();
|
|
697
749
|
for (const kind of kinds) {
|
|
698
750
|
if (!isConversationRecordKind(kind)) throw new Error(`unknown record kind: ${kind}`);
|
|
699
751
|
}
|
|
752
|
+
const detail = options.detail ?? "full";
|
|
753
|
+
if (detail !== "full" && detail !== "summary") throw new Error(`unknown record detail: ${String(detail)}`);
|
|
754
|
+
const fold = options.fold === true;
|
|
755
|
+
const unit = options.agentMessages === undefined ? "records" : "agentMessages";
|
|
700
756
|
const cursor = options.olderCursor
|
|
701
|
-
? decodeRecentCursor(options.olderCursor, agentConversationId, kinds)
|
|
757
|
+
? decodeRecentCursor(options.olderCursor, agentConversationId, kinds, unit)
|
|
702
758
|
: null;
|
|
703
759
|
const snapshotSequence = cursor?.snapshotSequence ?? Number(conversation.latest_sequence);
|
|
704
760
|
const beforeSequence = cursor?.beforeSequence ?? snapshotSequence + 1;
|
|
761
|
+
const page = unit === "records"
|
|
762
|
+
? this.recentRecordRange(agentConversationId, kinds, snapshotSequence, beforeSequence,
|
|
763
|
+
boundedInteger(options.limit ?? 50, 1, 500, "recent record limit"))
|
|
764
|
+
: this.recentAgentMessagePage(agentConversationId, kinds, snapshotSequence, beforeSequence,
|
|
765
|
+
boundedInteger(options.agentMessages!, 1, 10_000, "agentMessages"),
|
|
766
|
+
boundedInteger(options.limit ?? 2_000, 1, 10_000, "recent page limit"), fold);
|
|
767
|
+
const records = detail === "summary" ? page.records.map(summarizeRecord) : page.records;
|
|
768
|
+
const rest = {
|
|
769
|
+
snapshotSequence,
|
|
770
|
+
...(page.olderBefore !== undefined
|
|
771
|
+
? { olderCursor: encodeRecentCursor({
|
|
772
|
+
conversationId: agentConversationId,
|
|
773
|
+
snapshotSequence,
|
|
774
|
+
beforeSequence: page.olderBefore,
|
|
775
|
+
kinds,
|
|
776
|
+
unit,
|
|
777
|
+
}) }
|
|
778
|
+
: {}),
|
|
779
|
+
...(page.truncated ? { truncated: true as const } : {}),
|
|
780
|
+
};
|
|
781
|
+
if (!fold) return Object.freeze({ records: Object.freeze(records), ...rest });
|
|
782
|
+
const items = reconcileConversationTimeline([], records);
|
|
783
|
+
return Object.freeze({
|
|
784
|
+
items: detail === "summary" ? Object.freeze(items.map(summarizeItem)) : items,
|
|
785
|
+
...rest,
|
|
786
|
+
});
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
/** The newest `limit` matching records below `beforeSequence`. */
|
|
790
|
+
private recentRecordRange(
|
|
791
|
+
agentConversationId: AgentConversationId,
|
|
792
|
+
kinds: readonly string[],
|
|
793
|
+
snapshotSequence: number,
|
|
794
|
+
beforeSequence: number,
|
|
795
|
+
limit: number,
|
|
796
|
+
): RecentPageSlice {
|
|
705
797
|
const where = ["agent_conversation_id = ?", "sequence <= ?", "sequence < ?"];
|
|
706
798
|
const parameters: SqlValue[] = [agentConversationId, snapshotSequence, beforeSequence];
|
|
707
799
|
if (kinds.length) {
|
|
@@ -715,18 +807,89 @@ class SqliteConversationRecordPersistence implements ConversationRecordPersisten
|
|
|
715
807
|
).all(...parameters);
|
|
716
808
|
const selected = rows.slice(0, limit);
|
|
717
809
|
const oldest = selected.at(-1);
|
|
718
|
-
return
|
|
810
|
+
return {
|
|
719
811
|
records: hydrateConversationRecords(this.database, selected.reverse()),
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
812
|
+
...(rows.length > limit && oldest ? { olderBefore: Number(oldest.sequence) } : {}),
|
|
813
|
+
};
|
|
814
|
+
}
|
|
815
|
+
|
|
816
|
+
/**
|
|
817
|
+
* The items that began after the agent message `count + 1` places below `beforeSequence`, with
|
|
818
|
+
* every revision they have up to the snapshot. An item's revisions all lie in its operation, so
|
|
819
|
+
* the records of the operations the range touches are enough to find where each item began.
|
|
820
|
+
*/
|
|
821
|
+
private recentAgentMessagePage(
|
|
822
|
+
agentConversationId: AgentConversationId,
|
|
823
|
+
kinds: readonly string[],
|
|
824
|
+
snapshotSequence: number,
|
|
825
|
+
beforeSequence: number,
|
|
826
|
+
count: number,
|
|
827
|
+
limit: number,
|
|
828
|
+
fold: boolean,
|
|
829
|
+
): RecentPageSlice {
|
|
830
|
+
const boundaries = this.database.query<{ first: number }, [string, number, number, number]>(`
|
|
831
|
+
SELECT MIN(r.sequence) AS first
|
|
832
|
+
FROM conversation_records r
|
|
833
|
+
JOIN conversation_messages m ON m.record_row_id = r.row_id
|
|
834
|
+
WHERE r.agent_conversation_id = ? AND r.kind = 'message' AND m.role = 'assistant' AND r.sequence <= ?
|
|
835
|
+
GROUP BY COALESCE(m.logical_message_id, r.record_id)
|
|
836
|
+
HAVING first < ?
|
|
837
|
+
ORDER BY first DESC
|
|
838
|
+
LIMIT ?
|
|
839
|
+
`).all(agentConversationId, snapshotSequence, beforeSequence, count + 1);
|
|
840
|
+
const lowest = boundaries.length > count ? Number(boundaries[count]!.first) : 0;
|
|
841
|
+
|
|
842
|
+
const inRange = this.database.query<ConversationRecordRow, [string, number, number, number]>(`
|
|
843
|
+
SELECT * FROM conversation_records
|
|
844
|
+
WHERE agent_conversation_id = ? AND sequence > ? AND sequence < ? AND sequence <= ?
|
|
845
|
+
ORDER BY sequence
|
|
846
|
+
`).all(agentConversationId, lowest, beforeSequence, snapshotSequence);
|
|
847
|
+
const operations = [...new Set(inRange.flatMap((row) => row.operation_id === null ? [] : [row.operation_id]))];
|
|
848
|
+
const outside: ConversationRecordRow[] = [];
|
|
849
|
+
for (let index = 0; index < operations.length; index += 500) {
|
|
850
|
+
const chunk = operations.slice(index, index + 500);
|
|
851
|
+
outside.push(...this.database.query<ConversationRecordRow, SqlValue[]>(`
|
|
852
|
+
SELECT * FROM conversation_records
|
|
853
|
+
WHERE agent_conversation_id = ? AND operation_id IN (${chunk.map(() => "?").join(", ")})
|
|
854
|
+
AND sequence <= ? AND (sequence <= ? OR sequence >= ?)
|
|
855
|
+
`).all(agentConversationId, ...chunk, snapshotSequence, lowest, beforeSequence));
|
|
856
|
+
}
|
|
857
|
+
const all = hydrateConversationRecords(this.database,
|
|
858
|
+
[...inRange, ...outside].sort((left, right) => Number(left.sequence) - Number(right.sequence)));
|
|
859
|
+
|
|
860
|
+
const firstOf = new Map<string, number>();
|
|
861
|
+
for (const record of all) {
|
|
862
|
+
const id = conversationTimelineItemId(record);
|
|
863
|
+
if (!firstOf.has(id)) firstOf.set(id, record.sequence);
|
|
864
|
+
}
|
|
865
|
+
const startOf = (record: ConversationRecord) => firstOf.get(conversationTimelineItemId(record))!;
|
|
866
|
+
const kept = all.filter((record) => {
|
|
867
|
+
const start = startOf(record);
|
|
868
|
+
return start > lowest && start < beforeSequence && (kinds.length === 0 || kinds.includes(record.kind));
|
|
729
869
|
});
|
|
870
|
+
|
|
871
|
+
// Over the limit: keep the newest whole items, and let the next page begin below them.
|
|
872
|
+
const starts = [...new Set(kept.map(startOf))].sort((left, right) => right - left);
|
|
873
|
+
const sizes = new Map<number, number>();
|
|
874
|
+
for (const record of kept) sizes.set(startOf(record), (sizes.get(startOf(record)) ?? 0) + 1);
|
|
875
|
+
let used = 0;
|
|
876
|
+
let oldestKept: number | undefined;
|
|
877
|
+
for (const start of starts) {
|
|
878
|
+
const size = fold ? 1 : sizes.get(start)!;
|
|
879
|
+
if (oldestKept !== undefined && used + size > limit) {
|
|
880
|
+
return {
|
|
881
|
+
records: kept.filter((record) => startOf(record) >= oldestKept!),
|
|
882
|
+
olderBefore: oldestKept,
|
|
883
|
+
truncated: true,
|
|
884
|
+
};
|
|
885
|
+
}
|
|
886
|
+
used += size;
|
|
887
|
+
oldestKept = start;
|
|
888
|
+
}
|
|
889
|
+
return {
|
|
890
|
+
records: kept,
|
|
891
|
+
...(lowest > 0 ? { olderBefore: lowest + 1 } : {}),
|
|
892
|
+
};
|
|
730
893
|
}
|
|
731
894
|
|
|
732
895
|
private appendDirect(input: NewConversationRecord): ConversationRecord {
|
|
@@ -2132,16 +2295,29 @@ interface RecentCursor {
|
|
|
2132
2295
|
readonly snapshotSequence: number;
|
|
2133
2296
|
readonly beforeSequence: number;
|
|
2134
2297
|
readonly kinds: readonly string[];
|
|
2298
|
+
/** What the page counts. A cursor of one unit is refused by the other: their pages split differently. */
|
|
2299
|
+
readonly unit: "records" | "agentMessages";
|
|
2300
|
+
}
|
|
2301
|
+
|
|
2302
|
+
/** One page of `listRecent` before detail and folding: `olderBefore` is the next page's `beforeSequence`. */
|
|
2303
|
+
interface RecentPageSlice {
|
|
2304
|
+
readonly records: readonly ConversationRecord[];
|
|
2305
|
+
readonly olderBefore?: number;
|
|
2306
|
+
readonly truncated?: true;
|
|
2135
2307
|
}
|
|
2136
2308
|
|
|
2137
2309
|
function encodeRecentCursor(cursor: RecentCursor): string {
|
|
2138
|
-
|
|
2310
|
+
const { unit, ...rest } = cursor;
|
|
2311
|
+
// Record cursors keep their earlier encoding.
|
|
2312
|
+
return Buffer.from(JSON.stringify({ v: 1, ...rest, ...(unit === "records" ? {} : { unit }) }), "utf8")
|
|
2313
|
+
.toString("base64url");
|
|
2139
2314
|
}
|
|
2140
2315
|
|
|
2141
2316
|
function decodeRecentCursor(
|
|
2142
2317
|
encoded: string,
|
|
2143
2318
|
conversationId: AgentConversationId,
|
|
2144
2319
|
kinds: readonly string[],
|
|
2320
|
+
unit: RecentCursor["unit"],
|
|
2145
2321
|
): RecentCursor {
|
|
2146
2322
|
try {
|
|
2147
2323
|
if (encoded.length > 4_096) throw new Error();
|
|
@@ -2150,18 +2326,33 @@ function decodeRecentCursor(
|
|
|
2150
2326
|
|| !Number.isSafeInteger(value.snapshotSequence) || Number(value.snapshotSequence) < 0
|
|
2151
2327
|
|| !Number.isSafeInteger(value.beforeSequence) || Number(value.beforeSequence) < 1
|
|
2152
2328
|
|| Number(value.beforeSequence) > Number(value.snapshotSequence) + 1
|
|
2153
|
-
|| JSON.stringify(value.kinds) !== JSON.stringify(kinds)
|
|
2329
|
+
|| JSON.stringify(value.kinds) !== JSON.stringify(kinds)
|
|
2330
|
+
|| (value.unit ?? "records") !== unit) throw new Error();
|
|
2154
2331
|
return {
|
|
2155
2332
|
conversationId,
|
|
2156
2333
|
snapshotSequence: Number(value.snapshotSequence),
|
|
2157
2334
|
beforeSequence: Number(value.beforeSequence),
|
|
2158
2335
|
kinds,
|
|
2336
|
+
unit,
|
|
2159
2337
|
};
|
|
2160
2338
|
} catch {
|
|
2161
2339
|
throw new Error("invalid or mismatched recent-record cursor");
|
|
2162
2340
|
}
|
|
2163
2341
|
}
|
|
2164
2342
|
|
|
2343
|
+
/** A tool call without its input and output, the bulk of a history page. */
|
|
2344
|
+
function summarizeRecord(record: ConversationRecord): ConversationRecord {
|
|
2345
|
+
if (record.kind !== "tool_call" || (record.input === undefined && record.output === undefined)) return record;
|
|
2346
|
+
const { input: _input, output: _output, ...rest } = record;
|
|
2347
|
+
return Object.freeze(rest);
|
|
2348
|
+
}
|
|
2349
|
+
|
|
2350
|
+
/** An item reduced to its first revision and its merged current, filed under the latest revision's id. */
|
|
2351
|
+
function summarizeItem(item: ConversationTimelineItem): ConversationTimelineItem {
|
|
2352
|
+
if (item.revisions.length <= 2) return item;
|
|
2353
|
+
return Object.freeze({ ...item, revisions: Object.freeze([item.revisions[0]!, item.current]) });
|
|
2354
|
+
}
|
|
2355
|
+
|
|
2165
2356
|
async function canonicalSqlitePath(input: string): Promise<string> {
|
|
2166
2357
|
const resolved = resolve(input);
|
|
2167
2358
|
const parent = dirname(resolved);
|
|
@@ -1,6 +1,9 @@
|
|
|
1
|
+
import { contentText } from "../media/content.ts";
|
|
1
2
|
import type { Database } from "bun:sqlite";
|
|
2
3
|
import type { AgentConversationId, AgentSessionId } from "../agent-ids.ts";
|
|
4
|
+
import type { CancelOutcome } from "../operations/contracts.ts";
|
|
3
5
|
import type {
|
|
6
|
+
CancellationRecord,
|
|
4
7
|
ConversationErrorDetails,
|
|
5
8
|
ConversationErrorRecoverability,
|
|
6
9
|
ConversationErrorSource,
|
|
@@ -26,8 +29,7 @@ export interface ConversationRecordRow {
|
|
|
26
29
|
type SqlValue = string | number | bigint | boolean | Uint8Array | null;
|
|
27
30
|
|
|
28
31
|
export function operationIdFromRecord(record: NewConversationRecord): string | null {
|
|
29
|
-
if (record.
|
|
30
|
-
if (record.kind === "error") return record.operationId ?? null;
|
|
32
|
+
if (record.operationId?.trim()) return record.operationId;
|
|
31
33
|
if (!record.metadata) return null;
|
|
32
34
|
try {
|
|
33
35
|
const metadata = JSON.parse(record.metadata) as { operationId?: unknown };
|
|
@@ -214,6 +216,18 @@ export function insertConversationRecordDetail(
|
|
|
214
216
|
encodeJson(record.details as PersistenceJsonValue | undefined),
|
|
215
217
|
);
|
|
216
218
|
return;
|
|
219
|
+
case "cancellation":
|
|
220
|
+
run(database,
|
|
221
|
+
`INSERT INTO conversation_cancellation_events(
|
|
222
|
+
record_row_id, cancellation_id, state, reason, outcome
|
|
223
|
+
) VALUES (?, ?, ?, ?, ?)`,
|
|
224
|
+
rowId,
|
|
225
|
+
record.cancellationId,
|
|
226
|
+
record.state,
|
|
227
|
+
record.reason,
|
|
228
|
+
record.outcome ?? null,
|
|
229
|
+
);
|
|
230
|
+
return;
|
|
217
231
|
}
|
|
218
232
|
}
|
|
219
233
|
|
|
@@ -246,7 +260,9 @@ export function sameConversationRecord(
|
|
|
246
260
|
candidate: NewConversationRecord,
|
|
247
261
|
): boolean {
|
|
248
262
|
const { sequence: _sequence, ...withoutSequence } = persisted;
|
|
249
|
-
|
|
263
|
+
// A record that names its operation only in `metadata` reads back with `operationId` filled in.
|
|
264
|
+
const operationId = operationIdFromRecord(candidate);
|
|
265
|
+
return stableJson(withoutSequence) === stableJson(operationId ? { ...candidate, operationId } : candidate);
|
|
250
266
|
}
|
|
251
267
|
|
|
252
268
|
const DETAIL_TABLES: Readonly<Record<ConversationRecordKind, string>> = Object.freeze({
|
|
@@ -261,6 +277,7 @@ const DETAIL_TABLES: Readonly<Record<ConversationRecordKind, string>> = Object.f
|
|
|
261
277
|
activity: "conversation_activity_events",
|
|
262
278
|
metering: "conversation_metering_references",
|
|
263
279
|
error: "conversation_error_records",
|
|
280
|
+
cancellation: "conversation_cancellation_events",
|
|
264
281
|
});
|
|
265
282
|
|
|
266
283
|
function recordFromRows(
|
|
@@ -274,6 +291,7 @@ function recordFromRows(
|
|
|
274
291
|
sequence: Number(row.sequence),
|
|
275
292
|
kind: row.kind,
|
|
276
293
|
timestamp: row.timestamp,
|
|
294
|
+
...(row.operation_id !== null ? { operationId: row.operation_id } : {}),
|
|
277
295
|
...(row.metadata !== null ? { metadata: row.metadata } : {}),
|
|
278
296
|
};
|
|
279
297
|
switch (row.kind as ConversationRecordKind) {
|
|
@@ -398,6 +416,15 @@ function recordFromRows(
|
|
|
398
416
|
? { details: decodeJson(detail.details_json) as ConversationErrorDetails }
|
|
399
417
|
: {}),
|
|
400
418
|
});
|
|
419
|
+
case "cancellation":
|
|
420
|
+
return Object.freeze({
|
|
421
|
+
...envelope,
|
|
422
|
+
kind: "cancellation",
|
|
423
|
+
cancellationId: string(detail.cancellation_id),
|
|
424
|
+
state: string(detail.state) as CancellationRecord["state"],
|
|
425
|
+
reason: string(detail.reason) as CancellationRecord["reason"],
|
|
426
|
+
...(detail.outcome !== null ? { outcome: string(detail.outcome) as CancelOutcome } : {}),
|
|
427
|
+
});
|
|
401
428
|
}
|
|
402
429
|
}
|
|
403
430
|
|
|
@@ -430,7 +457,7 @@ function decodeJson(value: unknown): PersistenceJsonValue {
|
|
|
430
457
|
}
|
|
431
458
|
|
|
432
459
|
function searchableContent(content: PersistedContent): string {
|
|
433
|
-
return
|
|
460
|
+
return contentText(content);
|
|
434
461
|
}
|
|
435
462
|
|
|
436
463
|
function searchableJson(value: PersistenceJsonValue | undefined): string {
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import type { Database } from "bun:sqlite";
|
|
2
|
+
import type { SharedFile, SharedFilePage, SharedFileQuery, SharedFilesPersistence } from "../media/files.ts";
|
|
3
|
+
import type { AgentConversationId } from "../agent-ids.ts";
|
|
4
|
+
import type { PersistedMediaBlock } from "./backend.ts";
|
|
5
|
+
|
|
6
|
+
interface SharedFileRow {
|
|
7
|
+
record_id: string;
|
|
8
|
+
owner: string;
|
|
9
|
+
sequence: number;
|
|
10
|
+
timestamp: string;
|
|
11
|
+
role: "assistant" | "user";
|
|
12
|
+
part_index: number;
|
|
13
|
+
block: string;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** A field of the media block being listed. */
|
|
17
|
+
const field = (name: string) => `json_extract(part.value, '$.${name}')`;
|
|
18
|
+
|
|
19
|
+
/** The text a files search matches: name, kind, MIME type and size. */
|
|
20
|
+
const SEARCHED_TEXT = [field("name"), field("kind"), field("mimeType"), field("size")]
|
|
21
|
+
.map((value) => `COALESCE(${value}, '')`)
|
|
22
|
+
.join(" || ' ' || ");
|
|
23
|
+
|
|
24
|
+
/** `LIKE` operand matching the value literally anywhere in the text. */
|
|
25
|
+
function containing(value: string): string {
|
|
26
|
+
return `%${value.replace(/[\\%_]/g, "\\$&")}%`;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* The media parts of recorded messages, from their metadata: bytes are never read. Only the latest
|
|
31
|
+
* revision of an assistant message counts, so a streamed message lists its parts once. Files whose
|
|
32
|
+
* bytes were deleted or never kept are still listed: the history still shows them.
|
|
33
|
+
*/
|
|
34
|
+
export class SqliteSharedFiles implements SharedFilesPersistence {
|
|
35
|
+
constructor(private readonly database: Database) {}
|
|
36
|
+
|
|
37
|
+
async list(query: SharedFileQuery = {}): Promise<SharedFilePage> {
|
|
38
|
+
const limit = query.limit ?? 100;
|
|
39
|
+
const offset = query.cursor === undefined ? 0 : Number(query.cursor);
|
|
40
|
+
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 1000) throw new Error("file limit must be between 1 and 1000");
|
|
41
|
+
if (query.cursor !== undefined && (!/^\d+$/.test(query.cursor) || !Number.isSafeInteger(offset))) {
|
|
42
|
+
throw new Error("invalid file cursor");
|
|
43
|
+
}
|
|
44
|
+
for (const size of [query.minSize, query.maxSize]) {
|
|
45
|
+
if (size !== undefined && (!Number.isSafeInteger(size) || size < 0)) {
|
|
46
|
+
throw new Error("file size filter must be a non-negative integer");
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
const where = [`${field("type")} = 'media'`];
|
|
50
|
+
const values: (string | number)[] = [];
|
|
51
|
+
const add = (clause: string, value: string | number | undefined) => {
|
|
52
|
+
if (value === undefined) return;
|
|
53
|
+
where.push(clause);
|
|
54
|
+
values.push(value);
|
|
55
|
+
};
|
|
56
|
+
add("record.agent_conversation_id = ?", query.agentConversationId);
|
|
57
|
+
add(`${field("kind")} = ?`, query.kind);
|
|
58
|
+
add(`${field("mimeType")} = ?`, query.mimeType);
|
|
59
|
+
add(`${field("size")} >= ?`, query.minSize);
|
|
60
|
+
add(`${field("size")} <= ?`, query.maxSize);
|
|
61
|
+
add(`${field("name")} LIKE ? ESCAPE '\\'`, query.name === undefined ? undefined : containing(query.name));
|
|
62
|
+
add(`(${SEARCHED_TEXT}) LIKE ? ESCAPE '\\'`, query.text === undefined ? undefined : containing(query.text));
|
|
63
|
+
const rows = this.database.query<SharedFileRow, (string | number)[]>(`
|
|
64
|
+
SELECT record.record_id, record.agent_conversation_id AS owner, record.sequence, record.timestamp,
|
|
65
|
+
message.role, CAST(part.key AS INTEGER) AS part_index, part.value AS block
|
|
66
|
+
FROM conversation_records record
|
|
67
|
+
JOIN conversation_messages message ON message.record_row_id = record.row_id,
|
|
68
|
+
json_each(message.content_json) part
|
|
69
|
+
WHERE ${where.join(" AND ")}
|
|
70
|
+
AND (message.logical_message_id IS NULL OR NOT EXISTS (
|
|
71
|
+
SELECT 1 FROM conversation_records newer
|
|
72
|
+
JOIN conversation_messages revision ON revision.record_row_id = newer.row_id
|
|
73
|
+
WHERE newer.agent_conversation_id = record.agent_conversation_id
|
|
74
|
+
AND revision.logical_message_id = message.logical_message_id
|
|
75
|
+
AND newer.sequence > record.sequence
|
|
76
|
+
))
|
|
77
|
+
ORDER BY record.timestamp DESC, record.record_id DESC, part_index ASC
|
|
78
|
+
LIMIT ? OFFSET ?
|
|
79
|
+
`).all(...values, limit + 1, offset);
|
|
80
|
+
const files: SharedFile[] = rows.slice(0, limit).map((row) => ({
|
|
81
|
+
...JSON.parse(row.block) as PersistedMediaBlock,
|
|
82
|
+
agentConversationId: row.owner as AgentConversationId,
|
|
83
|
+
recordId: row.record_id,
|
|
84
|
+
sequence: row.sequence,
|
|
85
|
+
timestamp: row.timestamp,
|
|
86
|
+
role: row.role,
|
|
87
|
+
partIndex: row.part_index,
|
|
88
|
+
}));
|
|
89
|
+
return { files, ...(rows.length > limit ? { nextCursor: String(offset + limit) } : {}) };
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
async search(query: SharedFileQuery & { readonly text: string }): Promise<SharedFilePage> {
|
|
93
|
+
return this.list(query);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import type { Database } from "bun:sqlite";
|
|
2
|
+
import type { MediaInfo, MediaStore, StoredMedia } from "../media/store.ts";
|
|
3
|
+
|
|
4
|
+
interface MediaRow {
|
|
5
|
+
ref: string;
|
|
6
|
+
owner: string;
|
|
7
|
+
kind: MediaInfo["kind"];
|
|
8
|
+
mime_type: string;
|
|
9
|
+
name: string | null;
|
|
10
|
+
size: number;
|
|
11
|
+
sha256: string;
|
|
12
|
+
data?: Uint8Array;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function storedMedia(row: MediaRow): StoredMedia {
|
|
16
|
+
return {
|
|
17
|
+
ref: row.ref,
|
|
18
|
+
info: {
|
|
19
|
+
owner: row.owner,
|
|
20
|
+
kind: row.kind,
|
|
21
|
+
mimeType: row.mime_type,
|
|
22
|
+
...(row.name === null ? {} : { name: row.name }),
|
|
23
|
+
size: row.size,
|
|
24
|
+
sha256: row.sha256,
|
|
25
|
+
},
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Kept copies in the agent's own database, out of the message rows. The scoped writer joins the
|
|
31
|
+
* enclosing record transaction when one is active, so a copy and its record commit together.
|
|
32
|
+
*/
|
|
33
|
+
export class SqliteMediaStore implements MediaStore {
|
|
34
|
+
constructor(
|
|
35
|
+
private readonly database: Database,
|
|
36
|
+
private readonly write: <T>(work: () => T) => Promise<T>,
|
|
37
|
+
) {}
|
|
38
|
+
|
|
39
|
+
async put(bytes: Uint8Array, info: MediaInfo): Promise<string> {
|
|
40
|
+
return this.write(() => {
|
|
41
|
+
const ref = `media-${crypto.randomUUID()}`;
|
|
42
|
+
this.database.query(
|
|
43
|
+
`INSERT INTO conversation_media(ref, owner, kind, mime_type, name, size, sha256, data)
|
|
44
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
45
|
+
).run(ref, info.owner, info.kind, info.mimeType, info.name ?? null, info.size, info.sha256, bytes);
|
|
46
|
+
return ref;
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
async get(ref: string): Promise<(StoredMedia & { data: Uint8Array }) | null> {
|
|
51
|
+
const row = this.database.query<MediaRow, [string]>("SELECT * FROM conversation_media WHERE ref = ?").get(ref);
|
|
52
|
+
return row ? { ...storedMedia(row), data: new Uint8Array(row.data!) } : null;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
async delete(ref: string): Promise<void> {
|
|
56
|
+
await this.write(() => {
|
|
57
|
+
this.database.query("DELETE FROM conversation_media WHERE ref = ?").run(ref);
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
async list(owner: string): Promise<readonly StoredMedia[]> {
|
|
62
|
+
return this.database.query<MediaRow, [string]>(
|
|
63
|
+
`SELECT ref, owner, kind, mime_type, name, size, sha256
|
|
64
|
+
FROM conversation_media WHERE owner = ? ORDER BY rowid`,
|
|
65
|
+
).all(owner).map(storedMedia);
|
|
66
|
+
}
|
|
67
|
+
}
|