or3-provider-sqlite 0.0.23 → 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.
@@ -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,4 @@
1
+ import { type Kysely } from 'kysely';
2
+ /** Find due parked parents without scanning unrelated response bodies. */
3
+ export declare function up(db: Kysely<unknown>): Promise<void>;
4
+ export declare function down(db: Kysely<unknown>): Promise<void>;
@@ -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;
@@ -63,6 +66,13 @@ const QUOTA_RESERVATIONS_SQL = `SELECT intent.hash, MAX(intent.size_bytes) AS re
63
66
  function uid() {
64
67
  return globalThis.crypto.randomUUID();
65
68
  }
69
+ function parseRequiredHistoryAdmission(input) {
70
+ try {
71
+ return parseChatGenerationAdmissionEnvelope(input);
72
+ } catch (cause) {
73
+ throw Object.assign(new Error("Invalid background history admission", { cause }), { code: "VALIDATION_ERROR" });
74
+ }
75
+ }
66
76
  function nowEpoch() {
67
77
  return Math.floor(Date.now() / 1e3);
68
78
  }
@@ -85,15 +95,6 @@ export async function pruneExpiredSyncSnapshots() {
85
95
  getRawDb().prepare("DELETE FROM sync_snapshots WHERE expires_at <= ?").run(nowEpoch());
86
96
  }
87
97
  }
88
- function stableJson(value) {
89
- if (value === void 0) return "undefined";
90
- if (value === null || typeof value !== "object") return JSON.stringify(value);
91
- if (Array.isArray(value)) return `[${value.map(stableJson).join(",")}]`;
92
- const record = value;
93
- return `{${Object.keys(record).sort().map(
94
- (key) => `${JSON.stringify(key)}:${stableJson(record[key])}`
95
- ).join(",")}}`;
96
- }
97
98
  function backgroundHistoryOpId(admission, stage) {
98
99
  const hex = createHash("sha256").update(`${admission.workspaceId}\0${admission.generationId}\0${stage}`).digest("hex").slice(0, 32).split("");
99
100
  hex[12] = "4";
@@ -569,6 +570,7 @@ export class SqliteSyncGatewayAdapter {
569
570
  snapshotBootstrap: "snapshot-v1",
570
571
  historyRetention: "snapshot-v1",
571
572
  backgroundGenerationHistory: "v1",
573
+ delegationTerminalHistory: "v1",
572
574
  canonicalChatHistory: "v1",
573
575
  projectOwnership: "v1",
574
576
  workspaceItems: "v1",
@@ -605,32 +607,12 @@ export class SqliteSyncGatewayAdapter {
605
607
  revision: String(threadRevision?.value ?? 0),
606
608
  thread
607
609
  };
608
- if (thread.project_id) {
609
- 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);
610
- return {
611
- status: "ok",
612
- project_ownership: "resolved",
613
- revision: String(threadRevision?.value ?? 0),
614
- thread: { ...thread, project_id: owner ? thread.project_id : null }
615
- };
616
- }
617
- const projects = raw.prepare("SELECT id, data_json FROM s_projects WHERE workspace_id = ? AND COALESCE(deleted, 0) = 0").all(actor.workspaceId);
618
- const owners = projects.filter((project) => {
619
- const payload = JSON.parse(project.data_json);
620
- const entries = typeof payload.data === "string" ? JSON.parse(payload.data) : payload.data ?? [];
621
- if (!Array.isArray(entries)) throw new Error("Canonical project membership is unresolved.");
622
- return entries.some((entry) => {
623
- if (typeof entry === "string") return entry.trim() === query.thread_id;
624
- if (!entry || typeof entry !== "object" || Array.isArray(entry) || typeof entry.id !== "string") return false;
625
- const kind = typeof entry.kind === "string" ? entry.kind.trim().toLowerCase() : entry.kind;
626
- return (kind === void 0 || kind === "chat") && entry.id.trim() === query.thread_id;
627
- });
628
- });
610
+ const ownership = resolveCanonicalProjectOwnership(raw, actor.workspaceId, query.thread_id, thread.project_id);
629
611
  return {
630
612
  status: "ok",
631
- project_ownership: owners.length > 1 ? "conflict" : "resolved",
613
+ project_ownership: ownership.status,
632
614
  revision: String(threadRevision?.value ?? 0),
633
- thread: { ...thread, project_id: owners[0]?.id ?? null }
615
+ thread: { ...thread, project_id: ownership.projectId }
634
616
  };
635
617
  }
636
618
  if (query.kind === "messages") {
@@ -659,20 +641,20 @@ export class SqliteSyncGatewayAdapter {
659
641
  }
660
642
  assertCanonicalActor(actor) {
661
643
  if (isD1Driver()) {
662
- throw new Error("SQLite D1 does not support background generation history v1");
644
+ throw Object.assign(new Error("SQLite D1 does not support background generation history v1"), { code: "UNSUPPORTED" });
663
645
  }
664
646
  const membership = getRawDb().prepare(
665
647
  `SELECT role FROM workspace_members
