@tangle-network/agent-app 0.60.248 → 0.60.249

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.
@@ -9,10 +9,10 @@ import "../chunk-Y6PRDUFJ.js";
9
9
  import "../chunk-GEYACSFW.js";
10
10
  import {
11
11
  ChatComposer
12
- } from "../chunk-WCXHXCER.js";
12
+ } from "../chunk-63QAQP7I.js";
13
13
  import "../chunk-L7MB2LLM.js";
14
14
  import "../chunk-ZDPUC6CM.js";
15
- import "../chunk-OXUBZ5SE.js";
15
+ import "../chunk-2HQP2CTA.js";
16
16
  import "../chunk-E4AY62T2.js";
17
17
  import "../chunk-SJWIZT7B.js";
18
18
  import "../chunk-OQE6WMDP.js";
@@ -1,9 +1,9 @@
1
1
  import {
2
2
  ComposerModeControls,
3
3
  EntryComposer
4
- } from "../chunk-WCXHXCER.js";
4
+ } from "../chunk-63QAQP7I.js";
5
5
  import "../chunk-L7MB2LLM.js";
6
- import "../chunk-OXUBZ5SE.js";
6
+ import "../chunk-2HQP2CTA.js";
7
7
  import "../chunk-SJWIZT7B.js";
8
8
  import "../chunk-G4F2NWZH.js";
9
9
  import "../chunk-FUZETA6Z.js";
@@ -43,7 +43,7 @@ import {
43
43
  flattenHistory,
44
44
  readSandboxBinaryBytes,
45
45
  statSandboxFileSize
46
- } from "../chunk-CFGBGIRK.js";
46
+ } from "../chunk-5Y7Z5G3Y.js";
47
47
  import "../chunk-4LBCTFBP.js";
48
48
  import {
49
49
  ModelFailoverExhaustedError,
@@ -1,6 +1,7 @@
1
1
  // src/web-react/workspace-prewarm.ts
2
2
  import { createContext, useCallback, useContext, useEffect } from "react";
3
3
  var DEFAULT_MIN_INTERVAL_MS = 6e4;
4
+ var DEFAULT_HEARTBEAT_MS = 24e4;
4
5
  var lastSent = /* @__PURE__ */ new Map();
5
6
  var inFlight = /* @__PURE__ */ new Set();
6
7
  function documentIsVisible() {
@@ -9,22 +10,25 @@ function documentIsVisible() {
9
10
  return document.visibilityState === "visible";
10
11
  }
11
12
  function requestWorkspacePrewarm(url, options = {}) {
12
- if (!url || !documentIsVisible() || inFlight.has(url)) return false;
13
+ const reason = options.reason ?? "page-open";
14
+ const slot = `${reason} ${options.threadId ?? ""} ${url}`;
15
+ if (!url || !documentIsVisible() || inFlight.has(slot)) return false;
13
16
  const now = Date.now();
14
- const last = lastSent.get(url);
17
+ const last = lastSent.get(slot);
15
18
  if (last !== void 0 && now - last < (options.minIntervalMs ?? DEFAULT_MIN_INTERVAL_MS)) return false;
16
- lastSent.set(url, now);
17
- inFlight.add(url);
19
+ lastSent.set(slot, now);
20
+ inFlight.add(slot);
18
21
  void fetch(url, {
19
22
  method: "POST",
20
23
  credentials: "same-origin",
21
24
  headers: { "content-type": "application/json" },
22
- body: JSON.stringify({ reason: options.reason ?? "page-open" })
23
- }).then((response) => response.body?.cancel()).catch(() => void 0).finally(() => inFlight.delete(url));
25
+ body: JSON.stringify({ reason, ...options.threadId ? { threadId: options.threadId } : {} })
26
+ }).then((response) => response.body?.cancel()).catch(() => void 0).finally(() => inFlight.delete(slot));
24
27
  return true;
25
28
  }
