@tangle-network/agent-app 0.60.248 → 0.60.250
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assistant/index.js +2 -2
- package/dist/chat-react/index.js +2 -2
- package/dist/chat-routes/dispatch-first.d.ts +43 -0
- package/dist/chat-routes/index.js +2 -2
- package/dist/chat-routes/turn-execution.d.ts +3 -1
- package/dist/chat-routes/turn-route-contracts.d.ts +31 -0
- package/dist/{chunk-OXUBZ5SE.js → chunk-2HQP2CTA.js} +33 -12
- package/dist/chunk-2HQP2CTA.js.map +1 -0
- package/dist/{chunk-CFGBGIRK.js → chunk-5Y7Z5G3Y.js} +148 -15
- package/dist/chunk-5Y7Z5G3Y.js.map +1 -0
- package/dist/{chunk-WCXHXCER.js → chunk-63QAQP7I.js} +2 -2
- package/dist/{chunk-BDCC6UVW.js → chunk-A3KPDLSF.js} +144 -23
- package/dist/chunk-A3KPDLSF.js.map +1 -0
- package/dist/public-consultation/index.d.ts +1 -1
- package/dist/public-consultation/index.js +1 -1
- package/dist/sandbox/index.d.ts +1 -0
- package/dist/sandbox/index.js +13 -1
- package/dist/sandbox/prewarm-route.d.ts +41 -35
- package/dist/sandbox/warm-receipts.d.ts +67 -0
- package/dist/web-react/index.js +2 -2
- package/dist/web-react/workspace-prewarm.d.ts +12 -4
- package/dist/workspace-react/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-BDCC6UVW.js.map +0 -1
- package/dist/chunk-CFGBGIRK.js.map +0 -1
- package/dist/chunk-OXUBZ5SE.js.map +0 -1
- /package/dist/{chunk-WCXHXCER.js.map → chunk-63QAQP7I.js.map} +0 -0
package/dist/assistant/index.js
CHANGED
|
@@ -9,10 +9,10 @@ import "../chunk-Y6PRDUFJ.js";
|
|
|
9
9
|
import "../chunk-GEYACSFW.js";
|
|
10
10
|
import {
|
|
11
11
|
ChatComposer
|
|
12
|
-
} from "../chunk-
|
|
12
|
+
} from "../chunk-63QAQP7I.js";
|
|
13
13
|
import "../chunk-L7MB2LLM.js";
|
|
14
14
|
import "../chunk-ZDPUC6CM.js";
|
|
15
|
-
import "../chunk-
|
|
15
|
+
import "../chunk-2HQP2CTA.js";
|
|
16
16
|
import "../chunk-E4AY62T2.js";
|
|
17
17
|
import "../chunk-SJWIZT7B.js";
|
|
18
18
|
import "../chunk-OQE6WMDP.js";
|
package/dist/chat-react/index.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import {
|
|
2
2
|
ComposerModeControls,
|
|
3
3
|
EntryComposer
|
|
4
|
-
} from "../chunk-
|
|
4
|
+
} from "../chunk-63QAQP7I.js";
|
|
5
5
|
import "../chunk-L7MB2LLM.js";
|
|
6
|
-
import "../chunk-
|
|
6
|
+
import "../chunk-2HQP2CTA.js";
|
|
7
7
|
import "../chunk-SJWIZT7B.js";
|
|
8
8
|
import "../chunk-G4F2NWZH.js";
|
|
9
9
|
import "../chunk-FUZETA6Z.js";
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Dispatch-first admission: start the producer, and so the model call, as soon
|
|
3
|
+
* as the turn's identity is known, while the lock, the history recheck, the
|
|
4
|
+
* user-row insert, `contextGate` and `beforeTurn` run. Nothing the producer
|
|
5
|
+
* emits reaches the member, the turn buffer or the transcript until that chain
|
|
6
|
+
* commits; a refusal aborts the producer and drops what it emitted.
|
|
7
|
+
*
|
|
8
|
+
* Why: on Creative production (2026-10-21, gemini-3.7-flash, n=32 Router
|
|
9
|
+
* turns) the chain between `authorize` and the producer held about 780 ms of
|
|
10
|
+
* every turn's p50 (admission 343, profile pin 338, turn open 99) before the
|
|
11
|
+
* model was even called. The model's own first token takes 2.5-3.6 s, so that
|
|
12
|
+
* work fits inside it.
|
|
13
|
+
*
|
|
14
|
+
* What stays fail-closed: `authorize` has already run, so no model call starts
|
|
15
|
+
* for a caller without identity and workspace access. Billing is enforced in
|
|
16
|
+
* `authorize` or at the model service, which holds spend before it calls the
|
|
17
|
+
* provider; the product names which (`dispatchFirst: { billing }`). Gates the
|
|
18
|
+
* model service cannot know, such as a seat, run in `contextGate` beside the
|
|
19
|
+
* model call, and the output waits for them. Single-flight is unchanged: the lock still decides which turn's output is
|
|
20
|
+
* kept; a refused duplicate costs only the model call it started, which its
|
|
21
|
+
* `admissionSignal` cancels.
|
|
22
|
+
*/
|
|
23
|
+
import type { TurnTrace } from '../turn-trace/recorder';
|
|
24
|
+
import type { ChatTurnProduceArgs, ChatTurnRouteProducer, CreateChatTurnRoutesOptions } from './turn-route-contracts';
|
|
25
|
+
/** Thrown into `args.admitted` when the turn was refused after its producer started. */
|
|
26
|
+
export declare class TurnAdmissionRefusedError extends Error {
|
|
27
|
+
constructor();
|
|
28
|
+
}
|
|
29
|
+
export interface DispatchedProducer<TContext> {
|
|
30
|
+
/** The admission chain committed: hand the producer its final args and return it, with what it already emitted first. */
|
|
31
|
+
take(args: ChatTurnProduceArgs<TContext>): Promise<ChatTurnRouteProducer>;
|
|
32
|
+
/** The turn ended without the producer: abort it and discard its output. Idempotent; a no-op after `take`. */
|
|
33
|
+
refuse(): void;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Start `produce` now with the args known before the lock. `args.admitted`
|
|
37
|
+
* resolves to the final args at `take`, or rejects at `refuse`; the producer
|
|
38
|
+
* writes nothing durable before it resolves. Its stream is drained into memory
|
|
39
|
+
* from the start, so a producer that only works while pulled still dispatches.
|
|
40
|
+
*/
|
|
41
|
+
export declare function dispatchProducerFirst<TContext>(produce: (args: ChatTurnProduceArgs<TContext>) => ChatTurnRouteProducer | Promise<ChatTurnRouteProducer>, args: ChatTurnProduceArgs<TContext>, trace: TurnTrace): DispatchedProducer<TContext>;
|
|
42
|
+
/** The dispatched producer for this turn when the route dispatches first and `when` picks it; otherwise none. */
|
|
43
|
+
export declare function dispatchFirstFor<TContext>(options: CreateChatTurnRoutesOptions<TContext>, args: ChatTurnProduceArgs<TContext>, trace: TurnTrace): DispatchedProducer<TContext> | undefined;
|
|
@@ -43,7 +43,7 @@ import {
|
|
|
43
43
|
flattenHistory,
|
|
44
44
|
readSandboxBinaryBytes,
|
|
45
45
|
statSandboxFileSize
|
|
46
|
-
} from "../chunk-
|
|
46
|
+
} from "../chunk-5Y7Z5G3Y.js";
|
|
47
47
|
import "../chunk-4LBCTFBP.js";
|
|
48
48
|
import {
|
|
49
49
|
ModelFailoverExhaustedError,
|
|
@@ -83,7 +83,7 @@ import {
|
|
|
83
83
|
rowIdOf,
|
|
84
84
|
storeSupportsDraftPersistence,
|
|
85
85
|
streamChatRouteAsSandboxEvents
|
|
86
|
-
} from "../chunk-
|
|
86
|
+
} from "../chunk-A3KPDLSF.js";
|
|
87
87
|
import "../chunk-TCGZFSN5.js";
|
|
88
88
|
import "../chunk-FENBDSIW.js";
|
|
89
89
|
import "../chunk-RN4WPTBH.js";
|
|
@@ -3,10 +3,12 @@ import { type AssistantDraftStore, type DraftPersistenceTuning } from './draft-p
|
|
|
3
3
|
import { type AdmittedTurn, type TurnProgress } from './turn-admission';
|
|
4
4
|
import type { ChatTurnRequestContext, ChatTurnTraceOptions, CreateChatTurnRoutesOptions } from './turn-route-contracts';
|
|
5
5
|
import type { TurnRoutePhase } from './turn-progress';
|
|
6
|
-
/** Work `
|
|
6
|
+
/** Work started before `produce` took the turn: `handOff` gives it to `produce`; `release` frees it if nothing took it. */
|
|
7
7
|
export interface AfterAuthorizeWork {
|
|
8
8
|
handOff(): void;
|
|
9
9
|
release(): Promise<void>;
|
|
10
|
+
/** Free this too if the turn ends before `handOff`. */
|
|
11
|
+
add(release: () => void): void;
|
|
10
12
|
}
|
|
11
13
|
interface TurnExecutionOptions<TContext> {
|
|
12
14
|
options: CreateChatTurnRoutesOptions<TContext>;
|
|
@@ -271,6 +271,15 @@ export interface ChatTurnProduceArgs<TContext> {
|
|
|
271
271
|
* `createChatTurnRoutes` invocation supplies it before `produce` runs.
|
|
272
272
|
*/
|
|
273
273
|
handoffCompletion?: () => Promise<void>;
|
|
274
|
+
/** Set only under `dispatchFirst`, where `produce` starts before the lock. Resolves to the final args (with
|
|
275
|
+
* `userMessageId`, after `contextGate` and `beforeTurn`) once the admission chain commits, or rejects with
|
|
276
|
+
* `TurnAdmissionRefusedError` when the turn is refused. Start the model call at once; write nothing durable,
|
|
277
|
+
* and read nothing `beforeTurn` adds to `context`, until it resolves. */
|
|
278
|
+
admitted?: Promise<ChatTurnProduceArgs<TContext>>;
|
|
279
|
+
/** Set only under `dispatchFirst`: aborts when the turn is refused after `produce` started, or when the route stops
|
|
280
|
+
* reading the producer (a disconnect under `cancelOnDisconnect`). Pass it to the model call. Under `dispatchFirst`,
|
|
281
|
+
* `handoffCompletion` resolves only after `admitted` does. */
|
|
282
|
+
admissionSignal?: AbortSignal;
|
|
274
283
|
}
|
|
275
284
|
/** One event as it crosses the route: the producer's own vocabulary, or an
|
|
276
285
|
* injected keepalive. Same shape the engine forwards verbatim.
|
|
@@ -524,6 +533,28 @@ export interface CreateChatTurnRoutesOptions<TContext = void> {
|
|
|
524
533
|
* wrapped in `createSandboxChatProducer`. Router/openai-compat lane: the
|
|
525
534
|
* product's own producer. May be async (box resolution). */
|
|
526
535
|
produce(args: ChatTurnProduceArgs<TContext>): ChatTurnRouteProducer | Promise<ChatTurnRouteProducer>;
|
|
536
|
+
/**
|
|
537
|
+
* Start `produce`, and so the model call, right after the history read, while the lock, the history recheck, the
|
|
538
|
+
* user-row insert, `contextGate` and `beforeTurn` run (see `./dispatch-first`). Nothing it emits reaches the member,
|
|
539
|
+
* the turn buffer or the transcript before that chain commits; a refusal aborts it through `args.admissionSignal`
|
|
540
|
+
* and drops its output. `produce` receives `args.admitted` for the final args.
|
|
541
|
+
*
|
|
542
|
+
* Opt in only by naming where billing is enforced before any provider is paid: `'authorize'` (the product's
|
|
543
|
+
* balance and spend checks run there) or `'model-service'` (the Tangle Router holds the spend and refuses an
|
|
544
|
+
* unfunded key before it calls a provider, fail-closed). Entitlement gates the model service cannot know (a seat,
|
|
545
|
+
* a plan feature) belong in `contextGate`, which then runs while the model starts and holds its output until it
|
|
546
|
+
* passes. `beforeTurn` may still mutate `context` but must not return a patch, since the prompt has already been
|
|
547
|
+
* sent; a patch throws. Omit → `produce` runs after admission.
|
|
548
|
+
*
|
|
549
|
+
* `when` picks the turns that dispatch first (default all). Return false for a producer whose dispatch is keyed by
|
|
550
|
+
* the turn's `executionId` (a box session): two sends on one thread resolve the same id, and the refused duplicate
|
|
551
|
+
* would reach the winner's execution before the lock refused it. A Router call per request is safe; the refused
|
|
552
|
+
* duplicate costs only the call its `admissionSignal` cancels.
|
|
553
|
+
*/
|
|
554
|
+
dispatchFirst?: {
|
|
555
|
+
billing: 'authorize' | 'model-service';
|
|
556
|
+
when?: (args: ChatTurnProduceArgs<TContext>) => boolean;
|
|
557
|
+
};
|
|
527
558
|
/** Single-flight lock acquired before any side effect and released once when
|
|
528
559
|
* the turn settles (including short-circuit/throw). `/turn-stream`'s
|
|
529
560
|
* `createDurableTurnLock` is the shared DO-backed implementation. Omit →
|
|
@@ -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
|
-
|
|
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(
|
|
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(
|
|
17
|
-
inFlight.add(
|
|
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.
|
|
23
|
-
}).then((response) => response.body?.cancel()).catch(() => void 0).finally(() => inFlight.delete(
|
|
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
|
-
|
|
37
|
-
|
|
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-
|
|
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<WorkspacePrewarmHandle | null>(null)\n\nexport function useWorkspacePrewarmHandle(): WorkspacePrewarmHandle | null {\n return useContext(WorkspacePrewarmContext)\n}\n"],"mappings":";AAmBA,SAAS,eAAe,aAAa,YAAY,iBAAiB;AA0BlE,IAAM,0BAA0B;AAChC,IAAM,uBAAuB;AAC7B,IAAM,WAAW,oBAAI,IAAoB;AACzC,IAAM,WAAW,oBAAI,IAAY;AAEjC,SAAS,oBAA6B;AACpC,MAAI,OAAO,aAAa,YAAa,QAAO;AAC5C,MAAK,SAAmD,aAAc,QAAO;AAC7E,SAAO,SAAS,oBAAoB;AACtC;AAMO,SAAS,wBAAwB,KAAa,UAA0C,CAAC,GAAY;AAC1G,QAAM,SAAS,QAAQ,UAAU;AAEjC,QAAM,OAAO,GAAG,MAAM,IAAI,QAAQ,YAAY,EAAE,IAAI,GAAG;AACvD,MAAI,CAAC,OAAO,CAAC,kBAAkB,KAAK,SAAS,IAAI,IAAI,EAAG,QAAO;AAC/D,QAAM,MAAM,KAAK,IAAI;AACrB,QAAM,OAAO,SAAS,IAAI,IAAI;AAC9B,MAAI,SAAS,UAAa,MAAM,QAAQ,QAAQ,iBAAiB,yBAA0B,QAAO;AAClG,WAAS,IAAI,MAAM,GAAG;AACtB,WAAS,IAAI,IAAI;AACjB,OAAK,MAAM,KAAK;AAAA,IACd,QAAQ;AAAA,IACR,aAAa;AAAA,IACb,SAAS,EAAE,gBAAgB,mBAAmB;AAAA,IAC9C,MAAM,KAAK,UAAU,EAAE,QAAQ,GAAI,QAAQ,WAAW,EAAE,UAAU,QAAQ,SAAS,IAAI,CAAC,EAAG,CAAC;AAAA,EAC9F,CAAC,EACE,KAAK,CAAC,aAAa,SAAS,MAAM,OAAO,CAAC,EAC1C,MAAM,MAAM,MAAS,EACrB,QAAQ,MAAM,SAAS,OAAO,IAAI,CAAC;AACtC,SAAO;AACT;AAGO,SAAS,oBAAoB,SAA6D;AAC/F,QAAM,EAAE,KAAK,UAAU,MAAM,eAAe,SAAS,IAAI;AACzD,QAAM,cAAc,QAAQ,eAAe;AAC3C,QAAM,SAAS,WAAW,QAAQ,GAAG;AAErC,YAAU,MAAM;AACd,QAAI,CAAC,UAAU,CAAC,OAAO,OAAO,aAAa,YAAa;AACxD,UAAM,OAAO,MAAM;AACjB,8BAAwB,KAAK,EAAE,cAAc,CAAC;AAAA,IAChD;AACA,SAAK;AACL,aAAS,iBAAiB,oBAAoB,IAAI;AAGlD,QAAI,kBAAkB;AACtB,UAAM,UAAU,MAAM;AAAE,wBAAkB;AAAA,IAAK;AAC/C,UAAM,WAAW,CAAC,WAAW,eAAe,OAAO;AACnD,UAAM,OAAO,cAAc,IACvB,YAAY,MAAM;AAClB,UAAI,CAAC,gBAAiB;AACtB,wBAAkB;AAClB,8BAAwB,KAAK,EAAE,eAAe,cAAc,GAAG,QAAQ,YAAY,CAAC;AAAA,IACtF,GAAG,WAAW,IACZ;AACJ,QAAI,KAAM,YAAW,QAAQ,SAAU,UAAS,iBAAiB,MAAM,SAAS,EAAE,SAAS,KAAK,CAAC;AACjG,WAAO,MAAM;AACX,eAAS,oBAAoB,oBAAoB,IAAI;AACrD,UAAI,MAAM;AACR,sBAAc,IAAI;AAClB,mBAAW,QAAQ,SAAU,UAAS,oBAAoB,MAAM,OAAO;AAAA,MACzE;AAAA,IACF;AAAA,EACF,GAAG,CAAC,QAAQ,KAAK,eAAe,WAAW,CAAC;AAE5C,QAAM,WAAW,YAAY,MAAM;AACjC,QAAI,UAAU,IAAK,yBAAwB,KAAK,EAAE,eAAe,QAAQ,kBAAkB,GAAI,WAAW,EAAE,SAAS,IAAI,CAAC,EAAG,CAAC;AAAA,EAChI,GAAG,CAAC,QAAQ,KAAK,eAAe,QAAQ,CAAC;AAEzC,SAAO,EAAE,SAAS;AACpB;AAOO,IAAM,0BAA0B,cAA6C,IAAI;AAEjF,SAAS,4BAA2D;AACzE,SAAO,WAAW,uBAAuB;AAC3C;","names":[]}
|
|
@@ -28,6 +28,9 @@ import {
|
|
|
28
28
|
resolveTangleExecutionEnvironment,
|
|
29
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
|
-
|
|
868
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
893
|
-
|
|
894
|
-
for (const old of
|
|
895
|
-
if (
|
|
896
|
-
|
|
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,
|
|
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
|
|
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 (!
|
|
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-
|
|
3989
|
+
//# sourceMappingURL=chunk-5Y7Z5G3Y.js.map
|