or3-provider-sqlite 0.0.24 → 0.0.25
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/README.md +9 -3
- package/dist/module.json +1 -1
- package/dist/runtime/server/background-jobs/sqlite-provider.d.ts +34 -1
- package/dist/runtime/server/background-jobs/sqlite-provider.js +830 -29
- package/dist/runtime/server/db/migrate.js +4 -1
- package/dist/runtime/server/db/migrations/029_delegation_wait.d.ts +4 -0
- package/dist/runtime/server/db/migrations/029_delegation_wait.js +89 -0
- package/dist/runtime/server/db/schema.d.ts +8 -0
- package/dist/runtime/server/sync/background-history-fingerprint.d.ts +6 -0
- package/dist/runtime/server/sync/background-history-fingerprint.js +14 -0
- package/dist/runtime/server/sync/canonical-project-ownership.d.ts +6 -0
- package/dist/runtime/server/sync/canonical-project-ownership.js +20 -0
- package/dist/runtime/server/sync/sqlite-sync-gateway-adapter.d.ts +17 -0
- package/dist/runtime/server/sync/sqlite-sync-gateway-adapter.js +145 -34
- package/package.json +13 -7
|
@@ -51,6 +51,7 @@ const REQUIRED_SCHEMA_TABLES = [
|
|
|
51
51
|
"connect_environments",
|
|
52
52
|
"rate_limits",
|
|
53
53
|
"background_jobs",
|
|
54
|
+
"background_job_execution_quarantine",
|
|
54
55
|
"background_admission_cancels",
|
|
55
56
|
"background_generation_receipts"
|
|
56
57
|
];
|
|
@@ -59,6 +60,7 @@ import * as m025 from "./migrations/025_background_shutdown_accounting.js";
|
|
|
59
60
|
import * as m026 from "./migrations/026_retained_storage_usage.js";
|
|
60
61
|
import * as m027 from "./migrations/027_verified_storage_usage.js";
|
|
61
62
|
import * as m028 from "./migrations/028_user_scoped_device_cursors.js";
|
|
63
|
+
import * as m029 from "./migrations/029_delegation_wait.js";
|
|
62
64
|
const migrations = {
|
|
63
65
|
"001_init": m001,
|
|
64
66
|
"002_sync_tables": m002,
|
|
@@ -87,7 +89,8 @@ const migrations = {
|
|
|
87
89
|
"025_background_shutdown_accounting": m025,
|
|
88
90
|
"026_retained_storage_usage": m026,
|
|
89
91
|
"027_verified_storage_usage": m027,
|
|
90
|
-
"028_user_scoped_device_cursors": m028
|
|
92
|
+
"028_user_scoped_device_cursors": m028,
|
|
93
|
+
"029_delegation_wait": m029
|
|
91
94
|
};
|
|
92
95
|
class StaticMigrationProvider {
|
|
93
96
|
async getMigrations() {
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { sql } from "kysely";
|
|
2
|
+
export async function up(db) {
|
|
3
|
+
const columns = new Set((await sql`PRAGMA table_info(background_jobs)`.execute(db)).rows.map((row) => row.name));
|
|
4
|
+
if (!columns.has("delegation_admission_digest")) await sql`ALTER TABLE background_jobs ADD COLUMN delegation_admission_digest TEXT`.execute(db);
|
|
5
|
+
if (!columns.has("delegation_parent_id")) await sql`ALTER TABLE background_jobs ADD COLUMN delegation_parent_id TEXT`.execute(db);
|
|
6
|
+
if (!columns.has("delegation_history_retry_at")) await sql`ALTER TABLE background_jobs ADD COLUMN delegation_history_retry_at INTEGER NOT NULL DEFAULT 0`.execute(db);
|
|
7
|
+
if (!columns.has("delegation_wait_active")) await sql`ALTER TABLE background_jobs ADD COLUMN delegation_wait_active INTEGER NOT NULL DEFAULT 0 CHECK (delegation_wait_active IN (0, 1))`.execute(db);
|
|
8
|
+
if (!columns.has("delegation_wait_deadline")) await sql`ALTER TABLE background_jobs ADD COLUMN delegation_wait_deadline INTEGER`.execute(db);
|
|
9
|
+
await sql`CREATE TABLE IF NOT EXISTS background_job_execution_quarantine (
|
|
10
|
+
job_id TEXT PRIMARY KEY REFERENCES background_jobs(id) ON DELETE RESTRICT,
|
|
11
|
+
execution_json TEXT NOT NULL,
|
|
12
|
+
lease_owner TEXT,
|
|
13
|
+
lease_expires_at INTEGER
|
|
14
|
+
)`.execute(db);
|
|
15
|
+
await sql`INSERT INTO background_job_execution_quarantine (job_id, execution_json, lease_owner, lease_expires_at)
|
|
16
|
+
SELECT id, execution_json, lease_owner, lease_expires_at FROM background_jobs
|
|
17
|
+
WHERE execution_json IS NOT NULL AND json_valid(execution_json) = 0
|
|
18
|
+
ON CONFLICT(job_id) DO NOTHING`.execute(db);
|
|
19
|
+
const conflict = await sql`SELECT evidence.job_id FROM background_job_execution_quarantine AS evidence
|
|
20
|
+
JOIN background_jobs AS job ON job.id = evidence.job_id
|
|
21
|
+
WHERE job.execution_json IS NOT NULL AND json_valid(job.execution_json) = 0
|
|
22
|
+
AND job.execution_json IS NOT evidence.execution_json LIMIT 1`.execute(db);
|
|
23
|
+
if (conflict.rows.length) throw new Error("Conflicting quarantined background job execution evidence");
|
|
24
|
+
await sql`UPDATE background_jobs SET execution_json = '{"version":1,"delegationQuarantinedAt":0}',
|
|
25
|
+
delegation_wait_active = 1, delegation_wait_deadline = NULL, lease_owner = NULL, lease_expires_at = NULL
|
|
26
|
+
WHERE id IN (SELECT job_id FROM background_job_execution_quarantine)`.execute(db);
|
|
27
|
+
await sql`UPDATE background_jobs SET delegation_wait_active = 1, delegation_wait_deadline =
|
|
28
|
+
CASE WHEN json_type(execution_json, '$.delegationWait.deadlineAt') = 'integer'
|
|
29
|
+
THEN json_extract(execution_json, '$.delegationWait.deadlineAt') ELSE NULL END
|
|
30
|
+
WHERE json_type(execution_json, '$.delegationWait') IS NOT NULL`.execute(db);
|
|
31
|
+
await sql`CREATE INDEX IF NOT EXISTS background_jobs_delegation_deadline ON background_jobs(delegation_wait_deadline, started_at, id)
|
|
32
|
+
WHERE delegation_wait_active = 1 AND status = 'streaming'
|
|
33
|
+
AND (json_type(execution_json, '$.delegationWait') IS NOT 'object' OR
|
|
34
|
+
(json_extract(execution_json, '$.delegationWait.version') = 1 AND
|
|
35
|
+
(json_type(execution_json, '$.delegationQuarantinedAt') IS NOT NULL OR
|
|
36
|
+
json_extract(execution_json, '$.delegationWait.deadlineAt') IS NOT delegation_wait_deadline)))`.execute(db);
|
|
37
|
+
await sql`CREATE INDEX IF NOT EXISTS background_jobs_delegation_terminal_damage ON background_jobs(started_at, id)
|
|
38
|
+
WHERE delegation_wait_active = 1 AND status != 'streaming'
|
|
39
|
+
AND (json_type(execution_json, '$.delegationWait') IS NOT 'object' OR
|
|
40
|
+
(json_extract(execution_json, '$.delegationWait.version') = 1 AND
|
|
41
|
+
(json_type(execution_json, '$.delegationQuarantinedAt') IS NOT NULL OR
|
|
42
|
+
json_extract(execution_json, '$.delegationWait.deadlineAt') IS NOT delegation_wait_deadline)))`.execute(db);
|
|
43
|
+
await sql`CREATE INDEX IF NOT EXISTS background_jobs_delegation_missing_wait ON background_jobs(started_at, id)
|
|
44
|
+
WHERE delegation_wait_active = 1 AND json_type(execution_json, '$.delegationWait') IS NULL`.execute(db);
|
|
45
|
+
await sql`CREATE INDEX IF NOT EXISTS background_jobs_delegation_parent ON background_jobs(delegation_parent_id, id)
|
|
46
|
+
WHERE delegation_parent_id IS NOT NULL`.execute(db);
|
|
47
|
+
await sql`CREATE INDEX IF NOT EXISTS background_jobs_delegation_due
|
|
48
|
+
ON background_jobs(json_extract(execution_json, '$.delegationWait.nextCheckAt'), started_at, id)
|
|
49
|
+
WHERE json_type(execution_json, '$.delegationWait') IS NOT NULL`.execute(db);
|
|
50
|
+
await sql`CREATE INDEX IF NOT EXISTS background_jobs_delegation_invalid_due ON background_jobs(started_at, id)
|
|
51
|
+
WHERE json_extract(execution_json, '$.version') = 1
|
|
52
|
+
AND json_type(execution_json, '$.delegationWait') IS NOT NULL
|
|
53
|
+
AND json_extract(execution_json, '$.delegationWait.version') = 1
|
|
54
|
+
AND json_type(execution_json, '$.delegationQuarantinedAt') IS NULL
|
|
55
|
+
AND (COALESCE(json_type(execution_json, '$.delegationWait.nextCheckAt'), 'missing') NOT IN ('integer', 'real')
|
|
56
|
+
OR json_extract(execution_json, '$.delegationWait.nextCheckAt') < 0
|
|
57
|
+
OR json_extract(execution_json, '$.delegationWait.nextCheckAt') > 9007199254740991
|
|
58
|
+
OR json_extract(execution_json, '$.delegationWait.nextCheckAt') != CAST(json_extract(execution_json, '$.delegationWait.nextCheckAt') AS INTEGER))`.execute(db);
|
|
59
|
+
await sql`CREATE INDEX IF NOT EXISTS background_jobs_delegation_unsupported ON background_jobs(started_at, id)
|
|
60
|
+
WHERE json_type(execution_json, '$.delegationWait') IS NOT NULL
|
|
61
|
+
AND (json_extract(execution_json, '$.version') IS NOT 1
|
|
62
|
+
OR json_extract(execution_json, '$.delegationWait.version') IS NOT 1)`.execute(db);
|
|
63
|
+
await sql`CREATE INDEX IF NOT EXISTS background_jobs_delegation_quarantined ON background_jobs(started_at, id)
|
|
64
|
+
WHERE json_type(execution_json, '$.delegationQuarantinedAt') IS NOT NULL`.execute(db);
|
|
65
|
+
await sql`CREATE INDEX IF NOT EXISTS background_jobs_delegation_history_due
|
|
66
|
+
ON background_jobs(history_phase, delegation_history_retry_at, started_at, id)
|
|
67
|
+
WHERE history_phase IN ('admission_pending', 'finalization_pending')`.execute(db);
|
|
68
|
+
}
|
|
69
|
+
export async function down(db) {
|
|
70
|
+
await sql`DROP INDEX IF EXISTS background_jobs_delegation_deadline`.execute(db);
|
|
71
|
+
await sql`DROP INDEX IF EXISTS background_jobs_delegation_terminal_damage`.execute(db);
|
|
72
|
+
await sql`DROP INDEX IF EXISTS background_jobs_delegation_missing_wait`.execute(db);
|
|
73
|
+
await sql`DROP INDEX IF EXISTS background_jobs_delegation_history_due`.execute(db);
|
|
74
|
+
await sql`DROP INDEX IF EXISTS background_jobs_delegation_quarantined`.execute(db);
|
|
75
|
+
await sql`DROP INDEX IF EXISTS background_jobs_delegation_unsupported`.execute(db);
|
|
76
|
+
await sql`DROP INDEX IF EXISTS background_jobs_delegation_invalid_due`.execute(db);
|
|
77
|
+
await sql`DROP INDEX IF EXISTS background_jobs_delegation_due`.execute(db);
|
|
78
|
+
await sql`DROP INDEX IF EXISTS background_jobs_delegation_parent`.execute(db);
|
|
79
|
+
await sql`UPDATE background_jobs SET execution_json = (
|
|
80
|
+
SELECT execution_json FROM background_job_execution_quarantine AS evidence
|
|
81
|
+
WHERE evidence.job_id = background_jobs.id)
|
|
82
|
+
WHERE id IN (SELECT job_id FROM background_job_execution_quarantine)`.execute(db);
|
|
83
|
+
await sql`DROP TABLE background_job_execution_quarantine`.execute(db);
|
|
84
|
+
await sql`ALTER TABLE background_jobs DROP COLUMN delegation_wait_deadline`.execute(db);
|
|
85
|
+
await sql`ALTER TABLE background_jobs DROP COLUMN delegation_wait_active`.execute(db);
|
|
86
|
+
await sql`ALTER TABLE background_jobs DROP COLUMN delegation_parent_id`.execute(db);
|
|
87
|
+
await sql`ALTER TABLE background_jobs DROP COLUMN delegation_history_retry_at`.execute(db);
|
|
88
|
+
await sql`ALTER TABLE background_jobs DROP COLUMN delegation_admission_digest`.execute(db);
|
|
89
|
+
}
|
|
@@ -230,6 +230,8 @@ export interface BackgroundJobsTable {
|
|
|
230
230
|
lease_owner: string | null;
|
|
231
231
|
lease_expires_at: number | null;
|
|
232
232
|
attempts: number;
|
|
233
|
+
delegation_wait_active: number;
|
|
234
|
+
delegation_wait_deadline: number | null;
|
|
233
235
|
}
|
|
234
236
|
export interface BackgroundGenerationReceiptsTable {
|
|
235
237
|
id: string;
|
|
@@ -271,6 +273,12 @@ export interface Or3SqliteDb {
|
|
|
271
273
|
connect_environments: ConnectEnvironmentsTable;
|
|
272
274
|
rate_limits: RateLimitsTable;
|
|
273
275
|
background_jobs: BackgroundJobsTable;
|
|
276
|
+
background_job_execution_quarantine: {
|
|
277
|
+
job_id: string;
|
|
278
|
+
execution_json: string;
|
|
279
|
+
lease_owner: string | null;
|
|
280
|
+
lease_expires_at: number | null;
|
|
281
|
+
};
|
|
274
282
|
background_generation_receipts: BackgroundGenerationReceiptsTable;
|
|
275
283
|
s_threads: SyncedEntityTable;
|
|
276
284
|
s_messages: SyncedEntityTable;
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export declare function stableJson(value: unknown): string;
|
|
2
|
+
/** Bind a finalization receipt to its immutable admission and terminal result. */
|
|
3
|
+
export declare function backgroundFinalizationFingerprint(input: {
|
|
4
|
+
admission: unknown;
|
|
5
|
+
snapshot: unknown;
|
|
6
|
+
}): string;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
export function stableJson(value) {
|
|
3
|
+
if (value === void 0) return "undefined";
|
|
4
|
+
if (value === null || typeof value !== "object") return JSON.stringify(value);
|
|
5
|
+
if (Array.isArray(value)) return `[${value.map(stableJson).join(",")}]`;
|
|
6
|
+
const record = value;
|
|
7
|
+
return `{${Object.keys(record).sort().map(
|
|
8
|
+
(key) => `${JSON.stringify(key)}:${stableJson(record[key])}`
|
|
9
|
+
).join(",")}}`;
|
|
10
|
+
}
|
|
11
|
+
export function backgroundFinalizationFingerprint(input) {
|
|
12
|
+
const { expectedWorkspaceRevision: _revision, onlyIfThreadUnavailable: _threadPrecondition, ...snapshot } = input.snapshot;
|
|
13
|
+
return createHash("sha256").update(stableJson({ ...input, snapshot })).digest("hex");
|
|
14
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { getRawDb } from '../db/kysely.js';
|
|
2
|
+
/** Resolve explicit and legacy chat ownership inside the caller's SQLite snapshot. */
|
|
3
|
+
export declare function resolveCanonicalProjectOwnership(raw: ReturnType<typeof getRawDb>, workspaceId: string, threadId: string, explicitOwner: unknown): {
|
|
4
|
+
projectId: string | null;
|
|
5
|
+
status: 'resolved' | 'conflict';
|
|
6
|
+
};
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
export function resolveCanonicalProjectOwnership(raw, workspaceId, threadId, explicitOwner) {
|
|
2
|
+
if (explicitOwner) {
|
|
3
|
+
if (typeof explicitOwner !== "string") throw new Error("Canonical project ownership is unresolved.");
|
|
4
|
+
const owner = raw.prepare("SELECT id FROM s_projects WHERE workspace_id = ? AND id = ? AND COALESCE(deleted, 0) = 0").get(workspaceId, explicitOwner);
|
|
5
|
+
return { projectId: owner ? explicitOwner : null, status: "resolved" };
|
|
6
|
+
}
|
|
7
|
+
const projects = raw.prepare("SELECT id, data_json FROM s_projects WHERE workspace_id = ? AND COALESCE(deleted, 0) = 0").all(workspaceId);
|
|
8
|
+
const owners = projects.filter((project) => {
|
|
9
|
+
const payload = JSON.parse(project.data_json);
|
|
10
|
+
const entries = typeof payload.data === "string" ? JSON.parse(payload.data) : payload.data ?? [];
|
|
11
|
+
if (!Array.isArray(entries)) throw new Error("Canonical project membership is unresolved.");
|
|
12
|
+
return entries.some((entry) => {
|
|
13
|
+
if (typeof entry === "string") return entry.trim() === threadId;
|
|
14
|
+
if (!entry || typeof entry !== "object" || Array.isArray(entry) || typeof entry.id !== "string") return false;
|
|
15
|
+
const kind = typeof entry.kind === "string" ? entry.kind.trim().toLowerCase() : entry.kind;
|
|
16
|
+
return (kind === void 0 || kind === "chat") && entry.id.trim() === threadId;
|
|
17
|
+
});
|
|
18
|
+
});
|
|
19
|
+
return { projectId: owners[0]?.id ?? null, status: owners.length > 1 ? "conflict" : "resolved" };
|
|
20
|
+
}
|
|
@@ -9,6 +9,7 @@ import type { H3Event } from 'h3';
|
|
|
9
9
|
import type { CanonicalStorageQueryRequest, CanonicalStorageQueryResponse, SyncGatewayAdapter, SyncMaintenanceState, UploadIntentConsumptionRequest, UploadIntentReservationRequest } from '~~/server/sync/gateway/types';
|
|
10
10
|
import type { AdmitChatGenerationResult, CanonicalGenerationSnapshot, CanonicalHistoryActor, ChatGenerationAdmissionEnvelope, FinalizeChatGenerationResult } from '~~/shared/chat/background-history';
|
|
11
11
|
import type { PullRequest, PullResponse, PushBatch, PushResult, SnapshotRequest, SnapshotResponse } from '~~/shared/sync/types';
|
|
12
|
+
import { type ToolResultArtifactRow } from '~~/shared/chat/tool-result-artifact';
|
|
12
13
|
import { type CanonicalChatQuery, type CanonicalChatReadResult } from '~~/shared/chat/history-reader';
|
|
13
14
|
export declare function pruneExpiredSyncSnapshots(): Promise<void>;
|
|
14
15
|
export declare class SqliteSyncGatewayAdapter implements SyncGatewayAdapter {
|
|
@@ -23,6 +24,7 @@ export declare class SqliteSyncGatewayAdapter implements SyncGatewayAdapter {
|
|
|
23
24
|
readonly retainedStorageMetadata: "v1";
|
|
24
25
|
readonly atomicUploadQuota: "retained-v1";
|
|
25
26
|
readonly backgroundGenerationHistory?: undefined;
|
|
27
|
+
readonly delegationTerminalHistory?: undefined;
|
|
26
28
|
readonly canonicalChatHistory?: undefined;
|
|
27
29
|
readonly projectOwnership?: undefined;
|
|
28
30
|
readonly workspaceItems?: undefined;
|
|
@@ -30,6 +32,7 @@ export declare class SqliteSyncGatewayAdapter implements SyncGatewayAdapter {
|
|
|
30
32
|
readonly snapshotBootstrap: "snapshot-v1";
|
|
31
33
|
readonly historyRetention: "snapshot-v1";
|
|
32
34
|
readonly backgroundGenerationHistory: "v1";
|
|
35
|
+
readonly delegationTerminalHistory: "v1";
|
|
33
36
|
readonly canonicalChatHistory: "v1";
|
|
34
37
|
readonly projectOwnership: "v1";
|
|
35
38
|
readonly workspaceItems: "v1";
|
|
@@ -44,6 +47,20 @@ export declare class SqliteSyncGatewayAdapter implements SyncGatewayAdapter {
|
|
|
44
47
|
admission: ChatGenerationAdmissionEnvelope;
|
|
45
48
|
snapshot: CanonicalGenerationSnapshot;
|
|
46
49
|
}): Promise<FinalizeChatGenerationResult>;
|
|
50
|
+
private assertRetainedToolParent;
|
|
51
|
+
/** Persist immutable tool-result chunks and their sync changes in one workspace transaction. */
|
|
52
|
+
retainChatToolResult(actor: CanonicalHistoryActor, input: {
|
|
53
|
+
admission: ChatGenerationAdmissionEnvelope;
|
|
54
|
+
callId: string;
|
|
55
|
+
reference: string;
|
|
56
|
+
rows: ToolResultArtifactRow[];
|
|
57
|
+
}): Promise<void>;
|
|
58
|
+
/** Resolve one bounded artifact in a single authorized canonical snapshot. */
|
|
59
|
+
readChatToolResult(actor: CanonicalHistoryActor, input: {
|
|
60
|
+
admission: ChatGenerationAdmissionEnvelope;
|
|
61
|
+
callId: string;
|
|
62
|
+
reference: string;
|
|
63
|
+
}): Promise<string>;
|
|
47
64
|
reserveUploadIntent(event: H3Event, input: UploadIntentReservationRequest): Promise<void>;
|
|
48
65
|
consumeUploadIntent(event: H3Event, input: UploadIntentConsumptionRequest): Promise<void>;
|
|
49
66
|
cancelUploadIntent(event: H3Event, input: {
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { backgroundFinalizationFingerprint, stableJson } from "./background-history-fingerprint.js";
|
|
1
2
|
import { hasWorkspaceItemSemantics, WORKSPACE_ITEM_CAPABILITY } from "./workspace-item-capability.js";
|
|
2
3
|
import { createHash } from "node:crypto";
|
|
3
4
|
import { canRunSyncHistoryGc } from "./history-gc-policy.js";
|
|
@@ -21,8 +22,10 @@ import { emitWebhookSystemHook } from "~~/server/utils/webhooks/runtime";
|
|
|
21
22
|
import { incomingRevisionWins } from "~~/shared/sync/revision";
|
|
22
23
|
import { sanitizePayloadForSync } from "~~/shared/sync/sanitize";
|
|
23
24
|
import { readRequestUsage } from "~~/shared/chat/compaction";
|
|
25
|
+
import { matchesToolResultStorage, parseToolResultArtifact, prepareToolResultStorage, toolResultArtifactPrefix } from "~~/shared/chat/tool-result-artifact";
|
|
24
26
|
import { validateCanonicalChatQuery, encodeCanonicalChatSeek, parseCanonicalChatSeek } from "~~/shared/chat/history-reader";
|
|
25
27
|
import { computePullRetention } from "./history-gc-policy.js";
|
|
28
|
+
import { resolveCanonicalProjectOwnership } from "./canonical-project-ownership.js";
|
|
26
29
|
const DEFAULT_PULL_LIMIT = 100;
|
|
27
30
|
const MAX_PULL_LIMIT = 1e3;
|
|
28
31
|
const MAX_SNAPSHOT_PAGE_SIZE = 1e3;
|
|
@@ -92,15 +95,6 @@ export async function pruneExpiredSyncSnapshots() {
|
|
|
92
95
|
getRawDb().prepare("DELETE FROM sync_snapshots WHERE expires_at <= ?").run(nowEpoch());
|
|
93
96
|
}
|
|
94
97
|
}
|
|
95
|
-
function stableJson(value) {
|
|
96
|
-
if (value === void 0) return "undefined";
|
|
97
|
-
if (value === null || typeof value !== "object") return JSON.stringify(value);
|
|
98
|
-
if (Array.isArray(value)) return `[${value.map(stableJson).join(",")}]`;
|
|
99
|
-
const record = value;
|
|
100
|
-
return `{${Object.keys(record).sort().map(
|
|
101
|
-
(key) => `${JSON.stringify(key)}:${stableJson(record[key])}`
|
|
102
|
-
).join(",")}}`;
|
|
103
|
-
}
|
|
104
98
|
function backgroundHistoryOpId(admission, stage) {
|
|
105
99
|
const hex = createHash("sha256").update(`${admission.workspaceId}\0${admission.generationId}\0${stage}`).digest("hex").slice(0, 32).split("");
|
|
106
100
|
hex[12] = "4";
|
|
@@ -576,6 +570,7 @@ export class SqliteSyncGatewayAdapter {
|
|
|
576
570
|
snapshotBootstrap: "snapshot-v1",
|
|
577
571
|
historyRetention: "snapshot-v1",
|
|
578
572
|
backgroundGenerationHistory: "v1",
|
|
573
|
+
delegationTerminalHistory: "v1",
|
|
579
574
|
canonicalChatHistory: "v1",
|
|
580
575
|
projectOwnership: "v1",
|
|
581
576
|
workspaceItems: "v1",
|
|
@@ -612,32 +607,12 @@ export class SqliteSyncGatewayAdapter {
|
|
|
612
607
|
revision: String(threadRevision?.value ?? 0),
|
|
613
608
|
thread
|
|
614
609
|
};
|
|
615
|
-
|
|
616
|
-
const owner = raw.prepare("SELECT id FROM s_projects WHERE workspace_id = ? AND id = ? AND COALESCE(deleted, 0) = 0").get(actor.workspaceId, thread.project_id);
|
|
617
|
-
return {
|
|
618
|
-
status: "ok",
|
|
619
|
-
project_ownership: "resolved",
|
|
620
|
-
revision: String(threadRevision?.value ?? 0),
|
|
621
|
-
thread: { ...thread, project_id: owner ? thread.project_id : null }
|
|
622
|
-
};
|
|
623
|
-
}
|
|
624
|
-
const projects = raw.prepare("SELECT id, data_json FROM s_projects WHERE workspace_id = ? AND COALESCE(deleted, 0) = 0").all(actor.workspaceId);
|
|
625
|
-
const owners = projects.filter((project) => {
|
|
626
|
-
const payload = JSON.parse(project.data_json);
|
|
627
|
-
const entries = typeof payload.data === "string" ? JSON.parse(payload.data) : payload.data ?? [];
|
|
628
|
-
if (!Array.isArray(entries)) throw new Error("Canonical project membership is unresolved.");
|
|
629
|
-
return entries.some((entry) => {
|
|
630
|
-
if (typeof entry === "string") return entry.trim() === query.thread_id;
|
|
631
|
-
if (!entry || typeof entry !== "object" || Array.isArray(entry) || typeof entry.id !== "string") return false;
|
|
632
|
-
const kind = typeof entry.kind === "string" ? entry.kind.trim().toLowerCase() : entry.kind;
|
|
633
|
-
return (kind === void 0 || kind === "chat") && entry.id.trim() === query.thread_id;
|
|
634
|
-
});
|
|
635
|
-
});
|
|
610
|
+
const ownership = resolveCanonicalProjectOwnership(raw, actor.workspaceId, query.thread_id, thread.project_id);
|
|
636
611
|
return {
|
|
637
612
|
status: "ok",
|
|
638
|
-
project_ownership:
|
|
613
|
+
project_ownership: ownership.status,
|
|
639
614
|
revision: String(threadRevision?.value ?? 0),
|
|
640
|
-
thread: { ...thread, project_id:
|
|
615
|
+
thread: { ...thread, project_id: ownership.projectId }
|
|
641
616
|
};
|
|
642
617
|
}
|
|
643
618
|
if (query.kind === "messages") {
|
|
@@ -838,7 +813,7 @@ export class SqliteSyncGatewayAdapter {
|
|
|
838
813
|
throw Object.assign(new Error("Invalid background history workspace"), { code: "VALIDATION_ERROR" });
|
|
839
814
|
}
|
|
840
815
|
const raw = getRawDb();
|
|
841
|
-
const fingerprint =
|
|
816
|
+
const fingerprint = backgroundFinalizationFingerprint(input);
|
|
842
817
|
return raw.transaction(() => {
|
|
843
818
|
this.assertCanonicalActor(actor);
|
|
844
819
|
const receipt = raw.prepare(
|
|
@@ -859,6 +834,20 @@ export class SqliteSyncGatewayAdapter {
|
|
|
859
834
|
reason: receipt.outcome
|
|
860
835
|
};
|
|
861
836
|
}
|
|
837
|
+
if (input.snapshot.expectedWorkspaceRevision !== void 0) {
|
|
838
|
+
const expected = input.snapshot.expectedWorkspaceRevision;
|
|
839
|
+
if (typeof expected !== "string" || !/^(0|[1-9][0-9]*)$/.test(expected) || expected.length > 16)
|
|
840
|
+
throw Object.assign(new Error("Invalid terminal delegation revision"), { code: "VALIDATION_ERROR" });
|
|
841
|
+
const current2 = raw.prepare("SELECT value FROM server_version_counter WHERE workspace_id = ?").get(admission.workspaceId);
|
|
842
|
+
if (String(current2?.value ?? 0) !== expected)
|
|
843
|
+
throw Object.assign(new Error("Canonical history changed during delegation finalization"), { code: "ERR_DELEGATION_HISTORY_REVISION", retryable: true });
|
|
844
|
+
}
|
|
845
|
+
const thread = raw.prepare("SELECT deleted FROM s_threads WHERE workspace_id = ? AND id = ?").get(admission.workspaceId, admission.threadId);
|
|
846
|
+
const threadUnavailable = !thread || !!thread.deleted;
|
|
847
|
+
if (input.snapshot.onlyIfThreadUnavailable !== void 0 && input.snapshot.onlyIfThreadUnavailable !== true)
|
|
848
|
+
throw Object.assign(new Error("Invalid thread precondition"), { code: "VALIDATION_ERROR" });
|
|
849
|
+
if (input.snapshot.onlyIfThreadUnavailable && !threadUnavailable)
|
|
850
|
+
throw Object.assign(new Error("Canonical thread is available again"), { code: "ERR_DELEGATION_HISTORY_REVISION", retryable: true });
|
|
862
851
|
const row = raw.prepare(
|
|
863
852
|
`SELECT data_json, clock, deleted FROM s_messages
|
|
864
853
|
WHERE workspace_id = ? AND id = ?`
|
|
@@ -866,7 +855,8 @@ export class SqliteSyncGatewayAdapter {
|
|
|
866
855
|
const current = row ? JSON.parse(row.data_json) : null;
|
|
867
856
|
const data = current?.data && typeof current.data === "object" ? current.data : {};
|
|
868
857
|
let superseded = null;
|
|
869
|
-
if (
|
|
858
|
+
if (threadUnavailable) superseded = "deleted";
|
|
859
|
+
else if (!row || !current) superseded = "missing";
|
|
870
860
|
else if (row.deleted === 1 || current.deleted === true) superseded = "deleted";
|
|
871
861
|
else if (data.generation_id !== admission.generationId) superseded = "newer_generation";
|
|
872
862
|
else if (row.clock !== admission.assistantMessage.clock) superseded = "edited";
|
|
@@ -955,6 +945,127 @@ export class SqliteSyncGatewayAdapter {
|
|
|
955
945
|
return { status: "committed", replayed: false, serverVersion };
|
|
956
946
|
}).immediate();
|
|
957
947
|
}
|
|
948
|
+
assertRetainedToolParent(actor, admission) {
|
|
949
|
+
if (actor.workspaceId !== admission.workspaceId) throw Object.assign(new Error("Invalid tool result workspace"), { code: "VALIDATION_ERROR" });
|
|
950
|
+
this.assertCanonicalActor(actor);
|
|
951
|
+
const raw = getRawDb();
|
|
952
|
+
const receipt = raw.prepare(`SELECT fingerprint, outcome FROM background_generation_receipts
|
|
953
|
+
WHERE workspace_id = ? AND generation_id = ? AND stage = 'admission'`).get(admission.workspaceId, admission.generationId);
|
|
954
|
+
const fingerprint = createHash("sha256").update(stableJson(admission)).digest("hex");
|
|
955
|
+
const thread = raw.prepare("SELECT deleted FROM s_threads WHERE workspace_id = ? AND id = ?").get(admission.workspaceId, admission.threadId);
|
|
956
|
+
const assistant = raw.prepare("SELECT data_json, clock, deleted FROM s_messages WHERE workspace_id = ? AND id = ?").get(admission.workspaceId, admission.messageId);
|
|
957
|
+
const message = assistant ? JSON.parse(assistant.data_json) : void 0;
|
|
958
|
+
if (!receipt || receipt.outcome !== "admitted" || receipt.fingerprint !== fingerprint || !thread || thread.deleted || !assistant || assistant.deleted || assistant.clock !== admission.assistantMessage.clock || !message || message.thread_id !== admission.threadId || message.deleted === true || message.pending !== true || message.data?.generation_id !== admission.generationId)
|
|
959
|
+
throw Object.assign(new Error("Tool result parent history is unavailable"), { code: "SUPERSEDED" });
|
|
960
|
+
}
|
|
961
|
+
/** Persist immutable tool-result chunks and their sync changes in one workspace transaction. */
|
|
962
|
+
async retainChatToolResult(actor, input) {
|
|
963
|
+
const admission = parseRequiredHistoryAdmission(input.admission);
|
|
964
|
+
if (isD1Driver()) throw Object.assign(new Error("SQLite D1 does not support tool result retention"), { code: "UNSUPPORTED" });
|
|
965
|
+
if (actor.workspaceId !== admission.workspaceId || typeof input.callId !== "string" || !input.callId || new TextEncoder().encode(input.callId).length > 512 || !Array.isArray(input.rows) || !input.rows.length || input.rows.length > 32 || typeof input.reference !== "string" || input.reference.length > 2048 || input.rows.some((row) => !row || typeof row.value !== "string" || new TextEncoder().encode(row.value).length > 64 * 1024 || row.clock !== 1 || row.deleted !== false || !Number.isSafeInteger(row.created_at) || row.created_at < 0 || !Number.isSafeInteger(row.updated_at) || row.updated_at < 0))
|
|
966
|
+
throw Object.assign(new Error("Invalid tool result retention"), { code: "VALIDATION_ERROR" });
|
|
967
|
+
const content = input.rows.map((row) => row.value).join("");
|
|
968
|
+
if (new TextEncoder().encode(content).length > 256 * 1024)
|
|
969
|
+
throw Object.assign(new Error("Invalid tool result size"), { code: "VALIDATION_ERROR" });
|
|
970
|
+
const expected = await prepareToolResultStorage(content, {
|
|
971
|
+
threadId: admission.threadId,
|
|
972
|
+
parentAssistantId: admission.messageId,
|
|
973
|
+
callId: input.callId
|
|
974
|
+
});
|
|
975
|
+
if (expected.result !== input.reference || expected.rows.length !== input.rows.length || expected.rows.some((row, index) => row.id !== input.rows[index]?.id || row.name !== input.rows[index]?.name || row.value !== input.rows[index]?.value))
|
|
976
|
+
throw Object.assign(new Error("Invalid tool result identity"), { code: "VALIDATION_ERROR" });
|
|
977
|
+
const raw = getRawDb();
|
|
978
|
+
raw.transaction(() => {
|
|
979
|
+
this.assertRetainedToolParent(actor, admission);
|
|
980
|
+
const newRows = [];
|
|
981
|
+
for (const row of input.rows) {
|
|
982
|
+
const tombstone = raw.prepare("SELECT 1 FROM tombstones WHERE workspace_id = ? AND table_name = 'kv' AND pk = ?").get(admission.workspaceId, row.id);
|
|
983
|
+
const existing = raw.prepare("SELECT data_json, deleted, clock FROM s_kv WHERE workspace_id = ? AND id = ?").get(admission.workspaceId, row.id);
|
|
984
|
+
if (tombstone || existing?.deleted) throw Object.assign(new Error("Tool result was deleted"), { code: "SUPERSEDED" });
|
|
985
|
+
if (existing) {
|
|
986
|
+
const stored = JSON.parse(existing.data_json);
|
|
987
|
+
if (existing.clock !== row.clock || stored.deleted === true || stored.id !== row.id || stored.name !== row.name || stored.value !== row.value)
|
|
988
|
+
throw Object.assign(new Error("Conflicting tool result retention"), { code: "CONFLICT" });
|
|
989
|
+
} else newRows.push(row);
|
|
990
|
+
}
|
|
991
|
+
if (!newRows.length) return;
|
|
992
|
+
const counter = raw.prepare("SELECT value FROM server_version_counter WHERE workspace_id = ?").get(admission.workspaceId);
|
|
993
|
+
const baseVersion = counter?.value ?? 0;
|
|
994
|
+
raw.prepare(`INSERT INTO server_version_counter (workspace_id, value) VALUES (?, ?)
|
|
995
|
+
ON CONFLICT(workspace_id) DO UPDATE SET value = excluded.value`).run(admission.workspaceId, baseVersion + newRows.length);
|
|
996
|
+
const now = nowEpoch();
|
|
997
|
+
newRows.forEach((row, index) => {
|
|
998
|
+
const opId = `background-tool:${createHash("sha256").update(JSON.stringify([admission.workspaceId, admission.generationId, row.id])).digest("hex")}`;
|
|
999
|
+
const hlc = `${Date.now().toString(36).padStart(9, "0")}:000:background`;
|
|
1000
|
+
const sanitized = sanitizePayloadForSync("kv", row, "put");
|
|
1001
|
+
if (!sanitized) throw Object.assign(new Error("Invalid tool result payload"), { code: "VALIDATION_ERROR" });
|
|
1002
|
+
const payloadJson = JSON.stringify({ ...sanitized, hlc, op_id: opId });
|
|
1003
|
+
if (new TextEncoder().encode(payloadJson).length > MAX_SYNC_PAYLOAD_BYTES)
|
|
1004
|
+
throw Object.assign(new Error("Invalid tool result payload size"), { code: "VALIDATION_ERROR" });
|
|
1005
|
+
raw.prepare(`INSERT INTO s_kv (id, workspace_id, data_json, clock, hlc, device_id, op_id, deleted, created_at, updated_at)
|
|
1006
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, 0, ?, ?)`).run(
|
|
1007
|
+
row.id,
|
|
1008
|
+
admission.workspaceId,
|
|
1009
|
+
payloadJson,
|
|
1010
|
+
row.clock,
|
|
1011
|
+
hlc,
|
|
1012
|
+
backgroundHistoryDeviceId(admission.generationId),
|
|
1013
|
+
opId,
|
|
1014
|
+
now,
|
|
1015
|
+
now
|
|
1016
|
+
);
|
|
1017
|
+
raw.prepare(`INSERT INTO change_log (id, workspace_id, server_version, table_name, pk, op, payload_json,
|
|
1018
|
+
clock, hlc, device_id, op_id, created_at) VALUES (?, ?, ?, 'kv', ?, 'put', ?, ?, ?, ?, ?, ?)`).run(
|
|
1019
|
+
uid(),
|
|
1020
|
+
admission.workspaceId,
|
|
1021
|
+
baseVersion + index + 1,
|
|
1022
|
+
row.id,
|
|
1023
|
+
payloadJson,
|
|
1024
|
+
row.clock,
|
|
1025
|
+
hlc,
|
|
1026
|
+
backgroundHistoryDeviceId(admission.generationId),
|
|
1027
|
+
opId,
|
|
1028
|
+
now
|
|
1029
|
+
);
|
|
1030
|
+
});
|
|
1031
|
+
}).immediate();
|
|
1032
|
+
}
|
|
1033
|
+
/** Resolve one bounded artifact in a single authorized canonical snapshot. */
|
|
1034
|
+
async readChatToolResult(actor, input) {
|
|
1035
|
+
const admission = parseRequiredHistoryAdmission(input.admission);
|
|
1036
|
+
if (isD1Driver()) throw Object.assign(new Error("SQLite D1 does not support tool result retention"), { code: "UNSUPPORTED" });
|
|
1037
|
+
if (typeof input.callId !== "string" || !input.callId || new TextEncoder().encode(input.callId).length > 512 || typeof input.reference !== "string" || input.reference.length > 2048)
|
|
1038
|
+
throw Object.assign(new Error("Invalid tool result reference"), { code: "VALIDATION_ERROR" });
|
|
1039
|
+
const manifest = parseToolResultArtifact(input.reference);
|
|
1040
|
+
if (!manifest || manifest.threadId !== admission.threadId)
|
|
1041
|
+
throw Object.assign(new Error("Invalid tool result reference"), { code: "VALIDATION_ERROR" });
|
|
1042
|
+
const raw = getRawDb();
|
|
1043
|
+
return raw.transaction(() => {
|
|
1044
|
+
this.assertRetainedToolParent(actor, admission);
|
|
1045
|
+
const parts = [];
|
|
1046
|
+
for (let index = 0; index < manifest.parts; index++) {
|
|
1047
|
+
const id = `tool-result:${manifest.id}:${index}`;
|
|
1048
|
+
const row = raw.prepare("SELECT data_json, deleted, clock FROM s_kv WHERE workspace_id = ? AND id = ?").get(admission.workspaceId, id);
|
|
1049
|
+
let value;
|
|
1050
|
+
try {
|
|
1051
|
+
value = row && JSON.parse(row.data_json);
|
|
1052
|
+
} catch {
|
|
1053
|
+
throw Object.assign(new Error("Tool result is unavailable or corrupt"), { code: "TOOL_RESULT_UNAVAILABLE" });
|
|
1054
|
+
}
|
|
1055
|
+
if (!row || row.deleted || row.clock !== 1 || !value || value.deleted === true || value.id !== id || value.name !== `${toolResultArtifactPrefix(admission.threadId)}${manifest.id}:${index}` || typeof value.value !== "string" || new TextEncoder().encode(value.value).length > 64 * 1024)
|
|
1056
|
+
throw Object.assign(new Error("Tool result is unavailable or corrupt"), { code: "TOOL_RESULT_UNAVAILABLE" });
|
|
1057
|
+
parts.push(value.value);
|
|
1058
|
+
}
|
|
1059
|
+
const result = parts.join("");
|
|
1060
|
+
if (!matchesToolResultStorage(input.reference, result, {
|
|
1061
|
+
threadId: admission.threadId,
|
|
1062
|
+
parentAssistantId: admission.messageId,
|
|
1063
|
+
callId: input.callId
|
|
1064
|
+
}))
|
|
1065
|
+
throw Object.assign(new Error("Tool result is unavailable or corrupt"), { code: "TOOL_RESULT_UNAVAILABLE" });
|
|
1066
|
+
return result;
|
|
1067
|
+
}).immediate();
|
|
1068
|
+
}
|
|
958
1069
|
async reserveUploadIntent(event, input) {
|
|
959
1070
|
await assertWorkspaceScopeAuthorized(event, input.workspaceId);
|
|
960
1071
|
if (!input.intentId || !Number.isSafeInteger(input.sizeBytes) || input.sizeBytes < 0 || !Number.isSafeInteger(input.expiresAt) || input.expiresAt <= nowEpoch()) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "or3-provider-sqlite",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.25",
|
|
4
4
|
"repository": {
|
|
5
5
|
"type": "git",
|
|
6
6
|
"url": "git+https://github.com/Saluana/or3-provider-sqlite.git"
|
|
@@ -34,12 +34,14 @@
|
|
|
34
34
|
],
|
|
35
35
|
"scripts": {
|
|
36
36
|
"prepack": "bun run build",
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
37
|
+
"build": "nuxt-module-build build",
|
|
38
|
+
"lint": "eslint src --max-warnings 0",
|
|
39
|
+
"type-check": "tsc --noEmit",
|
|
40
|
+
"type-check:standalone": "tsc -p tsconfig.release.json --noEmit",
|
|
41
|
+
"type-check:host-contract": "bun run scripts/typecheck-host-contract.ts",
|
|
42
|
+
"test": "vitest run",
|
|
43
|
+
"test:host-integration": "vitest run --config vitest.host-integration.config.ts",
|
|
44
|
+
"test:delegation-artifact": "bun run scripts/test-delegation-artifact.ts"
|
|
43
45
|
},
|
|
44
46
|
"publishConfig": {
|
|
45
47
|
"access": "public"
|
|
@@ -56,12 +58,16 @@
|
|
|
56
58
|
"nuxt": "^3.0.0 || ^4.0.0"
|
|
57
59
|
},
|
|
58
60
|
"devDependencies": {
|
|
61
|
+
"@cfworker/json-schema": "4.1.1",
|
|
59
62
|
"@eslint/js": "^9.34.0",
|
|
63
|
+
"@noble/hashes": "^2.4.0",
|
|
60
64
|
"@nuxt/module-builder": "^1.0.2",
|
|
65
|
+
"@openrouter/sdk": "^1.2.145",
|
|
61
66
|
"@types/better-sqlite3": "^7.6.13",
|
|
62
67
|
"@types/node": "^24.10.1",
|
|
63
68
|
"@typescript-eslint/eslint-plugin": "^8.41.0",
|
|
64
69
|
"@typescript-eslint/parser": "^8.41.0",
|
|
70
|
+
"ajv": "^8.20.0",
|
|
65
71
|
"eslint": "^9.34.0",
|
|
66
72
|
"h3": "^1.15.11",
|
|
67
73
|
"pathe": "^2.0.3",
|