26
29
  function useWorkspacePrewarm(options) {
27
- const { url, enabled = true, minIntervalMs } = options;
30
+ const { url, enabled = true, minIntervalMs, threadId } = options;
31
+ const heartbeatMs = options.heartbeatMs ?? DEFAULT_HEARTBEAT_MS;
28
32
  const active = enabled && Boolean(url);
29
33
  useEffect(() => {
30
34
  if (!active || !url || typeof document === "undefined") return;
@@ -33,11 +37,28 @@ function useWorkspacePrewarm(options) {
33
37
  };
34
38
  fire();
35
39
  document.addEventListener("visibilitychange", fire);
36
- return () => document.removeEventListener("visibilitychange", fire);
37
- }, [active, url, minIntervalMs]);
40
+ let activeSinceBeat = false;
41
+ const touched = () => {
42
+ activeSinceBeat = true;
43
+ };
44
+ const activity = ["keydown", "pointerdown", "wheel"];
45
+ const beat = heartbeatMs > 0 ? setInterval(() => {
46
+ if (!activeSinceBeat) return;
47
+ activeSinceBeat = false;
48
+ requestWorkspacePrewarm(url, { minIntervalMs: heartbeatMs / 2, reason: "heartbeat" });
49
+ }, heartbeatMs) : void 0;
50
+ if (beat) for (const type of activity) document.addEventListener(type, touched, { passive: true });
51
+ return () => {
52
+ document.removeEventListener("visibilitychange", fire);
53
+ if (beat) {
54
+ clearInterval(beat);
55
+ for (const type of activity) document.removeEventListener(type, touched);
56
+ }
57
+ };
58
+ }, [active, url, minIntervalMs, heartbeatMs]);
38
59
  const reassert = useCallback(() => {
39
- if (active && url) requestWorkspacePrewarm(url, { minIntervalMs, reason: "composer-focus" });
40
- }, [active, url, minIntervalMs]);
60
+ if (active && url) requestWorkspacePrewarm(url, { minIntervalMs, reason: "composer-focus", ...threadId ? { threadId } : {} });
61
+ }, [active, url, minIntervalMs, threadId]);
41
62
  return { reassert };
42
63
  }
43
64
  var WorkspacePrewarmContext = createContext(null);
@@ -51,4 +72,4 @@ export {
51
72
  WorkspacePrewarmContext,
52
73
  useWorkspacePrewarmHandle
53
74
  };
