@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.
- package/CHANGELOG-audit.md +58 -0
- package/CONSUMER_GUIDE.md +571 -19
- package/package.json +6 -1
- package/src/agent-adapter-registry.ts +66 -0
- package/src/agent-conversation-continuation.ts +121 -0
- package/src/agent-conversation-contracts.ts +279 -0
- package/src/agent-conversation-errors.ts +31 -0
- package/src/agent-conversation-owner.ts +60 -0
- package/src/agent-conversation-presentation.ts +217 -0
- package/src/agent-conversation-queue.ts +44 -0
- package/src/agent-conversation.ts +41 -0
- package/src/agent-ids.ts +50 -0
- package/src/agent-session.ts +1032 -674
- package/src/agent.ts +1223 -0
- package/src/audit/config.ts +186 -0
- package/src/audit/contracts.ts +59 -0
- package/src/audit/index.ts +50 -0
- package/src/audit/projection.ts +127 -0
- package/src/audit/reader.ts +371 -0
- package/src/audit/runtime.ts +1060 -0
- package/src/checkpointing/config.ts +91 -0
- package/src/checkpointing/contracts.ts +45 -0
- package/src/checkpointing/coordinator.ts +100 -0
- package/src/checkpointing/ids.ts +5 -0
- package/src/checkpointing/index.ts +6 -0
- package/src/checkpointing/persistence/sqlite-repository.ts +159 -0
- package/src/checkpointing/recovery.ts +114 -0
- package/src/checkpointing/strategy.ts +139 -0
- package/src/identity/checkpoint-backed.ts +248 -0
- package/src/identity.ts +76 -0
- package/src/index.ts +132 -0
- package/src/internal-inference/config.ts +68 -0
- package/src/internal-inference/contracts.ts +218 -0
- package/src/internal-inference/coordination/handles.ts +133 -0
- package/src/internal-inference/coordination/manager.ts +487 -0
- package/src/internal-inference/ids.ts +10 -0
- package/src/internal-inference/index.ts +10 -0
- package/src/internal-inference/persistence/records.ts +132 -0
- package/src/internal-inference/persistence/repository.ts +35 -0
- package/src/internal-inference/persistence/sqlite-repository.ts +551 -0
- package/src/internal-inference/runtime/harness-runtime.ts +78 -0
- package/src/internal-inference/strategy/registry.ts +42 -0
- package/src/metering/engine.ts +47 -0
- package/src/metering/record.ts +4 -1
- package/src/observation/contracts.ts +10 -0
- package/src/observation/index.ts +8 -0
- package/src/observation/subscription-hub.ts +43 -0
- package/src/persistence/activity-projection.ts +26 -12
- package/src/persistence/backend.ts +839 -0
- package/src/persistence/index.ts +113 -0
- package/src/persistence/sqlite-backend.ts +2192 -0
- package/src/persistence/sqlite-conversation-records.ts +430 -0
- package/src/persistence/sqlite-owner-lock.ts +106 -0
- package/src/persistence/sqlite-schema.ts +589 -0
- package/src/persistence/timeline-reconcile.ts +72 -0
|
@@ -0,0 +1,430 @@
|
|
|
1
|
+
import type { Database } from "bun:sqlite";
|
|
2
|
+
import type { AgentConversationId, AgentSessionId } from "../agent-ids.ts";
|
|
3
|
+
import type {
|
|
4
|
+
ConversationRecord,
|
|
5
|
+
ConversationRecordKind,
|
|
6
|
+
NewConversationRecord,
|
|
7
|
+
PersistedContent,
|
|
8
|
+
PersistenceJsonValue,
|
|
9
|
+
} from "./backend.ts";
|
|
10
|
+
|
|
11
|
+
export interface ConversationRecordRow {
|
|
12
|
+
readonly row_id: number;
|
|
13
|
+
readonly record_id: string;
|
|
14
|
+
readonly agent_session_id: string;
|
|
15
|
+
readonly agent_conversation_id: string;
|
|
16
|
+
readonly sequence: number;
|
|
17
|
+
readonly kind: string;
|
|
18
|
+
readonly timestamp: string;
|
|
19
|
+
readonly operation_id: string | null;
|
|
20
|
+
readonly metadata: string | null;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
type SqlValue = string | number | bigint | boolean | Uint8Array | null;
|
|
24
|
+
|
|
25
|
+
export function operationIdFromRecord(record: NewConversationRecord): string | null {
|
|
26
|
+
if (record.kind === "metering") return record.operationId;
|
|
27
|
+
if (!record.metadata) return null;
|
|
28
|
+
try {
|
|
29
|
+
const metadata = JSON.parse(record.metadata) as { operationId?: unknown };
|
|
30
|
+
return typeof metadata?.operationId === "string" && metadata.operationId.trim()
|
|
31
|
+
? metadata.operationId
|
|
32
|
+
: null;
|
|
33
|
+
} catch {
|
|
34
|
+
return null;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function insertConversationRecordDetail(
|
|
39
|
+
database: Database,
|
|
40
|
+
rowId: number,
|
|
41
|
+
record: NewConversationRecord,
|
|
42
|
+
): void {
|
|
43
|
+
switch (record.kind) {
|
|
44
|
+
case "message": {
|
|
45
|
+
const content = encodeContent(record.content);
|
|
46
|
+
run(database,
|
|
47
|
+
`INSERT INTO conversation_messages(
|
|
48
|
+
record_row_id, role, participant_id, content_text, content_json, status, search_text,
|
|
49
|
+
consumer_metadata_json
|
|
50
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
51
|
+
rowId,
|
|
52
|
+
record.role,
|
|
53
|
+
record.participantId ?? null,
|
|
54
|
+
content.text,
|
|
55
|
+
content.json,
|
|
56
|
+
record.status ?? null,
|
|
57
|
+
searchableContent(record.content),
|
|
58
|
+
encodeJson(record.consumerMetadata),
|
|
59
|
+
);
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
case "tool_call": {
|
|
63
|
+
const output = encodeOptionalContent(record.output);
|
|
64
|
+
run(database,
|
|
65
|
+
`INSERT INTO conversation_tool_call_events(
|
|
66
|
+
record_row_id, tool_call_id, state, name, input_json,
|
|
67
|
+
output_text, output_json, error, search_text
|
|
68
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
69
|
+
rowId,
|
|
70
|
+
record.toolCallId,
|
|
71
|
+
record.state,
|
|
72
|
+
record.name ?? null,
|
|
73
|
+
encodeJson(record.input),
|
|
74
|
+
output.text,
|
|
75
|
+
output.json,
|
|
76
|
+
record.error ?? null,
|
|
77
|
+
joinSearchText([
|
|
78
|
+
record.name,
|
|
79
|
+
searchableJson(record.input),
|
|
80
|
+
record.output === undefined ? undefined : searchableContent(record.output),
|
|
81
|
+
record.error,
|
|
82
|
+
]),
|
|
83
|
+
);
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
case "permission":
|
|
87
|
+
run(database,
|
|
88
|
+
`INSERT INTO conversation_permission_events(
|
|
89
|
+
record_row_id, permission_id, state, request_json, outcome
|
|
90
|
+
) VALUES (?, ?, ?, ?, ?)`,
|
|
91
|
+
rowId,
|
|
92
|
+
record.permissionId,
|
|
93
|
+
record.state,
|
|
94
|
+
encodeJson(record.request),
|
|
95
|
+
record.outcome ?? null,
|
|
96
|
+
);
|
|
97
|
+
return;
|
|
98
|
+
case "configuration":
|
|
99
|
+
run(database,
|
|
100
|
+
`INSERT INTO conversation_configuration_events(
|
|
101
|
+
record_row_id, operation, config_id, value_json, status, error
|
|
102
|
+
) VALUES (?, ?, ?, ?, ?, ?)`,
|
|
103
|
+
rowId,
|
|
104
|
+
record.operation,
|
|
105
|
+
record.configId ?? null,
|
|
106
|
+
encodeJson(record.value),
|
|
107
|
+
record.status,
|
|
108
|
+
record.error ?? null,
|
|
109
|
+
);
|
|
110
|
+
return;
|
|
111
|
+
case "protocol":
|
|
112
|
+
run(database,
|
|
113
|
+
`INSERT INTO conversation_protocol_records(
|
|
114
|
+
record_row_id, direction, method, message_json
|
|
115
|
+
) VALUES (?, ?, ?, ?)`,
|
|
116
|
+
rowId,
|
|
117
|
+
record.direction,
|
|
118
|
+
record.method ?? null,
|
|
119
|
+
encodeJson(record.message),
|
|
120
|
+
);
|
|
121
|
+
return;
|
|
122
|
+
case "native_action":
|
|
123
|
+
run(database,
|
|
124
|
+
`INSERT INTO conversation_native_action_events(
|
|
125
|
+
record_row_id, action, transition_id, state, input_json, output_json, error
|
|
126
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?)`,
|
|
127
|
+
rowId,
|
|
128
|
+
record.action,
|
|
129
|
+
record.transitionId ?? null,
|
|
130
|
+
record.state,
|
|
131
|
+
encodeJson(record.input),
|
|
132
|
+
encodeJson(record.output),
|
|
133
|
+
record.error ?? null,
|
|
134
|
+
);
|
|
135
|
+
return;
|
|
136
|
+
case "agent_action":
|
|
137
|
+
run(database,
|
|
138
|
+
`INSERT INTO conversation_agent_action_events(
|
|
139
|
+
record_row_id, action, state, input_json, output_json, error
|
|
140
|
+
) VALUES (?, ?, ?, ?, ?, ?)`,
|
|
141
|
+
rowId,
|
|
142
|
+
record.action,
|
|
143
|
+
record.state,
|
|
144
|
+
encodeJson(record.input),
|
|
145
|
+
encodeJson(record.output),
|
|
146
|
+
record.error ?? null,
|
|
147
|
+
);
|
|
148
|
+
return;
|
|
149
|
+
case "thinking": {
|
|
150
|
+
const content = encodeContent(record.content);
|
|
151
|
+
run(database,
|
|
152
|
+
`INSERT INTO conversation_thinking_events(
|
|
153
|
+
record_row_id, thinking_id, state, content_text, content_json
|
|
154
|
+
) VALUES (?, ?, ?, ?, ?)`,
|
|
155
|
+
rowId,
|
|
156
|
+
record.thinkingId,
|
|
157
|
+
record.state,
|
|
158
|
+
content.text,
|
|
159
|
+
content.json,
|
|
160
|
+
);
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
case "activity": {
|
|
164
|
+
const content = encodeOptionalContent(record.content);
|
|
165
|
+
run(database,
|
|
166
|
+
`INSERT INTO conversation_activity_events(
|
|
167
|
+
record_row_id, activity_id, activity_type, state,
|
|
168
|
+
content_text, content_json, data_json, search_text
|
|
169
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
170
|
+
rowId,
|
|
171
|
+
record.activityId,
|
|
172
|
+
record.activityType,
|
|
173
|
+
record.state,
|
|
174
|
+
content.text,
|
|
175
|
+
content.json,
|
|
176
|
+
encodeJson(record.data),
|
|
177
|
+
joinSearchText([
|
|
178
|
+
record.activityType,
|
|
179
|
+
record.content === undefined ? undefined : searchableContent(record.content),
|
|
180
|
+
searchableJson(record.data),
|
|
181
|
+
]),
|
|
182
|
+
);
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
case "metering":
|
|
186
|
+
run(database,
|
|
187
|
+
`INSERT INTO conversation_metering_references(
|
|
188
|
+
record_row_id, operation_id, metering_record_id, status
|
|
189
|
+
) VALUES (?, ?, ?, ?)`,
|
|
190
|
+
rowId,
|
|
191
|
+
record.operationId,
|
|
192
|
+
record.meteringRecordId,
|
|
193
|
+
record.status,
|
|
194
|
+
);
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
export function hydrateConversationRecords(
|
|
200
|
+
database: Database,
|
|
201
|
+
rows: readonly ConversationRecordRow[],
|
|
202
|
+
): readonly ConversationRecord[] {
|
|
203
|
+
if (rows.length === 0) return Object.freeze([]);
|
|
204
|
+
const details = new Map<number, Record<string, unknown>>();
|
|
205
|
+
for (const kind of uniqueKinds(rows)) {
|
|
206
|
+
const ids = rows.filter((row) => row.kind === kind).map((row) => Number(row.row_id));
|
|
207
|
+
const table = DETAIL_TABLES[kind];
|
|
208
|
+
if (!table) throw new Error(`persisted conversation record has unknown kind: ${kind}`);
|
|
209
|
+
const found = database.query<Record<string, unknown>, number[]>(
|
|
210
|
+
`SELECT * FROM ${table} WHERE record_row_id IN (${ids.map(() => "?").join(", ")})`,
|
|
211
|
+
).all(...ids);
|
|
212
|
+
for (const detail of found) details.set(Number(detail.record_row_id), detail);
|
|
213
|
+
}
|
|
214
|
+
return Object.freeze(rows.map((row) => {
|
|
215
|
+
const detail = details.get(Number(row.row_id));
|
|
216
|
+
if (!detail) {
|
|
217
|
+
throw new Error(`conversation record ${row.record_id} has no ${row.kind} detail row`);
|
|
218
|
+
}
|
|
219
|
+
return recordFromRows(row, detail);
|
|
220
|
+
}));
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
export function sameConversationRecord(
|
|
224
|
+
persisted: ConversationRecord,
|
|
225
|
+
candidate: NewConversationRecord,
|
|
226
|
+
): boolean {
|
|
227
|
+
const { sequence: _sequence, ...withoutSequence } = persisted;
|
|
228
|
+
return stableJson(withoutSequence) === stableJson(candidate);
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
const DETAIL_TABLES: Readonly<Record<ConversationRecordKind, string>> = Object.freeze({
|
|
232
|
+
message: "conversation_messages",
|
|
233
|
+
tool_call: "conversation_tool_call_events",
|
|
234
|
+
permission: "conversation_permission_events",
|
|
235
|
+
configuration: "conversation_configuration_events",
|
|
236
|
+
protocol: "conversation_protocol_records",
|
|
237
|
+
native_action: "conversation_native_action_events",
|
|
238
|
+
agent_action: "conversation_agent_action_events",
|
|
239
|
+
thinking: "conversation_thinking_events",
|
|
240
|
+
activity: "conversation_activity_events",
|
|
241
|
+
metering: "conversation_metering_references",
|
|
242
|
+
});
|
|
243
|
+
|
|
244
|
+
function recordFromRows(
|
|
245
|
+
row: ConversationRecordRow,
|
|
246
|
+
detail: Record<string, unknown>,
|
|
247
|
+
): ConversationRecord {
|
|
248
|
+
const envelope = {
|
|
249
|
+
recordId: row.record_id,
|
|
250
|
+
agentSessionId: row.agent_session_id as AgentSessionId,
|
|
251
|
+
agentConversationId: row.agent_conversation_id as AgentConversationId,
|
|
252
|
+
sequence: Number(row.sequence),
|
|
253
|
+
kind: row.kind,
|
|
254
|
+
timestamp: row.timestamp,
|
|
255
|
+
...(row.metadata !== null ? { metadata: row.metadata } : {}),
|
|
256
|
+
};
|
|
257
|
+
switch (row.kind as ConversationRecordKind) {
|
|
258
|
+
case "message":
|
|
259
|
+
return Object.freeze({
|
|
260
|
+
...envelope,
|
|
261
|
+
kind: "message",
|
|
262
|
+
role: string(detail.role) as "assistant" | "user",
|
|
263
|
+
...(detail.participant_id !== null ? { participantId: string(detail.participant_id) } : {}),
|
|
264
|
+
...(detail.consumer_metadata_json !== null
|
|
265
|
+
? { consumerMetadata: decodeJson(detail.consumer_metadata_json) }
|
|
266
|
+
: {}),
|
|
267
|
+
content: decodeContent(detail.content_text, detail.content_json),
|
|
268
|
+
...(detail.status !== null ? { status: string(detail.status) as "in_progress" | "completed" | "cancelled" | "failed" } : {}),
|
|
269
|
+
});
|
|
270
|
+
case "tool_call":
|
|
271
|
+
return Object.freeze({
|
|
272
|
+
...envelope,
|
|
273
|
+
kind: "tool_call",
|
|
274
|
+
toolCallId: string(detail.tool_call_id),
|
|
275
|
+
state: string(detail.state) as "announced" | "input" | "completed" | "failed",
|
|
276
|
+
...(detail.name !== null ? { name: string(detail.name) } : {}),
|
|
277
|
+
...(detail.input_json !== null ? { input: decodeJson(detail.input_json) } : {}),
|
|
278
|
+
...(hasContent(detail.output_text, detail.output_json)
|
|
279
|
+
? { output: decodeContent(detail.output_text, detail.output_json) }
|
|
280
|
+
: {}),
|
|
281
|
+
...(detail.error !== null ? { error: string(detail.error) } : {}),
|
|
282
|
+
});
|
|
283
|
+
case "permission":
|
|
284
|
+
return Object.freeze({
|
|
285
|
+
...envelope,
|
|
286
|
+
kind: "permission",
|
|
287
|
+
permissionId: string(detail.permission_id),
|
|
288
|
+
state: string(detail.state) as "requested" | "resolved",
|
|
289
|
+
...(detail.request_json !== null ? { request: decodeJson(detail.request_json) } : {}),
|
|
290
|
+
...(detail.outcome !== null ? { outcome: string(detail.outcome) as "approved" | "denied" | "cancelled" } : {}),
|
|
291
|
+
});
|
|
292
|
+
case "configuration":
|
|
293
|
+
return Object.freeze({
|
|
294
|
+
...envelope,
|
|
295
|
+
kind: "configuration",
|
|
296
|
+
operation: string(detail.operation) as "set" | "restore" | "accept_effective" | "replace",
|
|
297
|
+
...(detail.config_id !== null ? { configId: string(detail.config_id) } : {}),
|
|
298
|
+
...(detail.value_json !== null ? { value: decodeJson(detail.value_json) } : {}),
|
|
299
|
+
status: string(detail.status) as "started" | "completed" | "failed",
|
|
300
|
+
...(detail.error !== null ? { error: string(detail.error) } : {}),
|
|
301
|
+
});
|
|
302
|
+
case "protocol":
|
|
303
|
+
return Object.freeze({
|
|
304
|
+
...envelope,
|
|
305
|
+
kind: "protocol",
|
|
306
|
+
direction: string(detail.direction) as "in" | "out" | "error",
|
|
307
|
+
...(detail.method !== null ? { method: string(detail.method) } : {}),
|
|
308
|
+
...(detail.message_json !== null ? { message: decodeJson(detail.message_json) } : {}),
|
|
309
|
+
});
|
|
310
|
+
case "native_action":
|
|
311
|
+
return Object.freeze({
|
|
312
|
+
...envelope,
|
|
313
|
+
kind: "native_action",
|
|
314
|
+
action: string(detail.action),
|
|
315
|
+
...(detail.transition_id !== null ? { transitionId: string(detail.transition_id) } : {}),
|
|
316
|
+
state: string(detail.state) as "started" | "checkpoint" | "completed" | "failed",
|
|
317
|
+
...(detail.input_json !== null ? { input: decodeJson(detail.input_json) } : {}),
|
|
318
|
+
...(detail.output_json !== null ? { output: decodeJson(detail.output_json) } : {}),
|
|
319
|
+
...(detail.error !== null ? { error: string(detail.error) } : {}),
|
|
320
|
+
});
|
|
321
|
+
case "agent_action":
|
|
322
|
+
return Object.freeze({
|
|
323
|
+
...envelope,
|
|
324
|
+
kind: "agent_action",
|
|
325
|
+
action: string(detail.action),
|
|
326
|
+
state: string(detail.state) as "requested" | "completed" | "failed",
|
|
327
|
+
...(detail.input_json !== null ? { input: decodeJson(detail.input_json) } : {}),
|
|
328
|
+
...(detail.output_json !== null ? { output: decodeJson(detail.output_json) } : {}),
|
|
329
|
+
...(detail.error !== null ? { error: string(detail.error) } : {}),
|
|
330
|
+
});
|
|
331
|
+
case "thinking":
|
|
332
|
+
return Object.freeze({
|
|
333
|
+
...envelope,
|
|
334
|
+
kind: "thinking",
|
|
335
|
+
thinkingId: string(detail.thinking_id),
|
|
336
|
+
state: string(detail.state) as "in_progress" | "completed" | "failed",
|
|
337
|
+
content: decodeContent(detail.content_text, detail.content_json),
|
|
338
|
+
});
|
|
339
|
+
case "activity":
|
|
340
|
+
return Object.freeze({
|
|
341
|
+
...envelope,
|
|
342
|
+
kind: "activity",
|
|
343
|
+
activityId: string(detail.activity_id),
|
|
344
|
+
activityType: string(detail.activity_type),
|
|
345
|
+
state: string(detail.state) as "in_progress" | "completed" | "failed",
|
|
346
|
+
...(hasContent(detail.content_text, detail.content_json)
|
|
347
|
+
? { content: decodeContent(detail.content_text, detail.content_json) }
|
|
348
|
+
: {}),
|
|
349
|
+
...(detail.data_json !== null ? { data: decodeJson(detail.data_json) } : {}),
|
|
350
|
+
});
|
|
351
|
+
case "metering":
|
|
352
|
+
return Object.freeze({
|
|
353
|
+
...envelope,
|
|
354
|
+
kind: "metering",
|
|
355
|
+
operationId: string(detail.operation_id),
|
|
356
|
+
meteringRecordId: string(detail.metering_record_id),
|
|
357
|
+
status: string(detail.status) as "available" | "partial" | "unavailable",
|
|
358
|
+
});
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
function encodeContent(content: PersistedContent): { text: string | null; json: string | null } {
|
|
363
|
+
return typeof content === "string"
|
|
364
|
+
? { text: content, json: null }
|
|
365
|
+
: { text: null, json: JSON.stringify(content) };
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
function encodeOptionalContent(content: PersistedContent | undefined) {
|
|
369
|
+
return content === undefined ? { text: null, json: null } : encodeContent(content);
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
function decodeContent(text: unknown, json: unknown): PersistedContent {
|
|
373
|
+
if (text !== null) return string(text);
|
|
374
|
+
if (json !== null) return decodeJson(json) as PersistedContent;
|
|
375
|
+
throw new Error("persisted content has neither text nor structured data");
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
function hasContent(text: unknown, json: unknown): boolean {
|
|
379
|
+
return text !== null || json !== null;
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
function encodeJson(value: PersistenceJsonValue | undefined): string | null {
|
|
383
|
+
return value === undefined ? null : JSON.stringify(value);
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
function decodeJson(value: unknown): PersistenceJsonValue {
|
|
387
|
+
return JSON.parse(string(value)) as PersistenceJsonValue;
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
function searchableContent(content: PersistedContent): string {
|
|
391
|
+
return typeof content === "string" ? content : searchableJson(content);
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
function searchableJson(value: PersistenceJsonValue | undefined): string {
|
|
395
|
+
if (value === undefined || value === null) return "";
|
|
396
|
+
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
|
|
397
|
+
return String(value);
|
|
398
|
+
}
|
|
399
|
+
if (Array.isArray(value)) return joinSearchText(value.map((item) => searchableJson(item)));
|
|
400
|
+
return joinSearchText(Object.values(value).map((item) => searchableJson(item)));
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
function joinSearchText(values: readonly (string | undefined)[]): string {
|
|
404
|
+
return values.filter((value): value is string => Boolean(value?.trim())).join("\n");
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
function uniqueKinds(rows: readonly ConversationRecordRow[]): ConversationRecordKind[] {
|
|
408
|
+
return [...new Set(rows.map((row) => row.kind as ConversationRecordKind))];
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
function stableJson(value: unknown): string {
|
|
412
|
+
if (Array.isArray(value)) return `[${value.map(stableJson).join(",")}]`;
|
|
413
|
+
if (value && typeof value === "object") {
|
|
414
|
+
return `{${Object.entries(value as Record<string, unknown>)
|
|
415
|
+
.filter(([, child]) => child !== undefined)
|
|
416
|
+
.sort(([left], [right]) => left.localeCompare(right))
|
|
417
|
+
.map(([key, child]) => `${JSON.stringify(key)}:${stableJson(child)}`)
|
|
418
|
+
.join(",")}}`;
|
|
419
|
+
}
|
|
420
|
+
return JSON.stringify(value);
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
function string(value: unknown): string {
|
|
424
|
+
if (typeof value !== "string") throw new Error("persisted conversation detail is malformed");
|
|
425
|
+
return value;
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
function run(database: Database, sql: string, ...values: SqlValue[]): void {
|
|
429
|
+
database.query(sql).run(...values);
|
|
430
|
+
}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { Database } from "bun:sqlite";
|
|
2
|
+
import { chmod } from "node:fs/promises";
|
|
3
|
+
import { randomUUID } from "node:crypto";
|
|
4
|
+
|
|
5
|
+
const heldOwnershipKeys = new Set<string>();
|
|
6
|
+
|
|
7
|
+
export class SqliteOwnerLockConflictError extends Error {
|
|
8
|
+
readonly ownershipKey: string;
|
|
9
|
+
readonly lockPath: string;
|
|
10
|
+
|
|
11
|
+
constructor(ownershipKey: string, lockPath: string, options?: ErrorOptions) {
|
|
12
|
+
super(`SQLite ownership is already held for ${ownershipKey}`, options);
|
|
13
|
+
this.name = "SqliteOwnerLockConflictError";
|
|
14
|
+
this.ownershipKey = ownershipKey;
|
|
15
|
+
this.lockPath = lockPath;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Process-lifetime ownership backed by SQLite's own cross-process file locks.
|
|
21
|
+
*
|
|
22
|
+
* The sidecar contains no application state. Its live connection is the lock, while the
|
|
23
|
+
* file itself may safely remain after close or process termination.
|
|
24
|
+
*/
|
|
25
|
+
export class SqliteOwnerLock {
|
|
26
|
+
private closed = false;
|
|
27
|
+
|
|
28
|
+
private constructor(
|
|
29
|
+
readonly ownershipKey: string,
|
|
30
|
+
readonly lockPath: string,
|
|
31
|
+
private readonly database: Database,
|
|
32
|
+
) {}
|
|
33
|
+
|
|
34
|
+
static async acquire(ownershipKey: string, lockPath: string): Promise<SqliteOwnerLock> {
|
|
35
|
+
if (heldOwnershipKeys.has(ownershipKey)) {
|
|
36
|
+
throw new SqliteOwnerLockConflictError(ownershipKey, lockPath);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
let database: Database | undefined;
|
|
40
|
+
try {
|
|
41
|
+
database = new Database(lockPath, { create: true, readwrite: true, strict: true });
|
|
42
|
+
database.exec("PRAGMA busy_timeout = 0");
|
|
43
|
+
const lockingMode = database.query<{ locking_mode: string }, []>(
|
|
44
|
+
"PRAGMA locking_mode = EXCLUSIVE",
|
|
45
|
+
).get()?.locking_mode;
|
|
46
|
+
if (lockingMode?.toLowerCase() !== "exclusive") {
|
|
47
|
+
throw new Error(`SQLite ownership sidecar did not enter exclusive mode: ${lockPath}`);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
database.exec("BEGIN EXCLUSIVE");
|
|
51
|
+
database.exec(`
|
|
52
|
+
CREATE TABLE IF NOT EXISTS owner_probe (
|
|
53
|
+
singleton INTEGER PRIMARY KEY CHECK (singleton = 1),
|
|
54
|
+
owner_token TEXT NOT NULL,
|
|
55
|
+
acquired_at TEXT NOT NULL
|
|
56
|
+
)
|
|
57
|
+
`);
|
|
58
|
+
database.query<unknown, [string, string]>(
|
|
59
|
+
`INSERT INTO owner_probe(singleton, owner_token, acquired_at)
|
|
60
|
+
VALUES (1, ?, ?)
|
|
61
|
+
ON CONFLICT(singleton) DO UPDATE SET
|
|
62
|
+
owner_token = excluded.owner_token,
|
|
63
|
+
acquired_at = excluded.acquired_at`,
|
|
64
|
+
).run(randomUUID(), new Date().toISOString());
|
|
65
|
+
database.exec("COMMIT");
|
|
66
|
+
|
|
67
|
+
// Retain the Database instance: exclusive mode keeps its file lock until close.
|
|
68
|
+
await chmod(lockPath, 0o600);
|
|
69
|
+
heldOwnershipKeys.add(ownershipKey);
|
|
70
|
+
return new SqliteOwnerLock(ownershipKey, lockPath, database);
|
|
71
|
+
} catch (error) {
|
|
72
|
+
if (database?.inTransaction) {
|
|
73
|
+
try {
|
|
74
|
+
database.exec("ROLLBACK");
|
|
75
|
+
} catch {
|
|
76
|
+
// Preserve the acquisition failure.
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
try {
|
|
80
|
+
database?.close();
|
|
81
|
+
} catch {
|
|
82
|
+
// Preserve the acquisition failure.
|
|
83
|
+
}
|
|
84
|
+
if (error instanceof SqliteOwnerLockConflictError || isSqliteLockConflict(error)) {
|
|
85
|
+
throw new SqliteOwnerLockConflictError(ownershipKey, lockPath, { cause: error });
|
|
86
|
+
}
|
|
87
|
+
throw error;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
close(): void {
|
|
92
|
+
if (this.closed) return;
|
|
93
|
+
this.closed = true;
|
|
94
|
+
try {
|
|
95
|
+
this.database.close();
|
|
96
|
+
} finally {
|
|
97
|
+
heldOwnershipKeys.delete(this.ownershipKey);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function isSqliteLockConflict(error: unknown): boolean {
|
|
103
|
+
if (!error || typeof error !== "object") return false;
|
|
104
|
+
const code = "code" in error ? String(error.code) : "";
|
|
105
|
+
return code === "SQLITE_BUSY" || code === "SQLITE_LOCKED";
|
|
106
|
+
}
|