666
648
  WHERE workspace_id = ? AND user_id = ?`
667
649
  ).get(actor.workspaceId, actor.userId);
668
650
  if (!membership || membership.role !== "owner" && membership.role !== "editor") {
669
- throw new Error("Forbidden background history actor");
651
+ throw Object.assign(new Error("Forbidden background history actor"), { code: "FORBIDDEN" });
670
652
  }
671
653
  }
672
654
  async admitChatGeneration(actor, input) {
673
- const admission = parseChatGenerationAdmissionEnvelope(input);
655
+ const admission = parseRequiredHistoryAdmission(input);
674
656
  if (actor.workspaceId !== admission.workspaceId) {
675
- throw new Error("Invalid background history workspace");
657
+ throw Object.assign(new Error("Invalid background history workspace"), { code: "VALIDATION_ERROR" });
676
658
  }
677
659
  const raw = getRawDb();
678
660
  const fingerprint = createHash("sha256").update(stableJson(admission)).digest("hex");
@@ -686,7 +668,7 @@ export class SqliteSyncGatewayAdapter {
686
668
  ).get(admission.workspaceId, admission.generationId);
687
669
  if (receipt) {
688
670
  if (receipt.fingerprint !== fingerprint) {
689
- throw new Error("Conflicting background admission replay");
671
+ throw Object.assign(new Error("Conflicting background admission replay"), { code: "CONFLICT" });
690
672
  }
691
673
  return {
692
674
  status: "admitted",
@@ -703,7 +685,7 @@ export class SqliteSyncGatewayAdapter {
703
685
  const expectedClock = admission.expectedAssistant?.clock ?? -1;
704
686
  const admissionClock = admission.assistantMessage.clock;
705
687
  if (row && row.deleted === 1 || row && row.clock > admissionClock || row && row.clock === admissionClock && generationId !== admission.generationId || row && row.clock > expectedClock && row.clock < admissionClock || row && row.clock === expectedClock && admission.expectedAssistant?.generationId !== void 0 && generationId !== admission.expectedAssistant.generationId) {
706
- throw new Error("Conflicting continuation admission");
688
+ throw Object.assign(new Error("Conflicting continuation admission"), { code: "CONFLICT" });
707
689
  }
708
690
  }
709
691
  const records = [
@@ -737,7 +719,7 @@ export class SqliteSyncGatewayAdapter {
737
719
  { clock: entry.record.clock, hlc, opId },
738
720
  tombstone
739
721
  )) {
740
- throw new Error("Background history record was superseded");
722
+ throw Object.assign(new Error("Background history record was superseded"), { code: "SUPERSEDED" });
741
723
  }
742
724
  const sanitized = sanitizePayloadForSync(
743
725
  entry.table,
@@ -745,12 +727,12 @@ export class SqliteSyncGatewayAdapter {
745
727
  "put"
746
728
  );
747
729
  if (!sanitized) {
748
- throw new Error("Invalid background history payload");
730
+ throw Object.assign(new Error("Invalid background history payload"), { code: "VALIDATION_ERROR" });
749
731
  }
750
732
  const payload = { ...sanitized, hlc, op_id: opId };
751
733
  const payloadJson = JSON.stringify(payload);
752
734
  if (new TextEncoder().encode(payloadJson).byteLength > MAX_SYNC_PAYLOAD_BYTES) {
753
- throw new Error("Invalid background history payload size");
735
+ throw Object.assign(new Error("Invalid background history payload size"), { code: "VALIDATION_ERROR" });
754
736
  }
755
737
  const version = baseVersion + index + 1;
756
738
  raw.prepare(
@@ -806,7 +788,7 @@ export class SqliteSyncGatewayAdapter {
806
788
  const admittedPayload = admittedAssistant ? JSON.parse(admittedAssistant.data_json) : null;
807
789
  const admittedData = admittedPayload?.data && typeof admittedPayload.data === "object" ? admittedPayload.data : {};
808
790
  if (!admittedAssistant || admittedAssistant.deleted === 1 || admittedAssistant.clock !== admission.assistantMessage.clock || admittedData.generation_id !== admission.generationId) {
809
- throw new Error("Background assistant admission was superseded");
791
+ throw Object.assign(new Error("Background assistant admission was superseded"), { code: "SUPERSEDED" });
810
792
  }
811
793
  raw.prepare(
812
794
  `INSERT INTO background_generation_receipts