54
- //# sourceMappingURL=chunk-OXUBZ5SE.js.map
75
+ //# sourceMappingURL=chunk-2HQP2CTA.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/web-react/workspace-prewarm.ts"],"sourcesContent":["/**\n * Prewarm on open: when a member opens a workspace page, ask the product to\n * warm that workspace (resume its box, prepare its profile) so the first turn\n * does not pay for it. The server half is `createWorkspacePrewarmRoute` in\n * `/sandbox`.\n *\n * Fires only from a visible, non-prerendered document. A tab opened in the\n * background fires when it first becomes visible. Requests for the same URL\n * and reason are spaced by `minIntervalMs` across every mount in the tab, so\n * navigating between pages of one workspace sends one request, not one per\n * page. Call `reassert()` on composer focus: a box can suspend while a tab sits\n * open, and focus warms the thread itself. While the tab stays visible it sends\n * a `heartbeat` every `heartbeatMs`, so what is warm stays warm; the route's\n * receipts make a heartbeat over warm state cost one read.\n *\n * Failures are silent by design. A warm is an optimization; the turn itself\n * still places the box, so nothing here may surface to the member.\n */\n\nimport { createContext, useCallback, useContext, useEffect } from 'react'\n\nexport interface WorkspacePrewarmRequestOptions {\n /** Minimum gap between requests for the same URL in this tab. Default 60 000 ms. */\n minIntervalMs?: number\n /** Sent to the route so a product can budget page opens apart from composer focus. Default `page-open`. */\n reason?: 'page-open' | 'composer-focus' | 'heartbeat'\n /** The thread the composer belongs to, so composer focus can warm that thread. */\n threadId?: string\n}\n\nexport interface UseWorkspacePrewarmOptions extends WorkspacePrewarmRequestOptions {\n /** The product's prewarm route for this workspace. Empty disables. */\n url: string | null | undefined\n /** False until the member is known to be signed in and allowed to chat. Default true. */\n enabled?: boolean\n /** Re-warm this often while the tab is visible and the member has used the page since the last beat (a key,\n * pointer or scroll), so an idle tab lets the box park. Default 240 000 ms; 0 disables. */\n heartbeatMs?: number\n}\n\nexport interface WorkspacePrewarmHandle {\n /** Ask again, subject to the same visibility and spacing rules. */\n reassert(): void\n}\n\nconst DEFAULT_MIN_INTERVAL_MS = 60_000\nconst DEFAULT_HEARTBEAT_MS = 240_000\nconst lastSent = new Map<string, number>()\nconst inFlight = new Set<string>()\n\nfunction documentIsVisible(): boolean {\n if (typeof document === 'undefined') return false\n if ((document as Document & { prerendering?: boolean }).prerendering) return false\n return document.visibilityState === 'visible'\n}\n\n/**\n * Send one prewarm request for `url` unless the tab is hidden, a request for it\n * is in flight, or one was sent within `minIntervalMs`. Returns whether it sent.\n */\nexport function requestWorkspacePrewarm(url: string, options: WorkspacePrewarmRequestOptions = {}): boolean {\n const reason = options.reason ?? 'page-open'\n // Page open, composer focus and heartbeat warm different things, so each is spaced on its own.\n const slot = `${reason} ${options.threadId ?? ''} ${url}`\n if (!url || !documentIsVisible() || inFlight.has(slot)) return false\n const now = Date.now()\n const last = lastSent.get(slot)\n if (last !== undefined && now - last < (options.minIntervalMs ?? DEFAULT_MIN_INTERVAL_MS)) return false\n lastSent.set(slot, now)\n inFlight.add(slot)\n void fetch(url, {\n method: 'POST',\n credentials: 'same-origin',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ reason, ...(options.threadId ? { threadId: options.threadId } : {}) }),\n })\n .then((response) => response.body?.cancel())\n .catch(() => undefined)\n .finally(() => inFlight.delete(slot))\n return true\n}\n\n/** Prewarm `url` when the page opens or becomes visible; `reassert` on composer focus. */\nexport function useWorkspacePrewarm(options: UseWorkspacePrewarmOptions): WorkspacePrewarmHandle {\n const { url, enabled = true, minIntervalMs, threadId } = options\n const heartbeatMs = options.heartbeatMs ?? DEFAULT_HEARTBEAT_MS\n const active = enabled && Boolean(url)\n\n useEffect(() => {\n if (!active || !url || typeof document === 'undefined') return\n const fire = () => {\n requestWorkspacePrewarm(url, { minIntervalMs })\n }\n fire()\n document.addEventListener('visibilitychange', fire)\n // Beat only for a member using the page: a hidden tab skips (requestWorkspacePrewarm checks visibility) and an\n // untouched one stops, so an open tab left overnight does not keep a box awake. Their return fires page-open.\n let activeSinceBeat = false\n const touched = () => { activeSinceBeat = true }\n const activity = ['keydown', 'pointerdown', 'wheel'] as const\n const beat = heartbeatMs > 0\n ? setInterval(() => {\n if (!activeSinceBeat) return\n activeSinceBeat = false\n requestWorkspacePrewarm(url, { minIntervalMs: heartbeatMs / 2, reason: 'heartbeat' })\n }, heartbeatMs)\n : undefined\n if (beat) for (const type of activity) document.addEventListener(type, touched, { passive: true })\n return () => {\n document.removeEventListener('visibilitychange', fire)\n if (beat) {\n clearInterval(beat)\n for (const type of activity) document.removeEventListener(type, touched)\n }\n }\n }, [active, url, minIntervalMs, heartbeatMs])\n\n const reassert = useCallback(() => {\n if (active && url) requestWorkspacePrewarm(url, { minIntervalMs, reason: 'composer-focus', ...(threadId ? { threadId } : {}) })\n }, [active, url, minIntervalMs, threadId])\n\n return { reassert }\n}\n\n/**\n * The prewarm handle of the workspace shell around this component. `AgentWorkspaceLayout` provides it when the\n * product passes `prewarm`; `ChatComposer` reasserts through it on focus unless the product passes its own\n * `onFocusWithin`. Outside a shell that warms, `reassert` does nothing.\n */\nexport const WorkspacePrewarmContext = createContext<WorkspacePrewarmHand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
29
  trimOrNull
30
30
  } from "./chunk-D6UJEOZQ.js";
31
+ import {
32
+ formatServerTiming
33
+ } from "./chunk-ORQD4AUO.js";
31
34
 
32
35
  // src/sandbox/prompt-trace.ts
33
36
  var asRec = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
