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.
@@ -1,8 +1,21 @@
1
1
  import { getJobConfig } from "~~/server/utils/background-jobs/store";
2
+ import { getScopedAdmissionKey } from "~~/server/utils/background-jobs/admission-cancels";
3
+ import { buildDelegationResume } from "~~/server/utils/background-jobs/delegation-resume";
2
4
  import { readRequestUsage } from "~~/shared/chat/compaction";
5
+ import { DelegationActivitySchema, DelegationDispatchSchema, DelegationWaitSchema } from "~~/shared/chat/delegation-checkpoint";
6
+ import { delegationAdmissionFingerprint, delegationChildIdentities } from "~~/shared/chat/delegation-identities";
7
+ import { toolCallFingerprint } from "~~/shared/chat/tool-ledger";
8
+ import { parseChatGenerationAdmissionEnvelope } from "~~/shared/chat/background-history";
9
+ import { matchesToolResultStorage } from "~~/shared/chat/tool-result-artifact";
10
+ import { normalizeError, serializeError } from "~~/shared/errors";
3
11
  import { randomUUID } from "node:crypto";
4
12
  import { d1All, d1Run } from "../db/d1.js";
5
- import { getRawDb, isD1Driver } from "../db/kysely.js";
13
+ import { getRawDb, getSqliteDriver, isD1Driver } from "../db/kysely.js";
14
+ import { resolveCanonicalProjectOwnership } from "../sync/canonical-project-ownership.js";
15
+ import { backgroundFinalizationFingerprint } from "../sync/background-history-fingerprint.js";
16
+ function hasParkedDeadline(row, wait) {
17
+ return row.delegation_wait_active === 1 && row.delegation_wait_deadline === wait.deadlineAt;
18
+ }
6
19
  function parseJson(value) {
7
20
  if (!value) return void 0;
8
21
  return JSON.parse(value);
@@ -10,6 +23,120 @@ function parseJson(value) {
10
23
  function json(value) {
11
24
  return value === void 0 ? null : JSON.stringify(value);
12
25
  }
26
+ function terminalDelegationCheckpoint(raw, parent, execution, wait, parentThreadUnavailable = false) {
27
+ if (parent.status === "streaming" || parent.sync_provider_id !== "sqlite" || !parent.generation_id || !execution.history || !["admission_pending", "finalization_pending"].includes(parent.history_phase ?? "")) return null;
28
+ try {
29
+ const history = parseChatGenerationAdmissionEnvelope(execution.history);
30
+ if (history.workspaceId !== execution.workspaceId || history.threadId !== parent.thread_id || history.messageId !== parent.message_id || history.generationId !== parent.generation_id) return null;
31
+ } catch {
32
+ return null;
33
+ }
34
+ const membership = raw.prepare(`SELECT m.role FROM workspace_members m JOIN workspaces w ON w.id = m.workspace_id
35
+ WHERE m.workspace_id = ? AND m.user_id = ? AND COALESCE(w.deleted, 0) = 0`).get(execution.workspaceId, parent.user_id);
36
+ if (!membership || !["owner", "editor"].includes(membership.role)) return null;
37
+ let calls;
38
+ try {
39
+ const stored = parseJson(parent.tool_calls_json) ?? [];
40
+ if (!Array.isArray(stored) || stored.some((call2) => !call2 || typeof call2 !== "object")) return null;
41
+ calls = stored;
42
+ } catch {
43
+ return null;
44
+ }
45
+ const matches = calls.filter((call2) => call2.id === wait.callId);
46
+ const call = matches[0];
47
+ const previous = call && DelegationActivitySchema.safeParse(call.delegation);
48
+ if (matches.length !== 1 || !call || call.name !== "delegate_chat" || typeof call.args !== "string" || toolCallFingerprint(call.name, call.args) !== wait.argumentFingerprint || !["pending", "loading"].includes(call.status) && !(call.status === "error" && execution.delegationTerminalProjection?.version === 1 && previous?.success && previous.data.callId === wait.callId)) return null;
49
+ const threadAvailable = (id) => {
50
+ const row = raw.prepare("SELECT data_json, deleted FROM s_threads WHERE workspace_id = ? AND id = ?").get(execution.workspaceId, id);
51
+ if (!row || row.deleted) return false;
52
+ try {
53
+ const thread = JSON.parse(row.data_json);
54
+ if (thread.id !== id || thread.deleted) return false;
55
+ const ownership = resolveCanonicalProjectOwnership(raw, execution.workspaceId, id, thread.project_id);
56
+ return ownership.status === "resolved" && !ownership.projectId;
57
+ } catch {
58
+ return null;
59
+ }
60
+ };
61
+ const parentThread = raw.prepare("SELECT deleted FROM s_threads WHERE workspace_id = ? AND id = ?").get(execution.workspaceId, parent.thread_id);
62
+ const parentMissing = !parentThread || !!parentThread.deleted;
63
+ if (parentThreadUnavailable ? !parentMissing : !threadAvailable(parent.thread_id)) return null;
64
+ const children = [];
65
+ for (const child of wait.children) {
66
+ if (child.kind === "rejected" || !child.jobId) {
67
+ children.push({ index: child.index, ...child.kind === "prepared" ? { modelName: child.request.model } : {}, outcome: "unavailable" });
68
+ continue;
69
+ }
70
+ const row = raw.prepare("SELECT * FROM background_jobs WHERE id = ? AND delegation_parent_id = ?").get(child.jobId, parent.id);
71
+ let childExecution;
72
+ try {
73
+ childExecution = row && parseJson(row.execution_json);
74
+ } catch {
75
+ return null;
76
+ }
77
+ if (!row || !childExecution || row.user_id !== parent.user_id || row.thread_id !== child.threadId || row.message_id !== child.assistantMessageId || row.sync_provider_id !== parent.sync_provider_id || childExecution.workspaceId !== execution.workspaceId || !childExecution.history || delegationAdmissionFingerprint(childExecution.history) !== delegationAdmissionFingerprint(child.admission.history) || row.generation_id !== childExecution.history.generationId || row.status === "streaming" || !["committed", "superseded"].includes(row.history_phase ?? "")) return null;
78
+ const receipt = raw.prepare(`SELECT outcome FROM background_generation_receipts
79
+ WHERE workspace_id = ? AND generation_id = ? AND stage = 'finalization'`).get(execution.workspaceId, row.generation_id);
80
+ if (row.history_phase === "committed" ? receipt?.outcome !== "committed" : !receipt || !["deleted", "missing", "newer_generation", "edited"].includes(receipt.outcome)) return null;
81
+ const availableThread = threadAvailable(child.threadId);
82
+ if (availableThread === null) return null;
83
+ const executionUncertain = row.status === "aborted" ? childExecution.delegationDispatch !== void 0 : row.status === "error" && normalizeError(row.error).code === "ERR_MODEL_OUTCOME_UNKNOWN";
84
+ let outcome = "unavailable";
85
+ if (availableThread && row.history_phase === "committed") {
86
+ const message = raw.prepare("SELECT data_json, clock, deleted FROM s_messages WHERE workspace_id = ? AND id = ?").get(execution.workspaceId, child.assistantMessageId);
87
+ try {
88
+ const record = message && JSON.parse(message.data_json);
89
+ const expectedState = row.status === "complete" ? "complete" : row.status === "aborted" ? "aborted" : "failed";
90
+ if (message && !message.deleted && record && !record.deleted && record.id === child.assistantMessageId && record.thread_id === child.threadId && record.role === "assistant" && record.pending === false && message.clock === childExecution.history.assistantMessage.clock + 1 && record.data?.generation_id === row.generation_id && record.data?.generation_state === expectedState && record.data?.content === row.content) {
91
+ outcome = row.status === "complete" ? "complete" : row.status === "aborted" ? executionUncertain ? "unknown" : "stopped" : executionUncertain ? "unknown" : "failed";
92
+ }
93
+ } catch {
94
+ return null;
95
+ }
96
+ }
97
+ children.push({
98
+ index: child.index,
99
+ ...availableThread ? { threadId: child.threadId } : {},
100
+ modelName: child.request.model,
101
+ outcome,
102
+ ...outcome === "unavailable" && executionUncertain ? { executionUncertain: true } : {}
103
+ });
104
+ }
105
+ const activity = DelegationActivitySchema.safeParse({ version: 1, callId: wait.callId, children });
106
+ if (!activity.success) return null;
107
+ return calls.map((item) => item.id === wait.callId ? {
108
+ ...item,
109
+ status: "error",
110
+ error: parent.status === "aborted" ? "Delegation stopped." : "Delegation could not finish.",
111
+ delegation: activity.data
112
+ } : item);
113
+ }
114
+ function terminalProjectionSettled(raw, parent, execution, wait) {
115
+ if (parent.status === "streaming" || !["committed", "superseded"].includes(parent.history_phase ?? "") || !parent.generation_id || !execution.history || execution.delegationTerminalProjection?.version !== 1 || parent.completed_at === null) return false;
116
+ try {
117
+ const admission = parseChatGenerationAdmissionEnvelope(execution.history);
118
+ if (admission.workspaceId !== execution.workspaceId || admission.threadId !== parent.thread_id || admission.messageId !== parent.message_id || admission.generationId !== parent.generation_id) return false;
119
+ const job = toJob(parent);
120
+ const calls = job.tool_calls ?? [];
121
+ const matches = calls.filter((call2) => call2.id === wait.callId);
122
+ const call = matches[0];
123
+ if (matches.length !== 1 || !call || call.name !== "delegate_chat" || typeof call.args !== "string" || toolCallFingerprint(call.name, call.args) !== wait.argumentFingerprint || !DelegationActivitySchema.safeParse(call.delegation).success) return false;
124
+ const receipt = raw.prepare(`SELECT outcome, fingerprint FROM background_generation_receipts
125
+ WHERE workspace_id = ? AND generation_id = ? AND stage = 'finalization'`).get(execution.workspaceId, parent.generation_id);
126
+ const fingerprint = backgroundFinalizationFingerprint({ admission: execution.history, snapshot: {
127
+ status: job.status,
128
+ content: job.content,
129
+ reasoning: job.reasoning,
130
+ toolCalls: job.tool_calls,
131
+ usage: readRequestUsage(job.usage),
132
+ error: job.error,
133
+ completedAt: job.completedAt
134
+ } });
135
+ return receipt?.fingerprint === fingerprint && (parent.history_phase === "committed" ? receipt.outcome === "committed" : ["deleted", "missing", "newer_generation", "edited"].includes(receipt.outcome));
136
+ } catch {
137
+ return false;
138
+ }
139
+ }
13
140
  function readStoredUsage(value) {
14
141
  try {
15
142
  return readRequestUsage(parseJson(value));
@@ -118,14 +245,18 @@ const INSERT_JOB_IF_CAPACITY = `INSERT INTO background_jobs (
118
245
  chunks_received, started_at, last_activity_at, tool_calls_json,
119
246
  workflow_state_json, execution_json, idempotency_key, attempts
120
247
  ) SELECT ?, ?, ?, ?, ?, ?, 'streaming', ?, ?, ?, ?, ?, 0, ?, ?, ?, ?, ?, ?, 0
121
- WHERE (SELECT COUNT(*) FROM background_jobs WHERE status = 'streaming'
122
- AND json_extract(execution_json, '$.clientToolCall') IS NULL) < ?
123
- AND (SELECT COUNT(*) FROM background_jobs WHERE status = 'streaming' AND user_id = ?
124
- AND json_extract(execution_json, '$.clientToolCall') IS NULL) < ?
125
- AND (SELECT COUNT(*) FROM background_jobs WHERE status = 'streaming'
126
- AND json_extract(execution_json, '$.clientToolCall') IS NOT NULL) < ?
127
- AND (SELECT COUNT(*) FROM background_jobs WHERE status = 'streaming' AND user_id = ?
128
- AND json_extract(execution_json, '$.clientToolCall') IS NOT NULL) < ?
248
+ WHERE (? = 1 OR (SELECT COUNT(*) FROM background_jobs WHERE status = 'streaming'
249
+ AND json_extract(execution_json, '$.clientToolCall') IS NULL
250
+ AND delegation_wait_active = 0 AND json_type(execution_json, '$.delegationWait') IS NULL) < ?)
251
+ AND (? = 1 OR (SELECT COUNT(*) FROM background_jobs WHERE status = 'streaming' AND user_id = ?
252
+ AND json_extract(execution_json, '$.clientToolCall') IS NULL
253
+ AND delegation_wait_active = 0 AND json_type(execution_json, '$.delegationWait') IS NULL) < ?)
254
+ AND (? = 0 OR (SELECT COUNT(*) FROM background_jobs WHERE status = 'streaming'
255
+ AND (json_extract(execution_json, '$.clientToolCall') IS NOT NULL
256
+ OR delegation_wait_active = 1 OR json_type(execution_json, '$.delegationWait') IS NOT NULL)) < ?)
257
+ AND (? = 0 OR (SELECT COUNT(*) FROM background_jobs WHERE status = 'streaming' AND user_id = ?
258
+ AND (json_extract(execution_json, '$.clientToolCall') IS NOT NULL
259
+ OR delegation_wait_active = 1 OR json_type(execution_json, '$.delegationWait') IS NOT NULL)) < ?)
129
260
  AND NOT EXISTS (
130
261
  SELECT 1 FROM background_admission_cancels
131
262
  WHERE user_id = ? AND admission_id = ? AND expires_at > ?
@@ -134,10 +265,29 @@ const INSERT_JOB_IF_CAPACITY = `INSERT INTO background_jobs (
134
265
  RETURNING id`;
135
266
  export class SqliteBackgroundJobProvider {
136
267
  name = "sqlite";
268
+ // Advertise only after the native database has completed the required migration.
269
+ // Other drivers remain disabled until their coordination contracts are qualified.
270
+ get delegationCoordinatorVersion() {
271
+ if (getSqliteDriver() !== "better-sqlite3") return void 0;
272
+ try {
273
+ const applied = getRawDb().prepare(
274
+ "SELECT 1 AS applied FROM kysely_migration WHERE name = ?"
275
+ ).get("029_delegation_wait");
276
+ return applied?.applied === 1 ? 1 : void 0;
277
+ } catch {
278
+ return void 0;
279
+ }
280
+ }
281
+ lastDelegationDiagnosticCheckAt;
137
282
  async createJob(params) {
138
283
  const now = Date.now();
139
284
  const id = randomUUID();
140
285
  const config = getJobConfig();
286
+ const execution = params.execution;
287
+ if (execution && "delegationWait" in execution) {
288
+ throw new Error("Delegation waits must be parked through the fenced transition");
289
+ }
290
+ const parked = Boolean(execution && "clientToolCall" in execution && execution.clientToolCall != null);
141
291
  if (isD1Driver()) {
142
292
  if (params.idempotencyKey) {
143
293
  const existing = await one(
@@ -156,10 +306,14 @@ export class SqliteBackgroundJobProvider {
156
306
  const inserted = await all(
157
307
  INSERT_JOB_IF_CAPACITY,
158
308
  ...insertParameters(id, params, now),
309
+ Number(parked),
159
310
  config.maxConcurrentJobs,
311
+ Number(parked),
160
312
  params.userId,
161
313
  config.maxConcurrentJobsPerUser,
314
+ Number(parked),
162
315
  config.maxConcurrentJobs,
316
+ Number(parked),
163
317
  params.userId,
164
318
  config.maxConcurrentJobsPerUser,
165
319
  params.userId,
@@ -205,13 +359,14 @@ export class SqliteBackgroundJobProvider {
205
359
  }
206
360
  const active = raw.prepare(
207
361
  `SELECT
208
- SUM(CASE WHEN json_extract(execution_json, '$.clientToolCall') IS NULL THEN 1 ELSE 0 END) AS total,
209
- SUM(CASE WHEN user_id = ? AND json_extract(execution_json, '$.clientToolCall') IS NULL THEN 1 ELSE 0 END) AS user_total,
210
- SUM(CASE WHEN json_extract(execution_json, '$.clientToolCall') IS NOT NULL THEN 1 ELSE 0 END) AS waiting_total,
211
- SUM(CASE WHEN user_id = ? AND json_extract(execution_json, '$.clientToolCall') IS NOT NULL THEN 1 ELSE 0 END) AS waiting_user_total
362
+ SUM(CASE WHEN json_extract(execution_json, '$.clientToolCall') IS NULL AND delegation_wait_active = 0 AND json_type(execution_json, '$.delegationWait') IS NULL THEN 1 ELSE 0 END) AS total,
363
+ SUM(CASE WHEN user_id = ? AND json_extract(execution_json, '$.clientToolCall') IS NULL AND delegation_wait_active = 0 AND json_type(execution_json, '$.delegationWait') IS NULL THEN 1 ELSE 0 END) AS user_total,
364
+ SUM(CASE WHEN json_extract(execution_json, '$.clientToolCall') IS NOT NULL OR delegation_wait_active = 1 OR json_type(execution_json, '$.delegationWait') IS NOT NULL THEN 1 ELSE 0 END) AS waiting_total,
365
+ SUM(CASE WHEN user_id = ? AND (json_extract(execution_json, '$.clientToolCall') IS NOT NULL OR delegation_wait_active = 1 OR json_type(execution_json, '$.delegationWait') IS NOT NULL) THEN 1 ELSE 0 END) AS waiting_user_total
212
366
  FROM background_jobs WHERE status = 'streaming'`
213
367
  ).get(params.userId, params.userId);
214
- if ((active.total ?? 0) >= config.maxConcurrentJobs || (active.user_total ?? 0) >= config.maxConcurrentJobsPerUser || (active.waiting_total ?? 0) >= config.maxConcurrentJobs || (active.waiting_user_total ?? 0) >= config.maxConcurrentJobsPerUser) {
368
+ const capacityExceeded = parked ? (active.waiting_total ?? 0) >= config.maxConcurrentJobs || (active.waiting_user_total ?? 0) >= config.maxConcurrentJobsPerUser : (active.total ?? 0) >= config.maxConcurrentJobs || (active.user_total ?? 0) >= config.maxConcurrentJobsPerUser;
369
+ if (capacityExceeded) {
215
370
  throw new Error(
216
371
  "Maximum concurrent background jobs reached"
217
372
  );
@@ -248,6 +403,8 @@ export class SqliteBackgroundJobProvider {
248
403
  const abortJob = `UPDATE background_jobs SET status = 'aborted',
249
404
  completed_at = ?, last_activity_at = ?, error = ?,
250
405
  lease_owner = NULL, lease_expires_at = NULL,
406
+ execution_json = CASE WHEN json_type(execution_json, '$.delegationWait') = 'object'
407
+ THEN json_set(execution_json, '$.delegationWait.nextCheckAt', ?) ELSE execution_json END,
251
408
  history_phase = CASE
252
409
  WHEN generation_id IS NOT NULL
253
410
  AND COALESCE(history_phase, 'ready') = 'ready'
@@ -272,6 +429,7 @@ export class SqliteBackgroundJobProvider {
272
429
  now,
273
430
  now,
274
431
  "Cancelled by user",
432
+ now,
275
433
  job2.id
276
434
  ).changes;
277
435
  return {
@@ -302,6 +460,7 @@ export class SqliteBackgroundJobProvider {
302
460
  now,
303
461
  now,
304
462
  "Cancelled by user",
463
+ now,
305
464
  job.id
306
465
  );
307
466
  return {
@@ -387,6 +546,8 @@ export class SqliteBackgroundJobProvider {
387
546
  return await run(
388
547
  `UPDATE background_jobs SET status = 'aborted', completed_at = ?,
389
548
  last_activity_at = ?, lease_owner = NULL, lease_expires_at = NULL,
549
+ execution_json = CASE WHEN json_type(execution_json, '$.delegationWait') = 'object'
550
+ THEN json_set(execution_json, '$.delegationWait.nextCheckAt', ?) ELSE execution_json END,
390
551
  history_phase = CASE
391
552
  WHEN generation_id IS NOT NULL
392
553
  AND COALESCE(history_phase, 'ready') = 'ready'
@@ -395,6 +556,7 @@ export class SqliteBackgroundJobProvider {
395
556
  WHERE id = ? AND user_id = ? AND status = 'streaming'`,
396
557
  now,
397
558
  now,
559
+ now,
398
560
  jobId,
399
561
  userId
400
562
  ) > 0;
@@ -415,21 +577,22 @@ export class SqliteBackgroundJobProvider {
415
577
  lease_owner = ?,
416
578
  lease_expires_at = ?,
417
579
  last_activity_at = ?,
418
- content = CASE WHEN attempts > 0
580
+ content = CASE WHEN attempts > 0 AND json_type(execution_json, '$.delegationDispatch') IS NULL
419
581
  THEN COALESCE(json_extract(execution_json, '$.contentBase'), '')
420
582
  ELSE content END,
421
- reasoning = CASE WHEN attempts > 0
583
+ reasoning = CASE WHEN attempts > 0 AND json_type(execution_json, '$.delegationDispatch') IS NULL
422
584
  THEN COALESCE(json_extract(execution_json, '$.reasoningBase'), '')
423
585
  ELSE reasoning END,
424
- usage_json = CASE WHEN attempts > 0
586
+ usage_json = CASE WHEN attempts > 0 AND json_type(execution_json, '$.delegationDispatch') IS NULL
425
587
  THEN CASE WHEN json_type(execution_json, '$.normalizedToolState.requestUsage') = 'object'
426
588
  THEN json_extract(execution_json, '$.normalizedToolState.requestUsage')
427
589
  ELSE NULL END
428
590
  ELSE usage_json END,
429
- chunks_received = CASE WHEN attempts > 0 THEN 0 ELSE chunks_received END,
591
+ chunks_received = CASE WHEN attempts > 0 AND json_type(execution_json, '$.delegationDispatch') IS NULL THEN 0 ELSE chunks_received END,
430
592
  attempts = attempts + 1
431
593
  WHERE id = ? AND status = 'streaming' AND execution_json IS NOT NULL
432
594
  AND json_extract(execution_json, '$.clientToolCall') IS NULL
595
+ AND delegation_wait_active = 0 AND json_type(execution_json, '$.delegationWait') IS NULL
433
596
  AND COALESCE(history_phase, 'ready') = 'ready'
434
597
  AND (lease_owner IS NULL OR lease_expires_at <= ?)
435
598
  RETURNING *`,
@@ -447,23 +610,24 @@ export class SqliteBackgroundJobProvider {
447
610
  lease_owner = ?,
448
611
  lease_expires_at = ?,
449
612
  last_activity_at = ?,
450
- content = CASE WHEN attempts > 0
613
+ content = CASE WHEN attempts > 0 AND json_type(execution_json, '$.delegationDispatch') IS NULL
451
614
  THEN COALESCE(json_extract(execution_json, '$.contentBase'), '')
452
615
  ELSE content END,
453
- reasoning = CASE WHEN attempts > 0
616
+ reasoning = CASE WHEN attempts > 0 AND json_type(execution_json, '$.delegationDispatch') IS NULL
454
617
  THEN COALESCE(json_extract(execution_json, '$.reasoningBase'), '')
455
618
  ELSE reasoning END,
456
- usage_json = CASE WHEN attempts > 0
619
+ usage_json = CASE WHEN attempts > 0 AND json_type(execution_json, '$.delegationDispatch') IS NULL
457
620
  THEN CASE WHEN json_type(execution_json, '$.normalizedToolState.requestUsage') = 'object'
458
621
  THEN json_extract(execution_json, '$.normalizedToolState.requestUsage')
459
622
  ELSE NULL END
460
623
  ELSE usage_json END,
461
- chunks_received = CASE WHEN attempts > 0 THEN 0 ELSE chunks_received END,
624
+ chunks_received = CASE WHEN attempts > 0 AND json_type(execution_json, '$.delegationDispatch') IS NULL THEN 0 ELSE chunks_received END,
462
625
  attempts = attempts + 1
463
626
  WHERE id = (
464
627
  SELECT id FROM background_jobs
465
628
  WHERE status = 'streaming' AND execution_json IS NOT NULL
466
629
  AND json_extract(execution_json, '$.clientToolCall') IS NULL
630
+ AND delegation_wait_active = 0 AND json_type(execution_json, '$.delegationWait') IS NULL
467
631
  AND COALESCE(history_phase, 'ready') = 'ready'
468
632
  AND (lease_owner IS NULL OR lease_expires_at <= ?)
469
633
  ORDER BY started_at ASC LIMIT 1
@@ -475,10 +639,596 @@ export class SqliteBackgroundJobProvider {
475
639
  );
476
640
  return row ? toJob(row) : null;
477
641
  }
642
+ async beginDelegationDispatch(jobId, leaseOwner) {
643
+ if (isD1Driver()) throw new Error("Delegation dispatch is unavailable for D1");
644
+ const now = Date.now();
645
+ const row = await one(
646
+ `UPDATE background_jobs SET execution_json = json_set(execution_json,
647
+ '$.delegationDispatchSequence', COALESCE(json_extract(execution_json, '$.delegationDispatchSequence'), 0) + 1,
648
+ '$.delegationDispatch', json_object('version', 1, 'sequence',
649
+ COALESCE(json_extract(execution_json, '$.delegationDispatchSequence'), 0) + 1, 'state', 'started')),
650
+ last_activity_at = ?
651
+ WHERE id = ? AND status = 'streaming' AND lease_owner = ? AND lease_expires_at > ?
652
+ AND COALESCE(history_phase, 'ready') = 'ready'
653
+ AND json_extract(execution_json, '$.delegationRecoveryPolicy') = 'v1'
654
+ AND json_type(execution_json, '$.delegationDispatch') IS NULL
655
+ AND delegation_wait_active = 0 AND json_type(execution_json, '$.delegationWait') IS NULL
656
+ AND json_type(execution_json, '$.clientToolCall') IS NULL
657
+ AND json_type(execution_json, '$.cancellationRequestedAt') IS NULL
658
+ AND (json_type(execution_json, '$.delegationDispatchSequence') IS NULL OR
659
+ (json_type(execution_json, '$.delegationDispatchSequence') = 'integer'
660
+ AND json_extract(execution_json, '$.delegationDispatchSequence') BETWEEN 0 AND 9007199254740990))
661
+ RETURNING execution_json`,
662
+ now,
663
+ jobId,
664
+ leaseOwner,
665
+ now
666
+ );
667
+ return row ? DelegationDispatchSchema.parse(JSON.parse(row.execution_json).delegationDispatch) : null;
668
+ }
669
+ async commitDelegationDispatch(jobId, leaseOwner, sequence, execution, toolCalls) {
670
+ if (isD1Driver()) throw new Error("Delegation dispatch is unavailable for D1");
671
+ if (!Number.isSafeInteger(sequence) || sequence < 1 || execution.version !== 1 || execution.delegationRecoveryPolicy !== "v1" || execution.delegationDispatchSequence !== sequence || execution.delegationDispatch !== void 0 || execution.cancellationRequestedAt !== void 0 || execution.delegationWait !== void 0 || execution.clientToolCall !== void 0) return false;
672
+ const now = Date.now();
673
+ return await run(
674
+ `UPDATE background_jobs SET execution_json = ?, tool_calls_json = ?, last_activity_at = ?
675
+ WHERE id = ? AND status = 'streaming' AND lease_owner = ? AND lease_expires_at > ?
676
+ AND COALESCE(history_phase, 'ready') = 'ready'
677
+ AND json_extract(execution_json, '$.workspaceId') = ?
678
+ AND json_extract(execution_json, '$.delegationRecoveryPolicy') = 'v1'
679
+ AND json_extract(execution_json, '$.delegationDispatchSequence') = ?
680
+ AND json_extract(execution_json, '$.delegationDispatch.version') = 1
681
+ AND json_extract(execution_json, '$.delegationDispatch.state') = 'started'
682
+ AND json_extract(execution_json, '$.delegationDispatch.sequence') = ?
683
+ AND json_extract(execution_json, '$.delegationDefaults') IS json_extract(?, '$.delegationDefaults')
684
+ AND json_type(execution_json, '$.cancellationRequestedAt') IS NULL`,
685
+ json(execution),
686
+ json(toolCalls),
687
+ now,
688
+ jobId,
689
+ leaseOwner,
690
+ now,
691
+ execution.workspaceId,
692
+ sequence,
693
+ sequence,
694
+ json(execution)
695
+ ) > 0;
696
+ }
697
+ async parkDelegationWait(jobId, leaseOwner, execution, toolCalls) {
698
+ const now = Date.now();
699
+ const parsed = DelegationWaitSchema.safeParse(execution.delegationWait);
700
+ if (!parsed.success || execution.version !== 1 || execution.delegationRecoveryPolicy !== "v1" || execution.delegationDispatchSequence !== void 0 && (!Number.isSafeInteger(execution.delegationDispatchSequence) || execution.delegationDispatchSequence < 0) || execution.clientToolCall || execution.cancellationRequestedAt !== void 0 || execution.delegationDispatch || parsed.data.expiredAt !== void 0 || parsed.data.deadlineAt <= now)
701
+ throw new Error("Invalid delegation wait checkpoint");
702
+ const config = getJobConfig();
703
+ const row = await one(
704
+ `UPDATE background_jobs SET execution_json = ?, tool_calls_json = ?, delegation_wait_active = 1, delegation_wait_deadline = ?,
705
+ lease_owner = NULL, lease_expires_at = NULL, last_activity_at = ?
706
+ WHERE id = ? AND status = 'streaming' AND lease_owner = ? AND lease_expires_at > ?
707
+ AND COALESCE(history_phase, 'ready') = 'ready'
708
+ AND json_extract(execution_json, '$.workspaceId') = ?
709
+ AND json_extract(execution_json, '$.delegationRecoveryPolicy') = 'v1'
710
+ AND json_extract(execution_json, '$.delegationDefaults') IS json_extract(?, '$.delegationDefaults')
711
+ AND json_type(execution_json, '$.delegationDispatch') IS NULL
712
+ AND (json_type(execution_json, '$.delegationDispatchSequence') IS NULL OR
713
+ (json_type(execution_json, '$.delegationDispatchSequence') = 'integer'
714
+ AND json_extract(execution_json, '$.delegationDispatchSequence') BETWEEN 0 AND 9007199254740991))
715
+ AND COALESCE(json_extract(execution_json, '$.delegationDispatchSequence'), 0) = ?
716
+ AND json_type(execution_json, '$.cancellationRequestedAt') IS NULL
717
+ AND delegation_wait_active = 0 AND json_type(execution_json, '$.delegationWait') IS NULL
718
+ AND json_extract(execution_json, '$.clientToolCall') IS NULL
719
+ AND (SELECT COUNT(*) FROM background_jobs WHERE status = 'streaming'
720
+ AND (json_extract(execution_json, '$.clientToolCall') IS NOT NULL
721
+ OR delegation_wait_active = 1 OR json_type(execution_json, '$.delegationWait') IS NOT NULL)) < ?
722
+ AND (SELECT COUNT(*) FROM background_jobs WHERE status = 'streaming'
723
+ AND user_id = (SELECT user_id FROM background_jobs WHERE id = ?)
724
+ AND (json_extract(execution_json, '$.clientToolCall') IS NOT NULL
725
+ OR delegation_wait_active = 1 OR json_type(execution_json, '$.delegationWait') IS NOT NULL)) < ?
726
+ RETURNING id`,
727
+ json(execution),
728
+ json(toolCalls),
729
+ parsed.data.deadlineAt,
730
+ now,
731
+ jobId,
732
+ leaseOwner,
733
+ now,
734
+ execution.workspaceId,
735
+ json(execution),
736
+ execution.delegationDispatchSequence ?? 0,
737
+ config.maxConcurrentJobs,
738
+ jobId,
739
+ config.maxConcurrentJobsPerUser
740
+ );
741
+ return Boolean(row);
742
+ }
743
+ async claimNextDelegationWait(leaseOwner, now, leaseExpiresAt) {
744
+ if (!leaseOwner || !Number.isSafeInteger(now) || !Number.isSafeInteger(leaseExpiresAt) || leaseExpiresAt <= now)
745
+ throw new Error("Invalid delegation coordinator lease");
746
+ await run(`UPDATE background_jobs SET status = 'aborted', completed_at = ?, last_activity_at = ?,
747
+ lease_owner = NULL, lease_expires_at = NULL,
748
+ history_phase = CASE WHEN generation_id IS NOT NULL AND COALESCE(history_phase, 'ready') = 'ready'
749
+ THEN 'finalization_pending' ELSE history_phase END
750
+ WHERE status = 'streaming' AND id IN (
751
+ SELECT child.id FROM background_jobs AS parent CROSS JOIN background_jobs AS child
752
+ WHERE child.delegation_parent_id = parent.id AND child.user_id = parent.user_id
753
+ AND parent.delegation_wait_active = 1 AND parent.status != 'streaming'
754
+ AND (json_type(parent.execution_json, '$.delegationWait') IS NOT 'object' OR
755
+ (json_extract(parent.execution_json, '$.delegationWait.version') = 1 AND
756
+ (json_type(parent.execution_json, '$.delegationQuarantinedAt') IS NOT NULL OR
757
+ json_extract(parent.execution_json, '$.delegationWait.deadlineAt') IS NOT parent.delegation_wait_deadline)))
758
+ AND child.status = 'streaming'
759
+ ORDER BY parent.started_at, parent.id, child.id LIMIT 20
760
+ )`, now, now);
761
+ await run(`UPDATE background_jobs SET status = 'aborted', completed_at = ?, last_activity_at = ?,
762
+ lease_owner = NULL, lease_expires_at = NULL,
763
+ history_phase = CASE WHEN generation_id IS NOT NULL AND COALESCE(history_phase, 'ready') = 'ready'
764
+ THEN 'finalization_pending' ELSE history_phase END
765
+ WHERE status = 'streaming' AND id IN (
766
+ SELECT child.id FROM background_jobs AS parent CROSS JOIN background_jobs AS child
767
+ WHERE child.delegation_parent_id = parent.id AND child.user_id = parent.user_id
768
+ AND parent.delegation_wait_active = 1 AND parent.status = 'streaming'
769
+ AND (parent.delegation_wait_deadline IS NULL OR parent.delegation_wait_deadline <= ?)
770
+ AND (json_type(parent.execution_json, '$.delegationWait') IS NOT 'object' OR
771
+ (json_extract(parent.execution_json, '$.delegationWait.version') = 1 AND
772
+ (json_type(parent.execution_json, '$.delegationQuarantinedAt') IS NOT NULL OR
773
+ json_extract(parent.execution_json, '$.delegationWait.deadlineAt') IS NOT parent.delegation_wait_deadline)))
774
+ AND child.status = 'streaming'
775
+ ORDER BY parent.delegation_wait_deadline, parent.started_at, parent.id, child.id LIMIT 20
776
+ )`, now, now, now);
777
+ if (this.lastDelegationDiagnosticCheckAt === void 0 || now < this.lastDelegationDiagnosticCheckAt || now - this.lastDelegationDiagnosticCheckAt >= 6e4) {
778
+ const unsupported = await all(
779
+ `SELECT id FROM background_jobs WHERE status IN ('streaming', 'complete', 'error', 'aborted')
780
+ AND json_type(execution_json, '$.delegationWait') IS NOT NULL
781
+ AND (json_extract(execution_json, '$.version') IS NOT 1
782
+ OR json_extract(execution_json, '$.delegationWait.version') IS NOT 1)
783
+ ORDER BY started_at, id LIMIT 20`
784
+ );
785
+ const quarantined = await all(
786
+ `SELECT id FROM background_jobs WHERE status IN ('streaming', 'complete', 'error', 'aborted')
787
+ AND json_type(execution_json, '$.delegationQuarantinedAt') IS NOT NULL
788
+ ORDER BY started_at, id LIMIT 20`
789
+ );
790
+ const missing = await all(
791
+ `SELECT id FROM background_jobs WHERE delegation_wait_active = 1
792
+ AND json_type(execution_json, '$.delegationWait') IS NULL
793
+ ORDER BY started_at, id LIMIT 20`
794
+ );
795
+ this.lastDelegationDiagnosticCheckAt = now;
796
+ const blocked = [
797
+ missing.length && `missing wait: ${missing.map((row2) => row2.id).join(", ")}`,
798
+ unsupported.length && `unsupported: ${unsupported.map((row2) => row2.id).join(", ")}`,
799
+ quarantined.length && `quarantined: ${quarantined.map((row2) => row2.id).join(", ")}`
800
+ ].filter(Boolean);
801
+ if (blocked.length) console.warn(`[background-jobs] Delegation checkpoints block recovery (up to 20 job IDs per category): ${blocked.join("; ")}.`);
802
+ }
803
+ const invalid = await one(
804
+ `UPDATE background_jobs SET
805
+ execution_json = json_set(execution_json, '$.delegationQuarantinedAt', ?),
806
+ lease_owner = NULL, lease_expires_at = NULL
807
+ WHERE id = (
808
+ SELECT id FROM background_jobs WHERE status IN ('streaming', 'complete', 'error', 'aborted')
809
+ AND json_extract(execution_json, '$.version') = 1
810
+ AND json_type(execution_json, '$.delegationWait') IS NOT NULL
811
+ AND json_extract(execution_json, '$.delegationWait.version') = 1
812
+ AND json_type(execution_json, '$.delegationQuarantinedAt') IS NULL
813
+ AND (COALESCE(json_type(execution_json, '$.delegationWait.nextCheckAt'), 'missing') NOT IN ('integer', 'real')
814
+ OR json_extract(execution_json, '$.delegationWait.nextCheckAt') < 0
815
+ OR json_extract(execution_json, '$.delegationWait.nextCheckAt') > 9007199254740991
816
+ OR json_extract(execution_json, '$.delegationWait.nextCheckAt') != CAST(json_extract(execution_json, '$.delegationWait.nextCheckAt') AS INTEGER))
817
+ AND (lease_owner IS NULL OR lease_expires_at <= ?)
818
+ ORDER BY started_at, id LIMIT 1
819
+ ) RETURNING id`,
820
+ now,
821
+ now
822
+ );
823
+ if (invalid) console.warn(`[background-jobs] Quarantined delegation wait with invalid next-check time (job ${invalid.id}).`);
824
+ const row = await one(
825
+ `UPDATE background_jobs SET lease_owner = ?, lease_expires_at = ?, last_activity_at = ?
826
+ WHERE id = (
827
+ SELECT id FROM background_jobs WHERE status IN ('streaming', 'complete', 'error', 'aborted')
828
+ AND json_extract(execution_json, '$.version') = 1
829
+ AND json_type(execution_json, '$.delegationWait') IS NOT NULL
830
+ AND json_extract(execution_json, '$.delegationWait.version') = 1
831
+ AND json_type(execution_json, '$.delegationQuarantinedAt') IS NULL
832
+ AND json_type(execution_json, '$.delegationWait.nextCheckAt') IN ('integer', 'real')
833
+ AND json_extract(execution_json, '$.delegationWait.nextCheckAt') >= 0
834
+ AND json_extract(execution_json, '$.delegationWait.nextCheckAt') = CAST(json_extract(execution_json, '$.delegationWait.nextCheckAt') AS INTEGER)
835
+ AND json_extract(execution_json, '$.delegationWait.nextCheckAt') <= ?
836
+ AND (lease_owner IS NULL OR lease_expires_at <= ?)
837
+ ORDER BY json_extract(execution_json, '$.delegationWait.nextCheckAt'), started_at, id
838
+ LIMIT 1
839
+ ) RETURNING *`,
840
+ leaseOwner,
841
+ leaseExpiresAt,
842
+ now,
843
+ now,
844
+ now
845
+ );
846
+ if (!row) return null;
847
+ const quarantineClaim = async () => {
848
+ const changed = await run(`UPDATE background_jobs SET
849
+ execution_json = json_set(execution_json, '$.delegationQuarantinedAt', ?),
850
+ lease_owner = NULL, lease_expires_at = NULL
851
+ WHERE id = ? AND status IN ('streaming', 'complete', 'error', 'aborted') AND lease_owner = ?
852
+ AND lease_expires_at > ?`, now, row.id, leaseOwner, Date.now());
853
+ if (!changed) throw leaseLost();
854
+ };
855
+ let job;
856
+ try {
857
+ job = toJob(row);
858
+ } catch {
859
+ await quarantineClaim();
860
+ throw new Error(`Invalid delegation job checkpoint (job ${row.id})`);
861
+ }
862
+ const wait = DelegationWaitSchema.safeParse(job.execution?.delegationWait);
863
+ if (!wait.success || !hasParkedDeadline(row, wait.data)) {
864
+ await quarantineClaim();
865
+ throw new Error(`Invalid delegation wait checkpoint (job ${job.id})`);
866
+ }
867
+ return job;
868
+ }
869
+ async admitDelegationChild(input) {
870
+ if (isD1Driver()) throw new Error("Atomic delegation admission is unavailable for D1");
871
+ const config = getJobConfig();
872
+ const raw = getRawDb();
873
+ return raw.transaction(() => {
874
+ const now = Date.now();
875
+ const parent = raw.prepare("SELECT * FROM background_jobs WHERE id = ?").get(input.parentJobId);
876
+ if (!parent || parent.status !== "streaming" || (parent.history_phase ?? "ready") !== "ready" || parent.lease_owner !== input.leaseOwner || !parent.lease_expires_at || parent.lease_expires_at <= now) return { status: "not-owned" };
877
+ const execution = parseJson(parent.execution_json);
878
+ const parsed = DelegationWaitSchema.safeParse(execution?.delegationWait);
879
+ if (!execution || "delegationQuarantinedAt" in execution || !parsed.success || !hasParkedDeadline(parent, parsed.data))
880
+ throw new Error("Invalid delegation wait checkpoint");
881
+ const wait = parsed.data;
882
+ if (wait.callId !== input.callId || wait.argumentFingerprint !== input.argumentFingerprint)
883
+ throw new Error("Conflicting delegation identity");
884
+ const prepared = wait.children[input.childIndex];
885
+ if (!prepared || prepared.kind !== "prepared" || prepared.index !== input.childIndex || prepared.settlement)
886
+ throw new Error("Invalid delegation child");
887
+ if (!parent.generation_id) throw new Error("Delegation parent has no generation identity");
888
+ const identities = delegationChildIdentities({
889
+ userId: parent.user_id,
890
+ workspaceId: execution.workspaceId,
891
+ parentGenerationId: parent.generation_id,
892
+ callId: wait.callId,
893
+ index: prepared.index
894
+ });
895
+ if (prepared.admissionId !== identities.admissionId || prepared.threadId !== identities.threadId || prepared.userMessageId !== identities.userMessageId || prepared.assistantMessageId !== identities.assistantMessageId)
896
+ throw new Error("Delegation child identity is outside its parent scope");
897
+ const admissionKey = getScopedAdmissionKey(parent.user_id, execution.workspaceId, prepared.admissionId);
898
+ const params = input.child;
899
+ const childExecution = params.execution;
900
+ if (!childExecution || "kind" in childExecution || childExecution.version !== 1 || params.kind !== "chat" || params.historyPhase !== "admission_pending" || params.userId !== parent.user_id || params.syncProviderId !== parent.sync_provider_id || !params.syncProviderId || params.idempotencyKey !== admissionKey || params.threadId !== prepared.threadId || params.messageId !== prepared.assistantMessageId || params.model !== prepared.request.model || childExecution.body.model !== params.model || params.initialContent || params.initialReasoning || params.tool_calls || params.workflow_state || childExecution.workspaceId !== execution.workspaceId || childExecution.apiKeyCiphertext !== execution.apiKeyCiphertext || childExecution.credentialSource !== execution.credentialSource || childExecution.referer !== execution.referer || childExecution.delegationRecoveryPolicy !== "v1" || childExecution.delegationWait || childExecution.clientToolCall || childExecution.delegationDispatch || childExecution.cancellationRequestedAt !== void 0)
901
+ throw new Error("Delegation child authority or identity mismatch");
902
+ const history = parseChatGenerationAdmissionEnvelope(childExecution.history);
903
+ if (history.version !== 1 || history.kind !== "new-turn" || history.admissionId !== prepared.admissionId || history.generationId !== params.generationId || params.generationId !== identities.generationId || history.workspaceId !== execution.workspaceId || history.threadId !== prepared.threadId || history.messageId !== prepared.assistantMessageId || history.thread?.id !== prepared.threadId || history.userMessage?.id !== prepared.userMessageId || history.userMessage.thread_id !== prepared.threadId || history.userMessage.role !== "user" || history.assistantMessage.id !== prepared.assistantMessageId || history.assistantMessage.thread_id !== prepared.threadId || history.assistantMessage.role !== "assistant")
904
+ throw new Error("Delegation child history mismatch");
905
+ const digest = delegationAdmissionFingerprint(params);
906
+ if (digest !== prepared.admissionFingerprint)
907
+ throw new Error("Delegation child admission does not match its checkpoint");
908
+ if (delegationAdmissionFingerprint({ body: childExecution.body, history: childExecution.history }) !== delegationAdmissionFingerprint(prepared.admission))
909
+ throw new Error("Delegation child admission does not match its saved request");
910
+ if (execution.cancellationRequestedAt !== void 0) return { status: "cancelled" };
911
+ if (prepared.jobId) {
912
+ const previous = raw.prepare(`SELECT id, delegation_admission_digest FROM background_jobs
913
+ WHERE id = ? AND user_id = ? AND idempotency_key = ? AND delegation_parent_id = ?`).get(
914
+ prepared.jobId,
915
+ parent.user_id,
916
+ admissionKey,
917
+ parent.id
918
+ );
919
+ if (!previous || previous.delegation_admission_digest !== digest)
920
+ throw new Error("Conflicting delegation child admission");
921
+ return { status: "admitted", jobId: previous.id, replayed: true };
922
+ }
923
+ if (wait.deadlineAt <= now) return { status: "expired" };
924
+ if (wait.revision !== input.revision) return { status: "not-owned" };
925
+ const existing = raw.prepare("SELECT id FROM background_jobs WHERE idempotency_key = ?").get(admissionKey);
926
+ if (existing) throw new Error("Conflicting delegation child admission");
927
+ const cancelled = raw.prepare(`SELECT 1 AS hit FROM background_admission_cancels
928
+ WHERE user_id = ? AND admission_id = ? AND expires_at > ?`).get(parent.user_id, admissionKey, now);
929
+ if (cancelled) return { status: "cancelled" };
930
+ const active = raw.prepare(`SELECT COUNT(*) AS total,
931
+ SUM(CASE WHEN user_id = ? THEN 1 ELSE 0 END) AS user_total
932
+ FROM background_jobs WHERE status = 'streaming'
933
+ AND json_extract(execution_json, '$.clientToolCall') IS NULL
934
+ AND delegation_wait_active = 0 AND json_type(execution_json, '$.delegationWait') IS NULL`).get(parent.user_id);
935
+ if (active.total >= config.maxConcurrentJobs || (active.user_total ?? 0) >= config.maxConcurrentJobsPerUser)
936
+ return { status: "capacity" };
937
+ const admissionAt = Date.now();
938
+ if (parent.lease_expires_at <= admissionAt) return { status: "not-owned" };
939
+ if (wait.deadlineAt <= admissionAt) return { status: "expired" };
940
+ const jobId = randomUUID();
941
+ const children = wait.children.map((child, index) => index === input.childIndex ? { ...prepared, jobId } : child);
942
+ const nextWait = DelegationWaitSchema.parse({ ...wait, children, revision: wait.revision + 1 });
943
+ raw.prepare(INSERT_JOB).run(...insertParameters(jobId, params, admissionAt));
944
+ raw.prepare("UPDATE background_jobs SET delegation_admission_digest = ?, delegation_parent_id = ? WHERE id = ?").run(digest, parent.id, jobId);
945
+ raw.prepare("UPDATE background_jobs SET execution_json = ?, last_activity_at = ? WHERE id = ?").run(json({ ...execution, delegationWait: nextWait }), admissionAt, parent.id);
946
+ return { status: "admitted", jobId, replayed: false };
947
+ }).immediate();
948
+ }
949
+ async commitDelegationWait(input) {
950
+ if (isD1Driver()) throw new Error("Atomic delegation coordination is unavailable for D1");
951
+ const proposed = DelegationWaitSchema.parse(input.wait);
952
+ const raw = getRawDb();
953
+ return raw.transaction(() => {
954
+ const now = Date.now();
955
+ const parent = raw.prepare("SELECT * FROM background_jobs WHERE id = ?").get(input.parentJobId);
956
+ if (!parent || parent.lease_owner !== input.leaseOwner || !parent.lease_expires_at || parent.lease_expires_at <= now) return false;
957
+ const execution = parseJson(parent.execution_json);
958
+ const previous = DelegationWaitSchema.safeParse(execution?.delegationWait);
959
+ if (!execution || "delegationQuarantinedAt" in execution || !previous.success || !hasParkedDeadline(parent, previous.data))
960
+ throw new Error("Invalid delegation wait checkpoint");
961
+ const wait = previous.data;
962
+ if (wait.revision !== input.expectedRevision) return false;
963
+ if (proposed.revision !== wait.revision + 1 || proposed.callId !== wait.callId || proposed.argumentFingerprint !== wait.argumentFingerprint || proposed.deadlineAt !== wait.deadlineAt || proposed.expiredAt !== wait.expiredAt || proposed.children.length !== wait.children.length)
964
+ throw new Error("Invalid delegation wait transition");
965
+ for (let index = 0; index < wait.children.length; index++) {
966
+ const before = wait.children[index];
967
+ const after = proposed.children[index];
968
+ const { settlement: beforeSettlement, ...beforeIdentity } = before;
969
+ const { settlement: afterSettlement, ...afterIdentity } = after;
970
+ if (JSON.stringify(beforeIdentity) !== JSON.stringify(afterIdentity) || beforeSettlement && JSON.stringify(beforeSettlement) !== JSON.stringify(afterSettlement))
971
+ throw new Error("Invalid delegation child transition");
972
+ if (!beforeSettlement && afterSettlement && after.kind === "prepared" && after.jobId && ["complete", "failed", "stopped"].includes(afterSettlement.kind)) {
973
+ const child = raw.prepare(`SELECT status, history_phase, message_id, thread_id, content, error, execution_json FROM background_jobs
974
+ WHERE id = ? AND user_id = ? AND delegation_parent_id = ?`).get(
975
+ after.jobId,
976
+ parent.user_id,
977
+ parent.id
978
+ );
979
+ const expectedStatus = afterSettlement.kind === "complete" ? "complete" : afterSettlement.kind === "failed" ? "error" : "aborted";
980
+ if (!child || child.status !== expectedStatus || child.message_id !== after.assistantMessageId || child.thread_id !== after.threadId || afterSettlement.kind === "complete" && child.history_phase !== "committed")
981
+ throw new Error("Delegation child outcome is not confirmed");
982
+ if (afterSettlement.kind === "failed" && normalizeError(child.error).code === "ERR_MODEL_OUTCOME_UNKNOWN")
983
+ throw new Error("Delegation child outcome is uncertain");
984
+ if (afterSettlement.kind === "stopped") {
985
+ const childExecution = parseJson(child.execution_json);
986
+ if (!childExecution || childExecution.delegationDispatch !== void 0)
987
+ throw new Error("Delegation child outcome is uncertain");
988
+ }
989
+ if (afterSettlement.kind === "complete") {
990
+ const result = afterSettlement.result;
991
+ const matches = result.kind === "inline" ? result.value === child.content : matchesToolResultStorage(
992
+ result.reference,
993
+ child.content,
994
+ { threadId: parent.thread_id, parentAssistantId: parent.message_id, callId: `${wait.callId}:child:${index}` }
995
+ );
996
+ if (!matches) throw new Error("Delegation child result does not match its completed job");
997
+ }
998
+ }
999
+ }
1000
+ const committedAt = Date.now();
1001
+ if (parent.lease_expires_at <= committedAt) return false;
1002
+ return raw.prepare(`UPDATE background_jobs SET
1003
+ execution_json = json_set(execution_json, '$.delegationWait', json(?)),
1004
+ last_activity_at = ?, lease_owner = NULL, lease_expires_at = NULL
1005
+ WHERE id = ? AND status = ? AND lease_owner = ? AND lease_expires_at > ?
1006
+ AND json_extract(execution_json, '$.delegationWait.revision') = ?`).run(
1007
+ JSON.stringify(proposed),
1008
+ committedAt,
1009
+ parent.id,
1010
+ parent.status,
1011
+ input.leaseOwner,
1012
+ committedAt,
1013
+ input.expectedRevision
1014
+ ).changes > 0;
1015
+ }).immediate();
1016
+ }
1017
+ async stopInvalidDelegationWait(input) {
1018
+ if (isD1Driver()) throw new Error("Atomic delegation coordination is unavailable for D1");
1019
+ const raw = getRawDb();
1020
+ return raw.transaction(() => {
1021
+ const now = Date.now();
1022
+ const parent = raw.prepare("SELECT * FROM background_jobs WHERE id = ?").get(input.parentJobId);
1023
+ if (!parent || parent.status !== "streaming" || parent.lease_owner !== input.leaseOwner || !parent.lease_expires_at || parent.lease_expires_at <= now) return "not-owned";
1024
+ let execution;
1025
+ try {
1026
+ execution = parseJson(parent.execution_json);
1027
+ } catch {
1028
+ return "unavailable";
1029
+ }
1030
+ const parsed = DelegationWaitSchema.safeParse(execution?.delegationWait);
1031
+ if (!execution || !parsed.success || !hasParkedDeadline(parent, parsed.data) || parsed.data.revision !== input.expectedRevision) return "not-owned";
1032
+ if (parent.sync_provider_id !== "sqlite" || !execution.history || !parent.generation_id) return "unavailable";
1033
+ let admission;
1034
+ try {
1035
+ admission = parseChatGenerationAdmissionEnvelope(execution.history);
1036
+ } catch {
1037
+ return "unavailable";
1038
+ }
1039
+ if (admission.workspaceId !== execution.workspaceId || admission.threadId !== parent.thread_id || admission.messageId !== parent.message_id || admission.generationId !== parent.generation_id) return "unavailable";
1040
+ const member = raw.prepare(`SELECT m.role FROM workspace_members m JOIN workspaces w ON w.id = m.workspace_id
1041
+ WHERE m.workspace_id = ? AND m.user_id = ? AND COALESCE(w.deleted, 0) = 0`).get(execution.workspaceId, parent.user_id);
1042
+ const thread = raw.prepare("SELECT data_json, deleted FROM s_threads WHERE workspace_id = ? AND id = ?").get(execution.workspaceId, parent.thread_id);
1043
+ const message = raw.prepare("SELECT data_json, clock, deleted FROM s_messages WHERE workspace_id = ? AND id = ?").get(execution.workspaceId, parent.message_id);
1044
+ let invalid = input.authorizationDenied === true || !member || !["owner", "editor"].includes(member.role) || !thread || !!thread.deleted || !message || !!message.deleted;
1045
+ if (!invalid && thread) {
1046
+ try {
1047
+ const record = JSON.parse(thread.data_json);
1048
+ if (!record || typeof record !== "object" || record.id !== parent.thread_id) return "unavailable";
1049
+ const ownership = resolveCanonicalProjectOwnership(raw, execution.workspaceId, parent.thread_id, record.project_id);
1050
+ invalid = !!record.deleted || !!ownership.projectId;
1051
+ if (!invalid && ownership.status !== "resolved") return "unavailable";
1052
+ } catch {
1053
+ return "unavailable";
1054
+ }
1055
+ }
1056
+ if (!invalid && message) {
1057
+ try {
1058
+ const record = JSON.parse(message.data_json);
1059
+ if (!record || typeof record !== "object" || typeof record.id !== "string" || typeof record.thread_id !== "string" || !record.data || typeof record.data !== "object" || typeof record.data.generation_id !== "string") return "unavailable";
1060
+ invalid = record.id !== parent.message_id || record.thread_id !== parent.thread_id || !!record.deleted || record.data?.generation_id !== parent.generation_id || message.clock !== admission.assistantMessage.clock;
1061
+ } catch {
1062
+ return "unavailable";
1063
+ }
1064
+ }
1065
+ if (!invalid) return "valid";
1066
+ const changedAt = Date.now();
1067
+ const changed = raw.prepare(`UPDATE background_jobs SET status = 'aborted', completed_at = ?, last_activity_at = ?,
1068
+ history_phase = CASE WHEN generation_id IS NOT NULL AND COALESCE(history_phase, 'ready') = 'ready'
1069
+ THEN 'finalization_pending' ELSE history_phase END
1070
+ WHERE id = ? AND status = 'streaming' AND lease_owner = ? AND lease_expires_at > ?
1071
+ AND json_extract(execution_json, '$.delegationWait.revision') = ?`).run(changedAt, changedAt, parent.id, input.leaseOwner, changedAt, input.expectedRevision);
1072
+ return changed.changes ? "stopped" : "not-owned";
1073
+ }).immediate();
1074
+ }
1075
+ async cleanupDelegationWait(input) {
1076
+ return this.stopDelegationChildren(input, false);
1077
+ }
1078
+ async expireDelegationWait(input) {
1079
+ const result = await this.stopDelegationChildren(input, true);
1080
+ if (result === "settled") throw new Error("Unexpected terminal delegation expiry");
1081
+ return result;
1082
+ }
1083
+ async stopDelegationChildren(input, expired) {
1084
+ if (isD1Driver()) throw new Error("Atomic delegation coordination is unavailable for D1");
1085
+ const raw = getRawDb();
1086
+ const leaseLost2 = Symbol("delegation cleanup lease lost");
1087
+ try {
1088
+ return raw.transaction(() => {
1089
+ const now = Date.now();
1090
+ const parent = raw.prepare("SELECT * FROM background_jobs WHERE id = ?").get(input.parentJobId);
1091
+ if (!parent || parent.lease_owner !== input.leaseOwner || !parent.lease_expires_at || parent.lease_expires_at <= now)
1092
+ return "not-owned";
1093
+ const execution = parseJson(parent.execution_json);
1094
+ const parsed = DelegationWaitSchema.safeParse(execution?.delegationWait);
1095
+ if (!execution || "delegationQuarantinedAt" in execution || !parsed.success || !hasParkedDeadline(parent, parsed.data))
1096
+ throw new Error("Invalid delegation wait checkpoint");
1097
+ const wait = parsed.data;
1098
+ if (wait.revision !== input.expectedRevision || (expired ? parent.status !== "streaming" || execution.cancellationRequestedAt !== void 0 || wait.expiredAt !== void 0 || now < wait.deadlineAt : parent.status === "streaming" && execution.cancellationRequestedAt === void 0))
1099
+ return "not-owned";
1100
+ const linked = raw.prepare("SELECT id, user_id, thread_id, message_id FROM background_jobs WHERE delegation_parent_id = ?").all(parent.id);
1101
+ const prepared = wait.children.filter((child) => child.kind === "prepared" && child.jobId);
1102
+ if (linked.length !== prepared.length || linked.some((job) => job.user_id !== parent.user_id || !prepared.some((child) => child.kind === "prepared" && child.jobId === job.id && child.threadId === job.thread_id && child.assistantMessageId === job.message_id)))
1103
+ throw new Error("Delegation child links are inconsistent");
1104
+ raw.prepare(`UPDATE background_jobs SET status = 'aborted', completed_at = ?, last_activity_at = ?,
1105
+ lease_owner = NULL, lease_expires_at = NULL,
1106
+ history_phase = CASE WHEN generation_id IS NOT NULL AND COALESCE(history_phase, 'ready') = 'ready'
1107
+ THEN 'finalization_pending' ELSE history_phase END
1108
+ WHERE delegation_parent_id = ? AND user_id = ? AND status = 'streaming'`).run(now, now, parent.id, parent.user_id);
1109
+ const committedAt = Date.now();
1110
+ if (parent.lease_expires_at <= committedAt) throw leaseLost2;
1111
+ if (!expired && terminalProjectionSettled(raw, parent, execution, wait)) {
1112
+ const { delegationWait: _wait, delegationTerminalProjection: _projection, ...finishedExecution } = execution;
1113
+ const result = raw.prepare(`UPDATE background_jobs SET execution_json = ?, tool_calls_json = ?, delegation_wait_active = 0, delegation_wait_deadline = NULL,
1114
+ last_activity_at = ?, lease_owner = NULL, lease_expires_at = NULL
1115
+ WHERE id = ? AND status != 'streaming' AND lease_owner = ? AND lease_expires_at > ?
1116
+ AND json_extract(execution_json, '$.delegationWait.revision') = ?`).run(
1117
+ json(finishedExecution),
1118
+ parent.tool_calls_json,
1119
+ committedAt,
1120
+ parent.id,
1121
+ input.leaseOwner,
1122
+ committedAt,
1123
+ input.expectedRevision
1124
+ );
1125
+ if (!result.changes) throw leaseLost2;
1126
+ return "settled";
1127
+ }
1128
+ const receipt = !expired && parent.generation_id && raw.prepare(`SELECT outcome FROM background_generation_receipts
1129
+ WHERE workspace_id = ? AND generation_id = ? AND stage = 'finalization'`).get(execution.workspaceId, parent.generation_id);
1130
+ const parentThread = raw.prepare("SELECT deleted FROM s_threads WHERE workspace_id = ? AND id = ?").get(execution.workspaceId, parent.thread_id);
1131
+ const parentThreadUnavailable = !parentThread || !!parentThread.deleted;
1132
+ const terminalCalls = !expired && !receipt ? terminalDelegationCheckpoint(raw, parent, execution, wait, parentThreadUnavailable) : null;
1133
+ if (terminalCalls) {
1134
+ const counter = raw.prepare("SELECT value FROM server_version_counter WHERE workspace_id = ?").get(execution.workspaceId);
1135
+ const nextWait2 = DelegationWaitSchema.parse({ ...wait, nextCheckAt: committedAt + 5e3, revision: wait.revision + 1 });
1136
+ const staged = {
1137
+ ...execution,
1138
+ delegationWait: nextWait2,
1139
+ delegationTerminalProjection: {
1140
+ version: 1,
1141
+ workspaceRevision: String(counter?.value ?? 0),
1142
+ ...parentThreadUnavailable ? { parentThreadUnavailable: true } : {}
1143
+ }
1144
+ };
1145
+ const result = raw.prepare(`UPDATE background_jobs SET execution_json = ?, tool_calls_json = ?,
1146
+ last_activity_at = ?, lease_owner = NULL, lease_expires_at = NULL
1147
+ WHERE id = ? AND status != 'streaming' AND lease_owner = ? AND lease_expires_at > ?
1148
+ AND json_extract(execution_json, '$.delegationWait.revision') = ?`).run(
1149
+ json(staged),
1150
+ json(terminalCalls),
1151
+ committedAt,
1152
+ parent.id,
1153
+ input.leaseOwner,
1154
+ committedAt,
1155
+ input.expectedRevision
1156
+ );
1157
+ if (!result.changes) throw leaseLost2;
1158
+ return "pending";
1159
+ }
1160
+ const nextWait = DelegationWaitSchema.parse({
1161
+ ...wait,
1162
+ nextCheckAt: committedAt + 5e3,
1163
+ revision: wait.revision + 1,
1164
+ ...expired ? { expiredAt: committedAt, children: wait.children.map((child) => child.kind === "prepared" && !child.jobId && !child.settlement ? { ...child, settlement: { kind: "unavailable", code: "deadline_expired" } } : child) } : {}
1165
+ });
1166
+ const nextExecution = raw.prepare(`UPDATE background_jobs SET
1167
+ execution_json = json_set(execution_json, '$.delegationWait', json(?)),
1168
+ last_activity_at = ?, lease_owner = NULL, lease_expires_at = NULL
1169
+ WHERE id = ? AND lease_owner = ? AND lease_expires_at > ?
1170
+ AND json_extract(execution_json, '$.delegationWait.revision') = ?`).run(JSON.stringify(nextWait), committedAt, parent.id, input.leaseOwner, committedAt, input.expectedRevision);
1171
+ if (!nextExecution.changes) throw leaseLost2;
1172
+ return "pending";
1173
+ }).immediate();
1174
+ } catch (error) {
1175
+ if (error === leaseLost2) return "not-owned";
1176
+ throw error;
1177
+ }
1178
+ }
1179
+ async resumeDelegationWait(input) {
1180
+ if (isD1Driver()) throw new Error("Atomic delegation coordination is unavailable for D1");
1181
+ const config = getJobConfig();
1182
+ const raw = getRawDb();
1183
+ return raw.transaction(() => {
1184
+ const now = Date.now();
1185
+ const parent = raw.prepare("SELECT * FROM background_jobs WHERE id = ?").get(input.parentJobId);
1186
+ if (!parent || parent.status !== "streaming" || (parent.history_phase ?? "ready") !== "ready" || parent.lease_owner !== input.leaseOwner || !parent.lease_expires_at || parent.lease_expires_at <= now)
1187
+ return "not-owned";
1188
+ const job = toJob(parent);
1189
+ const execution = job.execution;
1190
+ const wait = DelegationWaitSchema.safeParse(execution?.delegationWait);
1191
+ if (!execution || "delegationQuarantinedAt" in execution || !wait.success || !hasParkedDeadline(parent, wait.data))
1192
+ throw new Error("Invalid delegation wait checkpoint");
1193
+ if (execution.cancellationRequestedAt !== void 0 || wait.data.revision !== input.expectedRevision || wait.data.deadlineAt <= now && wait.data.expiredAt === void 0)
1194
+ return "not-owned";
1195
+ if (parent.sync_provider_id !== "sqlite" || typeof input.expectedSyncRevision !== "string" || !/^(0|[1-9][0-9]*)$/.test(input.expectedSyncRevision)) return "not-owned";
1196
+ const access = raw.prepare(`SELECT m.role FROM workspace_members m JOIN workspaces w ON w.id = m.workspace_id
1197
+ WHERE m.workspace_id = ? AND m.user_id = ? AND COALESCE(w.deleted, 0) = 0`).get(execution.workspaceId, parent.user_id);
1198
+ const syncCounter = raw.prepare("SELECT value FROM server_version_counter WHERE workspace_id = ?").get(execution.workspaceId);
1199
+ if (!access || !["owner", "editor"].includes(access.role) || String(syncCounter?.value ?? 0) !== input.expectedSyncRevision)
1200
+ return "not-owned";
1201
+ const checkpoint = buildDelegationResume(job, input);
1202
+ const active = raw.prepare(`SELECT COUNT(*) AS total,
1203
+ SUM(CASE WHEN user_id = ? THEN 1 ELSE 0 END) AS user_total
1204
+ FROM background_jobs WHERE status = 'streaming'
1205
+ AND json_extract(execution_json, '$.clientToolCall') IS NULL
1206
+ AND delegation_wait_active = 0 AND json_type(execution_json, '$.delegationWait') IS NULL`).get(parent.user_id);
1207
+ if (active.total >= config.maxConcurrentJobs || (active.user_total ?? 0) >= config.maxConcurrentJobsPerUser)
1208
+ return "capacity";
1209
+ const resumedAt = Date.now();
1210
+ if (parent.lease_expires_at <= resumedAt || wait.data.deadlineAt <= resumedAt && wait.data.expiredAt === void 0) return "not-owned";
1211
+ const changed = raw.prepare(`UPDATE background_jobs SET execution_json = ?, tool_calls_json = ?, delegation_wait_active = 0, delegation_wait_deadline = NULL,
1212
+ lease_owner = NULL, lease_expires_at = NULL, last_activity_at = ?
1213
+ WHERE id = ? AND status = 'streaming' AND lease_owner = ? AND lease_expires_at > ?
1214
+ AND json_type(execution_json, '$.cancellationRequestedAt') IS NULL
1215
+ AND json_extract(execution_json, '$.delegationWait.revision') = ?`).run(
1216
+ json(checkpoint.execution),
1217
+ json(checkpoint.toolCalls),
1218
+ resumedAt,
1219
+ parent.id,
1220
+ input.leaseOwner,
1221
+ resumedAt,
1222
+ input.expectedRevision
1223
+ ).changes;
1224
+ return changed ? "resumed" : "not-owned";
1225
+ }).immediate();
1226
+ }
478
1227
  async renewJobLease(jobId, leaseOwner, _now, leaseExpiresAt) {
479
1228
  return await run(
480
1229
  `UPDATE background_jobs SET lease_expires_at = ?, last_activity_at = ?
481
- WHERE id = ? AND status = 'streaming' AND lease_owner = ?
1230
+ WHERE id = ? AND (status = 'streaming' OR delegation_wait_active = 1 OR json_type(execution_json, '$.delegationWait') IS NOT NULL)
1231
+ AND lease_owner = ?
482
1232
  AND lease_expires_at > ?`,
483
1233
  leaseExpiresAt,
484
1234
  Date.now(),
@@ -488,14 +1238,18 @@ export class SqliteBackgroundJobProvider {
488
1238
  ) > 0;
489
1239
  }
490
1240
  async updateJobExecution(jobId, execution, leaseOwner) {
1241
+ if (execution.delegationWait !== void 0) return false;
491
1242
  return await run(
492
1243
  `UPDATE background_jobs SET execution_json = ?, last_activity_at = ?
493
1244
  WHERE id = ? AND status = 'streaming' AND lease_owner = ?
1245
+ AND delegation_wait_active = 0 AND json_type(execution_json, '$.delegationWait') IS NULL
1246
+ AND json_extract(execution_json, '$.delegationDefaults') IS json_extract(?, '$.delegationDefaults')
494
1247
  AND lease_expires_at > ?`,
495
1248
  json(execution),
496
1249
  Date.now(),
497
1250
  jobId,
498
1251
  leaseOwner,
1252
+ json(execution),
499
1253
  Date.now()
500
1254
  ) > 0;
501
1255
  }
@@ -534,6 +1288,7 @@ export class SqliteBackgroundJobProvider {
534
1288
  WHERE id = ? AND user_id = ? AND status = 'streaming'
535
1289
  AND json_extract(execution_json, '$.clientToolCall.callId') = ?
536
1290
  AND json_extract(execution_json, '$.clientToolCall.claimToken') = ?
1291
+ AND json_extract(execution_json, '$.delegationDefaults') IS json_extract(?, '$.delegationDefaults')
537
1292
  AND COALESCE(json_extract(execution_json, '$.clientToolCall.claimExpiresAt'), 0) > ?`,
538
1293
  json(execution),
539
1294
  json(toolCalls),
@@ -542,6 +1297,7 @@ export class SqliteBackgroundJobProvider {
542
1297
  userId,
543
1298
  callId,
544
1299
  claimToken,
1300
+ json(execution),
545
1301
  now
546
1302
  ) > 0;
547
1303
  }
@@ -581,14 +1337,43 @@ export class SqliteBackgroundJobProvider {
581
1337
  where += ` AND COALESCE(history_phase, 'ready') IN (${placeholders})`;
582
1338
  values.push(...options.from);
583
1339
  }
584
- return await run(`UPDATE background_jobs SET history_phase = ? WHERE ${where}`, ...values) > 0;
1340
+ return await run(`UPDATE background_jobs SET history_phase = ?, delegation_history_retry_at = 0 WHERE ${where}`, ...values) > 0;
1341
+ }
1342
+ async deferDelegationHistory(input) {
1343
+ if (!["admission_pending", "finalization_pending"].includes(input.phase)) return false;
1344
+ return await run(
1345
+ `UPDATE background_jobs SET delegation_history_retry_at = ?
1346
+ WHERE id = ? AND user_id = ? AND generation_id = ? AND history_phase = ?
1347
+ AND json_extract(execution_json, '$.delegationRecoveryPolicy') = 'v1'`,
1348
+ Date.now() + 3e4,
1349
+ input.jobId,
1350
+ input.userId,
1351
+ input.generationId,
1352
+ input.phase
1353
+ ) > 0;
585
1354
  }
586
1355
  async getPendingHistoryJobs(limit) {
587
1356
  const rows = await all(
588
1357
  `SELECT * FROM background_jobs
589
1358
  WHERE history_phase IN ('admission_pending', 'finalization_pending')
1359
+ AND NOT EXISTS (SELECT 1 FROM background_job_execution_quarantine AS evidence
1360
+ WHERE evidence.job_id = background_jobs.id)
1361
+ AND json_type(execution_json, '$.delegationQuarantinedAt') IS NULL
1362
+ AND delegation_history_retry_at <= ?
1363
+ AND (status = 'streaming' OR history_phase = 'admission_pending'
1364
+ OR (delegation_wait_active = 0 AND json_type(execution_json, '$.delegationWait') IS NULL)
1365
+ OR (delegation_wait_active = 1 AND json_type(execution_json, '$.delegationWait') = 'object'
1366
+ AND json_type(execution_json, '$.delegationQuarantinedAt') IS NULL
1367
+ AND json_extract(execution_json, '$.delegationWait.deadlineAt') = delegation_wait_deadline
1368
+ AND json_extract(execution_json, '$.delegationTerminalProjection.version') = 1
1369
+ AND json_type(execution_json, '$.delegationTerminalProjection.workspaceRevision') = 'text'
1370
+ AND length(json_extract(execution_json, '$.delegationTerminalProjection.workspaceRevision')) BETWEEN 1 AND 16
1371
+ AND json_extract(execution_json, '$.delegationTerminalProjection.workspaceRevision') NOT GLOB '*[^0-9]*'
1372
+ AND (json_extract(execution_json, '$.delegationTerminalProjection.workspaceRevision') = '0'
1373
+ OR substr(json_extract(execution_json, '$.delegationTerminalProjection.workspaceRevision'), 1, 1) != '0')))
590
1374
  ORDER BY started_at ASC
591
1375
  LIMIT ?`,
1376
+ Date.now(),
592
1377
  Math.max(1, Math.min(100, Math.floor(limit)))
593
1378
  );
594
1379
  return rows.map(toJob);
@@ -597,20 +1382,33 @@ export class SqliteBackgroundJobProvider {
597
1382
  const config = getJobConfig();
598
1383
  const now = Date.now();
599
1384
  const timedOut = await run(
600
- `UPDATE background_jobs SET status = 'error', error = 'Job timed out',
1385
+ `UPDATE background_jobs SET status = 'error', error = CASE
1386
+ WHEN json_type(execution_json, '$.delegationDispatch') IS NOT NULL THEN ?
1387
+ ELSE 'Job timed out' END,
601
1388
  completed_at = ?, lease_owner = NULL, lease_expires_at = NULL,
602
1389
  history_phase = CASE
603
1390
  WHEN generation_id IS NOT NULL
604
1391
  AND COALESCE(history_phase, 'ready') = 'ready'
605
1392
  THEN 'finalization_pending'
606
1393
  ELSE history_phase END
607
- WHERE status = 'streaming' AND last_activity_at <= ?`,
1394
+ WHERE status = 'streaming' AND last_activity_at <= ?
1395
+ AND delegation_wait_active = 0 AND json_type(execution_json, '$.delegationWait') IS NULL`,
1396
+ serializeError(Object.assign(new Error("Model request outcome is unknown."), { code: "ERR_MODEL_OUTCOME_UNKNOWN", retryable: false }), { source: "provider" }),
608
1397
  now,
609
1398
  now - config.jobTimeoutMs
610
1399
  );
611
1400
  const removed = await run(
612
1401
  `DELETE FROM background_jobs
613
1402
  WHERE status != 'streaming' AND completed_at IS NOT NULL AND completed_at <= ?
1403
+ AND delegation_wait_active = 0 AND json_type(execution_json, '$.delegationWait') IS NULL
1404
+ AND (delegation_parent_id IS NULL OR NOT EXISTS (
1405
+ SELECT 1 FROM background_jobs AS parent
1406
+ WHERE parent.id = background_jobs.delegation_parent_id
1407
+ AND (parent.status = 'streaming'
1408
+ OR COALESCE(parent.history_phase, '') NOT IN ('committed', 'superseded')
1409
+ OR parent.delegation_wait_active = 1
1410
+ OR json_type(parent.execution_json, '$.delegationWait') IS NOT NULL)
1411
+ ))
614
1412
  AND (
615
1413
  history_phase IS NULL
616
1414
  OR history_phase IN ('ready', 'committed', 'superseded')
@@ -622,7 +1420,8 @@ export class SqliteBackgroundJobProvider {
622
1420
  async getActiveJobCount() {
623
1421
  const row = await one(
624
1422
  `SELECT COUNT(*) AS total FROM background_jobs WHERE status = 'streaming'
625
- AND json_extract(execution_json, '$.clientToolCall') IS NULL`
1423
+ AND json_extract(execution_json, '$.clientToolCall') IS NULL
1424
+ AND delegation_wait_active = 0 AND json_type(execution_json, '$.delegationWait') IS NULL`
626
1425
  );
627
1426
  return row?.total ?? 0;
628
1427
  }
@@ -631,8 +1430,10 @@ export class SqliteBackgroundJobProvider {
631
1430
  `SELECT
632
1431
  (SELECT COUNT(*) FROM background_jobs WHERE status = 'streaming') +
633
1432
  (SELECT COUNT(*) FROM background_jobs
634
- WHERE history_phase IN ('admission_pending', 'finalization_pending')
635
- AND status != 'streaming') AS total`
1433
+ WHERE status != 'streaming' AND (
1434
+ history_phase IN ('admission_pending', 'finalization_pending')
1435
+ OR delegation_wait_active = 1 OR json_type(execution_json, '$.delegationWait') IS NOT NULL
1436
+ )) AS total`
636
1437
  );
637
1438
  if (!row) throw new Error("SQLite shutdown accounting unavailable");
638
1439
  return row.total;