@@ -826,12 +808,12 @@ export class SqliteSyncGatewayAdapter {
826
808
  return result;
827
809
  }
828
810
  async finalizeChatGeneration(actor, input) {
829
- const admission = parseChatGenerationAdmissionEnvelope(input.admission);
811
+ const admission = parseRequiredHistoryAdmission(input.admission);
830
812
  if (actor.workspaceId !== admission.workspaceId) {
831
- throw new Error("Invalid background history workspace");
813
+ throw Object.assign(new Error("Invalid background history workspace"), { code: "VALIDATION_ERROR" });
832
814
  }
833
815
  const raw = getRawDb();
834
- const fingerprint = createHash("sha256").update(stableJson(input)).digest("hex");
816
+ const fingerprint = backgroundFinalizationFingerprint(input);
835
817
  return raw.transaction(() => {
836
818
  this.assertCanonicalActor(actor);
837
819
  const receipt = raw.prepare(
@@ -841,7 +823,7 @@ export class SqliteSyncGatewayAdapter {
841
823
  ).get(admission.workspaceId, admission.generationId);
842
824
  if (receipt) {
843
825
  if (receipt.fingerprint !== fingerprint) {
844
- throw new Error("Conflicting background finalization replay");
826
+ throw Object.assign(new Error("Conflicting background finalization replay"), { code: "CONFLICT" });
845
827
  }
846
828
  return receipt.outcome === "committed" ? {
847
829
  status: "committed",
@@ -852,6 +834,20 @@ export class SqliteSyncGatewayAdapter {
852
834
  reason: receipt.outcome
853
835
  };
854
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 });
855
851
  const row = raw.prepare(
856
852
  `SELECT data_json, clock, deleted FROM s_messages
857
853
  WHERE workspace_id = ? AND id = ?`
@@ -859,7 +855,8 @@ export class SqliteSyncGatewayAdapter {
859
855
  const current = row ? JSON.parse(row.data_json) : null;
860
856
  const data = current?.data && typeof current.data === "object" ? current.data : {};
861
857
  let superseded = null;
862
- if (!row || !current) superseded = "missing";
858
+ if (threadUnavailable) superseded = "deleted";
859
+ else if (!row || !current) superseded = "missing";
863
860
  else if (row.deleted === 1 || current.deleted === true) superseded = "deleted";
864
861
  else if (data.generation_id !== admission.generationId) superseded = "newer_generation";
865
862
  else if (row.clock !== admission.assistantMessage.clock) superseded = "edited";
@@ -900,7 +897,7 @@ export class SqliteSyncGatewayAdapter {
900
897
  };
901
898
  const payloadJson = JSON.stringify(payload);
902
899
  if (new TextEncoder().encode(payloadJson).byteLength > MAX_SYNC_PAYLOAD_BYTES) {
903
- throw new Error("Invalid background history payload size");
900
+ throw Object.assign(new Error("Invalid background history payload size"), { code: "VALIDATION_ERROR" });
904
901
  }
905
902
  const counter = raw.prepare("SELECT value FROM server_version_counter WHERE workspace_id = ?").get(admission.workspaceId);
906
903
  const serverVersion = (counter?.value ?? 0) + 1;
@@ -948,6 +945,127 @@ export class SqliteSyncGatewayAdapter {
948
945
  return { status: "committed", replayed: false, serverVersion };
949
946
  }).immediate();
950
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
+ }
951
1069
  async reserveUploadIntent(event, input) {
952
1070
  await assertWorkspaceScopeAuthorized(event, input.workspaceId);
953
1071
  if (!input.intentId || !Number.isSafeInteger(input.sizeBytes) || input.sizeBytes < 0 || !Number.isSafeInteger(input.expiresAt) || input.expiresAt <= nowEpoch()) {