or3-provider-sqlite 0.0.24 → 0.0.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/README.md +27 -3
  2. package/dist/module.json +1 -1
  3. package/dist/runtime/server/background-jobs/sqlite-provider.d.ts +37 -2
  4. package/dist/runtime/server/background-jobs/sqlite-provider.js +848 -30
  5. package/dist/runtime/server/db/kysely.d.ts +1 -0
  6. package/dist/runtime/server/db/kysely.js +3 -0
  7. package/dist/runtime/server/db/migrate.js +12 -2
  8. package/dist/runtime/server/db/migration-schema.d.ts +3 -0
  9. package/dist/runtime/server/db/migration-schema.js +21 -0
  10. package/dist/runtime/server/db/migrations/029_delegation_wait.d.ts +4 -0
  11. package/dist/runtime/server/db/migrations/029_delegation_wait.js +89 -0
  12. package/dist/runtime/server/db/migrations/030_storage_generations.d.ts +4 -0
  13. package/dist/runtime/server/db/migrations/030_storage_generations.js +42 -0
  14. package/dist/runtime/server/db/migrations/031_storage_generation_uploads.d.ts +4 -0
  15. package/dist/runtime/server/db/migrations/031_storage_generation_uploads.js +56 -0
  16. package/dist/runtime/server/db/schema.d.ts +8 -0
  17. package/dist/runtime/server/db/storage-generation-guards.d.ts +17 -0
  18. package/dist/runtime/server/db/storage-generation-guards.js +169 -0
  19. package/dist/runtime/server/db/storage-generation-upload-guards.d.ts +7 -0
  20. package/dist/runtime/server/db/storage-generation-upload-guards.js +182 -0
  21. package/dist/runtime/server/storage/sqlite-generation-coordinator.d.ts +62 -0
  22. package/dist/runtime/server/storage/sqlite-generation-coordinator.js +223 -0
  23. package/dist/runtime/server/storage/sqlite-generation-upload-coordinator.d.ts +60 -0
  24. package/dist/runtime/server/storage/sqlite-generation-upload-coordinator.js +435 -0
  25. package/dist/runtime/server/sync/background-history-fingerprint.d.ts +6 -0
  26. package/dist/runtime/server/sync/background-history-fingerprint.js +14 -0
  27. package/dist/runtime/server/sync/canonical-project-ownership.d.ts +6 -0
  28. package/dist/runtime/server/sync/canonical-project-ownership.js +20 -0
  29. package/dist/runtime/server/sync/sqlite-sync-gateway-adapter.d.ts +17 -0
  30. package/dist/runtime/server/sync/sqlite-sync-gateway-adapter.js +145 -34
  31. package/package.json +13 -7
@@ -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
- if (thread.project_id) {
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: owners.length > 1 ? "conflict" : "resolved",
613
+ project_ownership: ownership.status,
639
614
  revision: String(threadRevision?.value ?? 0),
640
- thread: { ...thread, project_id: owners[0]?.id ?? null }
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 = createHash("sha256").update(stableJson(input)).digest("hex");
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 (!row || !current) superseded = "missing";
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.24",
3
+ "version": "0.0.26",
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
- "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
- "test": "vitest run",
42
- "test:host-integration": "vitest run --config vitest.host-integration.config.ts"
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",