@@ -856,6 +859,70 @@ WHERE key = ?1 AND expires_at = ?2`;
856
859
  };
857
860
  }
858
861
 
862
+ // src/sandbox/warm-receipts.ts
863
+ function warmReceiptId(step, key) {
864
+ return `${step}:${key}`;
865
+ }
866
+ async function warmKey(parts) {
867
+ const missing = Object.keys(parts).filter((name) => parts[name] === void 0);
868
+ if (missing.length) throw new Error(`warmKey: ${missing.join(", ")} undefined`);
869
+ const canonical = JSON.stringify(Object.keys(parts).sort().map((name) => [name, parts[name]]));
870
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(canonical));
871
+ return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
872
+ }
873
+ function createMemoryWarmReceiptStore(options = {}) {
874
+ const limit = options.limit ?? 1e3;
875
+ const receipts = /* @__PURE__ */ new Map();
876
+ return {
877
+ async get(id) {
878
+ return receipts.get(id) ?? null;
879
+ },
880
+ async put(id, receipt) {
881
+ receipts.delete(id);
882
+ receipts.set(id, receipt);
883
+ for (const old of receipts.keys()) {
884
+ if (receipts.size <= limit) break;
885
+ receipts.delete(old);
886
+ }
887
+ }
888
+ };
889
+ }
890
+ var DEFAULT_WARM_RECEIPT_TABLE = "warm_receipts";
891
+ var WARM_RECEIPT_TABLE_DDL = `CREATE TABLE IF NOT EXISTS ${DEFAULT_WARM_RECEIPT_TABLE} (
892
+ id TEXT PRIMARY KEY,
893
+ at INTEGER NOT NULL,
894
+ expires_at INTEGER NOT NULL,
895
+ report TEXT
896
+ );
897
+ CREATE INDEX IF NOT EXISTS ${DEFAULT_WARM_RECEIPT_TABLE}_by_expiry ON ${DEFAULT_WARM_RECEIPT_TABLE} (expires_at)`;
898
+ var PRUNE_EVERY_WRITES = 64;
899
+ var SAFE_IDENTIFIER2 = /^[A-Za-z_][A-Za-z0-9_]*$/;
900
+ function createD1WarmReceiptStore(db, options = {}) {
901
+ const table = options.table ?? DEFAULT_WARM_RECEIPT_TABLE;
902
+ if (!SAFE_IDENTIFIER2.test(table)) throw new Error(`Invalid warm receipt table name: ${JSON.stringify(table)}`);
903
+ const getSql = `SELECT at, expires_at, report FROM ${table} WHERE id = ?1`;
904
+ const putSql = `INSERT INTO ${table} (id, at, expires_at, report) VALUES (?1, ?2, ?3, ?4)
905
+ ON CONFLICT(id) DO UPDATE SET at = ?2, expires_at = ?3, report = ?4`;
906
+ const pruneSql = `DELETE FROM ${table} WHERE expires_at < ?1`;
907
+ const now = options.now ?? (() => Date.now());
908
+ let writes = 0;
909
+ return {
910
+ async get(id) {
911
+ const row = await db.prepare(getSql).bind(id).first();
912
+ if (!row) return null;
913
+ return {
914
+ at: row.at,
915
+ expiresAt: row.expires_at,
916
+ ...row.report ? { report: JSON.parse(row.report) } : {}
917
+ };
918
+ },
919
+ async put(id, receipt) {
920
+ await db.prepare(putSql).bind(id, receipt.at, receipt.expiresAt, receipt.report ? JSON.stringify(receipt.report) : null).run();
921
+ if (++writes % PRUNE_EVERY_WRITES === 0) await db.prepare(pruneSql).bind(now()).run();
922
+ }
923
+ };
924
+ }
925
+
859
926
  // src/sandbox/prewarm-route.ts
860
927
  var AUTOMATED_AGENT = /bot\b|crawler|spider|slurp|facebookexternalhit|embedly|preview|whatsapp|curl\/|wget\/|python-requests|go-http-client/i;
861
928
  function isAutomatedPrewarmRequest(request) {
@@ -864,17 +931,25 @@ function isAutomatedPrewarmRequest(request) {
864
931
  return AUTOMATED_AGENT.test(request.headers.get("user-agent") ?? "");
865
932
  }
866
933
  var RECENT_LIMIT = 1e3;
867
- async function requestReason(request) {
868
- if (Number(request.headers.get("content-length") ?? 0) > 1024) return "page-open";
934
+ var REASONS = ["page-open", "composer-focus", "heartbeat"];
935
+ var THREAD_ID = /^[A-Za-z0-9_:.-]{1,128}$/;
936
+ async function requestIntent(request) {
937
+ if (Number(request.headers.get("content-length") ?? 0) > 1024) return { reason: "page-open" };
869
938
  try {
870
939
  const body = await request.clone().json();
871
- return body?.reason === "composer-focus" ? "composer-focus" : "page-open";
940
+ const reason = REASONS.find((known) => known === body?.reason) ?? "page-open";
941
+ const threadId = typeof body?.threadId === "string" && THREAD_ID.test(body.threadId) ? body.threadId : void 0;
942
+ return { reason, ...threadId ? { threadId } : {} };
872
943
  } catch {
873
- return "page-open";
944
+ return { reason: "page-open" };
874
945
  }
875
946
  }
876
947
  function reply(body, status = 200) {
877
- return Response.json(body, { status, headers: { "Cache-Control": "private, no-store" } });
948
+ const headers = { "Cache-Control": "private, no-store" };
949
+ if (body.steps?.length) {
950
+ headers["Server-Timing"] = formatServerTiming(body.steps.map((step) => ({ name: `warm.${step.name}`, durMs: step.ms, desc: step.outcome })));
951
+ }
952
+ return Response.json(body, { status, headers });
878
953
  }
879
954
  function createWorkspacePrewarmRoute(options) {
880
955
  const recentMs = options.recentMs ?? 3e4;
@@ -882,18 +957,20 @@ function createWorkspacePrewarmRoute(options) {
882
957
  const staleMs = options.staleMs ?? 45e3;
883
958
  const inFlight = /* @__PURE__ */ new Map();
884
959
  const recent = /* @__PURE__ */ new Map();
960
+ const warmUntil = /* @__PURE__ */ new Map();
961
+ const stepsInFlight = /* @__PURE__ */ new Map();
885
962
  const emit = (event) => {
886
963
  try {
887
964
  options.onEvent?.(event);
888
965
  } catch {
889
966
  }
890
967
  };
891
- const remember = (key, at) => {
892
- recent.delete(key);
893
- recent.set(key, at);
894
- for (const old of recent.keys()) {
895
- if (recent.size <= RECENT_LIMIT) break;
896
- recent.delete(old);
968
+ const remember = (key, at, into = recent) => {
969
+ into.delete(key);
970
+ into.set(key, at);
971
+ for (const old of into.keys()) {
972
+ if (into.size <= RECENT_LIMIT) break;
973
+ into.delete(old);
897
974
  }
898
975
  };
899
976
  async function run(key, warm) {
@@ -910,6 +987,51 @@ function createWorkspacePrewarmRoute(options) {
910
987
  return { outcome: "failed", ms };
911
988
  }
912
989
  }
990
+ async function runStep(step) {
991
+ const started = now();
992
+ const id = warmReceiptId(step.name, step.key);
993
+ const result = (outcome, error) => {
994
+ const ms = now() - started;
995
+ emit({ type: "step", name: step.name, key: step.key, outcome, ms, ...error ? { error } : {} });
996
+ return { name: step.name, outcome, ms };
997
+ };
998
+ const local = warmUntil.get(id);
999
+ if (local !== void 0 && now() < local) return result("hit");
1000
+ const running = stepsInFlight.get(id);
1001
+ if (running && now() - running.at < staleMs) return result("joined");
1002
+ const mark = { at: now() };
1003
+ stepsInFlight.set(id, mark);
1004
+ try {
1005
+ if (options.receipts) {
1006
+ try {
1007
+ const stored = await options.receipts.get(id);
1008
+ if (stored && now() < stored.expiresAt) {
1009
+ remember(id, stored.expiresAt, warmUntil);
1010
+ return result("hit");
1011
+ }
1012
+ } catch (err) {
1013
+ emit({ type: "failed", key: id, ms: now() - started, error: err instanceof Error ? err.message : String(err) });
1014
+ }
1015
+ }
1016
+ let report;
1017
+ try {
1018
+ report = await step.run() ?? void 0;
1019
+ } catch (err) {
1020
+ return result("failed", err instanceof Error ? err.message : String(err));
1021
+ }
1022
+ const at = now();
1023
+ const expiresAt = at + step.ttlMs;
1024
+ remember(id, expiresAt, warmUntil);
1025
+ if (options.receipts) {
1026
+ await options.receipts.put(id, { at, expiresAt, ...report ? { report } : {} }).catch((err) => {
1027
+ emit({ type: "failed", key: id, ms: now() - started, error: err instanceof Error ? err.message : String(err) });
1028
+ });
1029
+ }
1030
+ return result("miss");
1031
+ } finally {
1032
+ if (stepsInFlight.get(id) === mark) stepsInFlight.delete(id);
1033
+ }
1034
+ }
913
1035
  return async function prewarm(request, context) {
914
1036
  const started = now();
915
1037
  if (request.method !== "POST") {
@@ -918,13 +1040,18 @@ function createWorkspacePrewarmRoute(options) {
918
1040
  if (isAutomatedPrewarmRequest(request)) return reply({ outcome: "automated", ms: 0 });
919
1041
  let auth;
920
1042
  try {
921
- auth = await options.authorize({ request, context, reason: await requestReason(request) });
1043
+ auth = await options.authorize({ request, context, ...await requestIntent(request) });
922
1044
  } catch (err) {
923
1045
  emit({ type: "failed", key: "", ms: now() - started, error: err instanceof Error ? err.message : String(err) });
924
1046
  return reply({ outcome: "failed", ms: now() - started });
925
1047
  }
926
1048
  if (auth.status === "denied") return auth.response;
927
1049
  if (auth.status === "declined") return reply({ outcome: "declined", ms: now() - started, reason: auth.reason });
1050
+ if ("steps" in auth) {
1051
+ const steps = await Promise.all(auth.steps.map((step) => runStep(step)));
1052
+ const outcome = steps.some((step) => step.outcome === "failed") ? "failed" : steps.some((step) => step.outcome === "miss") ? "warmed" : steps.some((step) => step.outcome === "joined") ? "joined" : "recent";
1053
+ return reply({ outcome, ms: now() - started, steps });
1054
+ }
928
1055
  const { key } = auth;
929
1056
  const running = inFlight.get(key);
930
1057
  if (running && now() - running.at < staleMs) {
@@ -1307,7 +1434,7 @@ var WARM_LEASE_PENDING_DDL = [
1307
1434
  `ALTER TABLE ${DEFAULT_WARM_LEASE_TABLE} ADD COLUMN pending_ms INTEGER NOT NULL DEFAULT 0`,
1308
1435
  `ALTER TABLE ${DEFAULT_WARM_LEASE_TABLE} ADD COLUMN pending_reason TEXT`
1309
1436
  ];
1310
- var SAFE_IDENTIFIER2 = /^[A-Za-z_][A-Za-z0-9_]*$/;
1437
+ var SAFE_IDENTIFIER3 = /^[A-Za-z_][A-Za-z0-9_]*$/;
1311
1438
  function parseSlots(text) {
1312
1439
  if (!text) return [];
1313
1440
  try {
@@ -1344,7 +1471,7 @@ function toRow(row) {
1344
1471
  }
1345
1472
  function createD1WarmLeaseStore(db, options = {}) {
1346
1473
  const t = options.table ?? DEFAULT_WARM_LEASE_TABLE;
1347
- if (!SAFE_IDENTIFIER2.test(t)) throw new Error(`Invalid warm lease table name: ${JSON.stringify(t)}`);
1474
+ if (!SAFE_IDENTIFIER3.test(t)) throw new Error(`Invalid warm lease table name: ${JSON.stringify(t)}`);
1348
1475
  const free = `(${t}.lease_id IS NULL OR (${t}.warm_at = 0 AND ${t}.started_at <= ?6))`;
1349
1476
  const beginSql = `INSERT INTO ${t} (key, lease_id, reason, started_at, hold_until) VALUES (?1, ?2, ?3, ?4, ?5)
1350
1477
  ON CONFLICT(key) DO UPDATE SET
@@ -3774,6 +3901,12 @@ export {
3774
3901
  DEFAULT_PREWARM_CLAIM_TABLE,
3775
3902
  PREWARM_CLAIM_TABLE_DDL,
3776
3903
  createD1PrewarmClaimStore,
3904
+ warmReceiptId,
3905
+ warmKey,
3906
+ createMemoryWarmReceiptStore,
3907
+ DEFAULT_WARM_RECEIPT_TABLE,
3908
+ WARM_RECEIPT_TABLE_DDL,
3909
+ createD1WarmReceiptStore,
3777
3910
  isAutomatedPrewarmRequest,
3778
3911
  createWorkspacePrewarmRoute,
3779
3912
  DEFAULT_FOREGROUND_PROVISION_CLAIM_TTL_SECONDS,
@@ -3853,4 +3986,4 @@ export {
3853
3986
  deleteSecret,
3854
3987
  mintSandboxScopedToken
3855
3988
  };
3856
- //# sourceMappingURL=chunk-CFGBGIRK.js.map
3989
+ //# sourceMappingURL=chunk-5Y7Z5G3Y.js.map