@tangle-network/agent-app 0.60.100 → 0.60.102
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/chat-routes/index.js +2 -2
- package/dist/{chunk-TQ7K5FRG.js → chunk-3FH4GZ27.js} +19 -2
- package/dist/chunk-3FH4GZ27.js.map +1 -0
- package/dist/{chunk-N2UQIEWN.js → chunk-P2EKAQUB.js} +101 -9
- package/dist/chunk-P2EKAQUB.js.map +1 -0
- package/dist/public-consultation/index.d.ts +1 -1
- package/dist/runtime/index.js +1 -1
- package/dist/runtime/loop.d.ts +10 -0
- package/dist/runtime/openai-stream.d.ts +4 -0
- package/dist/sandbox/escalation-speculator.d.ts +66 -0
- package/dist/sandbox/index.d.ts +1 -0
- package/dist/sandbox/index.js +11 -1
- package/dist/sandbox/warm-lease-d1.d.ts +3 -1
- package/dist/sandbox/warm-lease.d.ts +21 -2
- package/package.json +1 -1
- package/dist/chunk-N2UQIEWN.js.map +0 -1
- package/dist/chunk-TQ7K5FRG.js.map +0 -1
|
@@ -42,7 +42,7 @@ import {
|
|
|
42
42
|
flattenHistory,
|
|
43
43
|
readSandboxBinaryBytes,
|
|
44
44
|
statSandboxFileSize
|
|
45
|
-
} from "../chunk-
|
|
45
|
+
} from "../chunk-P2EKAQUB.js";
|
|
46
46
|
import "../chunk-4LBCTFBP.js";
|
|
47
47
|
import "../chunk-WVESWAJJ.js";
|
|
48
48
|
import "../chunk-LWSJK546.js";
|
|
@@ -56,7 +56,7 @@ import "../chunk-TMOYOMSW.js";
|
|
|
56
56
|
import {
|
|
57
57
|
ProtectedModelSettlementError,
|
|
58
58
|
runRouterTurn
|
|
59
|
-
} from "../chunk-
|
|
59
|
+
} from "../chunk-3FH4GZ27.js";
|
|
60
60
|
import "../chunk-D6UJEOZQ.js";
|
|
61
61
|
import "../chunk-7YA4QNTU.js";
|
|
62
62
|
import {
|
|
@@ -25,11 +25,15 @@ async function* toLoopEvents(chunks) {
|
|
|
25
25
|
const reasoning = choice.delta?.reasoning_content ?? choice.delta?.thinking;
|
|
26
26
|
if (reasoning) yield { type: "reasoning", text: reasoning };
|
|
27
27
|
for (const tc of choice.delta?.tool_calls ?? []) {
|
|
28
|
-
const cur = calls.get(tc.index) ?? { name: "", args: "" };
|
|
28
|
+
const cur = calls.get(tc.index) ?? { name: "", args: "", announced: false };
|
|
29
29
|
if (tc.id) cur.id = tc.id;
|
|
30
30
|
if (tc.function?.name) cur.name += tc.function.name;
|
|
31
31
|
if (tc.function?.arguments) cur.args += tc.function.arguments;
|
|
32
32
|
calls.set(tc.index, cur);
|
|
33
|
+
if (!cur.announced && cur.name) {
|
|
34
|
+
cur.announced = true;
|
|
35
|
+
yield { type: "tool_call_start", ...cur.id ? { toolCallId: cur.id } : {}, toolName: cur.name };
|
|
36
|
+
}
|
|
33
37
|
}
|
|
34
38
|
}
|
|
35
39
|
for (const [, c] of [...calls.entries()].sort((a, b) => a[0] - b[0])) {
|
|
@@ -311,6 +315,19 @@ async function runRouterTurn(options) {
|
|
|
311
315
|
return outcome(typeof status === "number" ? { code: `model_http_${status}`, status, message: "The model service did not answer." } : { code: "model_unavailable", message: "The model service did not answer." });
|
|
312
316
|
}
|
|
313
317
|
if (stop !== "completed") return outcome({ code: `turn_${stop}`, message: "The reply was stopped before it finished." });
|
|
318
|
+
if (!segments.some((part) => part.trim())) {
|
|
319
|
+
if (toolsRan === 0) {
|
|
320
|
+
try {
|
|
321
|
+
stop = await run();
|
|
322
|
+
} catch {
|
|
323
|
+
stop = "completed";
|
|
324
|
+
}
|
|
325
|
+
if (stop !== "completed") return outcome({ code: `turn_${stop}`, message: "The reply was stopped before it finished." });
|
|
326
|
+
}
|
|
327
|
+
if (!segments.some((part) => part.trim())) {
|
|
328
|
+
return outcome({ code: "model_empty", message: "The model finished without writing a reply." });
|
|
329
|
+
}
|
|
330
|
+
}
|
|
314
331
|
return outcome();
|
|
315
332
|
}
|
|
316
333
|
|
|
@@ -439,4 +456,4 @@ export {
|
|
|
439
456
|
ProtectedModelSettlementError,
|
|
440
457
|
createRouterProtectedModelPort
|
|
441
458
|
};
|
|
442
|
-
//# sourceMappingURL=chunk-
|
|
459
|
+
//# sourceMappingURL=chunk-3FH4GZ27.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/runtime/openai-stream.ts","../src/runtime/loop.ts","../src/runtime/router-turn.ts","../src/runtime/protected-model.ts"],"sourcesContent":["/**\n * OpenAI-compatible stream → `LoopEvent` adapter, for NON-sandbox copilots.\n *\n * `streamAppToolLoop` takes a `streamTurn` seam that yields `LoopEvent`s. A\n * sandboxed agent produces those from its container; a browser/edge copilot\n * instead calls a model directly. The Tangle Router, the tcloud SDK, and most\n * providers all speak the OpenAI Chat Completions streaming shape — so the ONE\n * reusable piece is assembling that stream (content deltas + FRAGMENTED\n * tool-call deltas) into `LoopEvent`s. That assembly is the boilerplate every\n * copilot would re-write (and get wrong — OpenAI streams tool-call arguments in\n * pieces across chunks).\n *\n * This does NOT implement an HTTP client beyond a minimal `fetch` + SSE reader\n * (browser/edge/Node-safe, zero deps). For richer transport use the tcloud SDK\n * or the Vercel AI SDK and pipe their stream through {@link toLoopEvents}.\n */\nimport type { LoopEvent, LoopMessage, LoopToolCall } from './loop'\nimport { normalizeModelId } from './model-catalog'\n\n/** Minimal OpenAI Chat Completions streaming chunk (structural — no `openai` dep). */\nexport interface OpenAIStreamChunk {\n /** The model that produced this chunk. The Tangle Router reports the DATED\n * upstream id here (`gpt-5-2025-08-07`) whether or not it substituted, so\n * this is a served-model source only after id folding — see\n * {@link OpenAICompatServedModel}. */\n model?: string\n choices?: Array<{\n delta?: {\n content?: string | null\n /** Reasoning deltas — DeepSeek/router use `reasoning_content`; some proxies use `thinking`. */\n reasoning_content?: string | null\n thinking?: string | null\n tool_calls?: Array<{\n index: number\n id?: string\n function?: { name?: string; arguments?: string }\n }>\n }\n finish_reason?: string | null\n }>\n /** Final-chunk token accounting (requires `stream_options.include_usage`). */\n usage?: {\n prompt_tokens?: number\n completion_tokens?: number\n } | null\n}\n\ninterface PartialToolCall {\n id?: string\n name: string\n args: string\n announced: boolean\n}\n\n/**\n * Map an OpenAI-compat streaming chunk iterator to `LoopEvent`s: each content\n * delta → a `text` event; tool-call deltas are accumulated by index across\n * chunks and emitted as one complete `tool_call` event when the stream finishes\n * (arguments JSON-parsed; an empty/garbled args string yields `{}` rather than\n * throwing). Works for the Tangle Router, tcloud, or any OpenAI-compat source.\n *\n * Each call also yields one `tool_call_start` as soon as its name arrives,\n * while its arguments are still streaming, so a caller can start work the call\n * will need. Providers send the whole name in the call's first delta.\n */\nexport async function* toLoopEvents(chunks: AsyncIterable<OpenAIStreamChunk>): AsyncIterable<LoopEvent> {\n const calls = new Map<number, PartialToolCall>()\n for await (const chunk of chunks) {\n // Usage rides the final chunk, which has an empty choices array — handle\n // it before the choice guard.\n if (chunk.usage?.prompt_tokens != null || chunk.usage?.completion_tokens != null) {\n yield {\n type: 'usage',\n usage: {\n promptTokens: chunk.usage.prompt_tokens ?? 0,\n completionTokens: chunk.usage.completion_tokens ?? 0,\n },\n }\n }\n const choice = chunk.choices?.[0]\n if (!choice) continue\n const content = choice.delta?.content\n if (content) yield { type: 'text', text: content }\n const reasoning = choice.delta?.reasoning_content ?? choice.delta?.thinking\n if (reasoning) yield { type: 'reasoning', text: reasoning }\n for (const tc of choice.delta?.tool_calls ?? []) {\n const cur = calls.get(tc.index) ?? { name: '', args: '', announced: false }\n if (tc.id) cur.id = tc.id\n if (tc.function?.name) cur.name += tc.function.name\n if (tc.function?.arguments) cur.args += tc.function.arguments\n calls.set(tc.index, cur)\n if (!cur.announced && cur.name) {\n cur.announced = true\n yield { type: 'tool_call_start', ...(cur.id ? { toolCallId: cur.id } : {}), toolName: cur.name }\n }\n }\n }\n for (const [, c] of [...calls.entries()].sort((a, b) => a[0] - b[0])) {\n if (!c.name) continue\n yield { type: 'tool_call', call: { toolCallId: c.id, toolName: c.name, args: safeParse(c.args) } satisfies LoopToolCall }\n }\n}\n\nfunction safeParse(s: string): Record<string, unknown> {\n if (!s.trim()) return {}\n try {\n const v = JSON.parse(s)\n return v && typeof v === 'object' && !Array.isArray(v) ? (v as Record<string, unknown>) : {}\n } catch {\n return {}\n }\n}\n\n/**\n * Which model actually served one direct-router turn.\n *\n * The router substitutes models on purpose — a quota-walled primary comes back\n * `200` answered by a different model — and says so in response headers. This\n * lane used to drop the whole `Response` after taking `.body`, so a turn\n * requested as `claude-sonnet-4-6` and answered by `openai/gpt-5` was recorded\n * by its caller as Claude: per-model quality scoring blamed the wrong model and\n * cost used the wrong price basis.\n *\n * Map this onto the shell's existing attribution contract rather than inventing\n * a second channel — `ChatTurnRouteProducer.modelAttribution()` (`/chat-routes`):\n *\n * modelAttribution: () => ({ requestedModel, servedModel, echoReceived: true })\n *\n * Leave that contract's `servedSource` unset: its union is sandbox\n * profile-resolution vocabulary with no router analogue.\n */\nexport interface OpenAICompatServedModel {\n /** The model id this turn asked for (`OpenAICompatStreamTurnOptions.model`). */\n requestedModel: string\n /** The model the router/provider reports having actually served. */\n servedModel: string\n /** Where `servedModel` was read from. The header is the router's own\n * substitution signal; the body is the backstop that survives CORS. */\n source: 'router_header' | 'response_body'\n /** True when served differs from requested after id folding. Folded, not\n * compared raw: the body reports a dated id on EVERY turn, so `!==` would\n * claim a substitution every time. */\n substituted: boolean\n /** `x-tangle-failover` `trigger=` — why the router swapped. Absent when the\n * router did not inject the substitute (a caller-supplied fallback chain\n * sets the served-model header without the failover one). */\n trigger?: string\n /** `x-tangle-failover` `degraded=`. */\n degraded?: boolean\n}\n\n/** Parse `from=…; to=…; trigger=…; degraded=…` down to the fields we report.\n * Absent/garbled segments are simply omitted — attribution is best-effort and\n * must never fail a turn that is otherwise streaming fine. */\nfunction parseFailoverHeader(raw: string | null): { trigger?: string; degraded?: boolean } {\n if (!raw) return {}\n const fields = new Map<string, string>()\n for (const segment of raw.split(';')) {\n const eq = segment.indexOf('=')\n if (eq === -1) continue\n fields.set(segment.slice(0, eq).trim().toLowerCase(), segment.slice(eq + 1).trim())\n }\n const trigger = fields.get('trigger')\n const degraded = fields.get('degraded')\n return {\n ...(trigger ? { trigger } : {}),\n ...(degraded != null ? { degraded: degraded === 'true' } : {}),\n }\n}\n\n/** Define options for configuring an OpenAI-compatible streaming chat turn including API details and tools */\nexport interface OpenAICompatStreamTurnOptions {\n /** OpenAI-compat base URL (e.g. the Tangle Router `https://router.tangle.tools/v1`). */\n baseUrl: string\n apiKey: string\n model: string\n /** OpenAI tool definitions — pass `buildAppToolOpenAITools(taxonomy)` so the\n * model can call the app tools. Omit for a tool-free copilot. */\n tools?: unknown[]\n temperature?: number\n fetchImpl?: typeof fetch\n /** Extra body fields (e.g. `max_tokens`). */\n extraBody?: Record<string, unknown>\n /** Extra request headers, e.g. a trace id the router records with the generation. */\n headers?: Record<string, string>\n /**\n * Called at most ONCE per turn, as soon as the serving model is\n * determinable, with what actually answered. Never called when neither the\n * header nor the body names a model — silence means \"learned nothing\", not\n * \"nothing was substituted\".\n *\n * `streamTurn` runs once per TOOL turn, so a multi-turn `runAppToolLoop`\n * fires this once per turn; take the last for row attribution.\n */\n onServedModel?: (served: OpenAICompatServedModel) => void\n}\n\n/**\n * Build a `streamTurn` that calls an OpenAI-compatible `/chat/completions`\n * endpoint (Tangle Router / tcloud / any compat provider) with `stream: true`\n * and yields `LoopEvent`s via {@link toLoopEvents}. Browser/edge/Node-safe —\n * just `fetch` + an SSE reader. Drop straight into `streamAppToolLoop`:\n *\n * const cfg = resolveTangleModelConfig() // or { baseUrl, apiKey, model }\n * streamAppToolLoop({ streamTurn: createOpenAICompatStreamTurn({ ...cfg, tools }), executeToolCall, ... })\n */\nexport function createOpenAICompatStreamTurn(\n opts: OpenAICompatStreamTurnOptions,\n): (messages: LoopMessage[]) => AsyncIterable<LoopEvent> {\n const base = opts.baseUrl.replace(/\\/+$/, '')\n const doFetch = opts.fetchImpl ?? fetch\n return (messages) =>\n toLoopEvents(\n streamChatCompletions(doFetch, `${base}/chat/completions`, opts.apiKey, {\n model: opts.model,\n messages,\n stream: true,\n stream_options: { include_usage: true },\n ...(opts.tools && opts.tools.length > 0 ? { tools: opts.tools } : {}),\n ...(opts.temperature != null ? { temperature: opts.temperature } : {}),\n ...opts.extraBody,\n }, opts.onServedModel ? { requestedModel: opts.model, report: opts.onServedModel } : undefined, opts.headers),\n )\n}\n\n/** Stream + parse an OpenAI-compat SSE response into chunks. Tolerates `data:`\n * framing, multi-line buffers, and the terminal `[DONE]`. */\nasync function* streamChatCompletions(\n doFetch: typeof fetch,\n url: string,\n apiKey: string,\n body: Record<string, unknown>,\n attribution?: { requestedModel: string; report: (served: OpenAICompatServedModel) => void },\n headers?: Record<string, string>,\n): AsyncIterable<OpenAIStreamChunk> {\n const res = await doFetch(url, {\n method: 'POST',\n headers: { ...headers, Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json', Accept: 'text/event-stream' },\n body: JSON.stringify(body),\n })\n if (!res.ok || !res.body) {\n const text = res.body ? await res.text().catch(() => '') : ''\n const error = new Error(`OpenAI-compat stream failed (HTTP ${res.status})${text ? `: ${text.slice(0, 200)}` : ''}`)\n // Stamp the NUMERIC status. `isUpstreamUnavailable` (`/model-resolution`)\n // reads a numeric field first and prose only as a backstop, and a\n // Cloudflare EDGE 502 gives it nothing else to read: `content-type:\n // text/plain`, a body of `error code: 502`, and none of the router's own\n // `x-tangle-*` headers, because the origin never ran. Carrying the status\n // as data keeps THIS path — the browser/edge copilot lane, which calls the\n // router directly — out of the string-matching business entirely.\n Object.assign(error, { status: res.status })\n throw error\n }\n // Served-model attribution, fired at most once, as early as it is knowable.\n //\n // The header comes first because it is the router's OWN substitution signal:\n // `X-Tangle-Served-Model` is set only when the served model differs from the\n // requested one, so its presence is authoritative and it arrives before the\n // first byte of content. `X-Tangle-Failover` rides along only when the router\n // itself picked the substitute (a caller-supplied fallback chain sets the\n // former without the latter), which is why `trigger`/`degraded` are optional.\n //\n // The body is the backstop for when the header cannot reach us. In a BROWSER,\n // headers are invisible to JS unless the server lists them in\n // `Access-Control-Expose-Headers` — tangle-router#324 added both, but that\n // only helps once it is DEPLOYED, and any other OpenAI-compat endpoint\n // pointed at this client exposes nothing. The chunk `model` field is not\n // subject to CORS, so it keeps the browser lane attributable regardless.\n let reported = false\n const report = (served: OpenAICompatServedModel): void => {\n if (reported || !attribution) return\n reported = true\n attribution.report(served)\n }\n if (attribution) {\n const servedHeader = res.headers.get('x-tangle-served-model')\n if (servedHeader) {\n report({\n requestedModel: attribution.requestedModel,\n servedModel: servedHeader,\n source: 'router_header',\n substituted: normalizeModelId(servedHeader) !== normalizeModelId(attribution.requestedModel),\n ...parseFailoverHeader(res.headers.get('x-tangle-failover')),\n })\n }\n }\n const reader = res.body.getReader()\n const decoder = new TextDecoder()\n let buffer = ''\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n buffer += decoder.decode(value, { stream: true })\n const lines = buffer.split('\\n')\n buffer = lines.pop() ?? ''\n for (const line of lines) {\n const trimmed = line.trim()\n if (!trimmed.startsWith('data:')) continue\n const data = trimmed.slice(5).trim()\n if (data === '[DONE]') return\n let chunk: OpenAIStreamChunk\n try {\n chunk = JSON.parse(data) as OpenAIStreamChunk\n } catch {\n continue /* skip a partial/garbled SSE frame */\n }\n // Body fallback: only when the header said nothing. Fold both ids before\n // comparing — the router reports the dated upstream id (`gpt-5-2025-08-07`)\n // for a request of `openai/gpt-5` even with NO substitution, so a raw\n // `!==` would report a swap on literally every turn.\n if (attribution && !reported && chunk.model) {\n report({\n requestedModel: attribution.requestedModel,\n servedModel: chunk.model,\n source: 'response_body',\n substituted: normalizeModelId(chunk.model) !== normalizeModelId(attribution.requestedModel),\n })\n }\n yield chunk\n }\n }\n}\n","/**\n * The bounded agent tool-loop — owned by `@tangle-network/agent-runtime`.\n *\n * A model turn may emit tool calls (integration-hub actions, the app tools from\n * `../tools`, delegation). The loop streams a turn, collects the executable tool\n * calls, dispatches each, appends the results to history in OpenAI\n * function-calling shape, and re-runs so the model reads them — bounded by\n * `maxToolTurns`, a wall-clock `deadlineMs`, and a `maxCostUsd` budget.\n *\n * The history shape is the OpenAI function-calling contract: the assistant turn\n * that emitted tool calls is preserved as an `assistant` message carrying its\n * `tool_calls` array, and each result is its own `{ role: 'tool', tool_call_id,\n * content }` message keyed to the call. A strict model (Claude, and any\n * OpenAI-compatible provider that validates tool history) needs this to read its\n * own tool use back; folding results into a `user` message makes such models\n * re-issue the same call in a loop.\n *\n * The loop is substrate-owned (`runToolLoop` / `streamToolLoop`); the app\n * supplies `streamTurn` (wrapping its model endpoint) and `executeToolCall`\n * (routing to its integration + app-tool executors). The app-facing names below\n * are 1:1 aliases of the canonical symbols, kept so this package's consumers and\n * the in-package `createAgentRuntime` read against a single, stable vocabulary.\n *\n * This is the LEAF the runtime barrel and its children both import — keeping the\n * tool-loop vocabulary out of any import cycle. The barrel re-exports it.\n */\n\nexport {\n runToolLoop as runAppToolLoop,\n streamToolLoop as streamAppToolLoop,\n} from '@tangle-network/agent-runtime/tool-loop'\nexport type {\n ToolLoopCall as LoopToolCall,\n ToolLoopAssistantToolCall as LoopAssistantToolCall,\n ToolLoopMessage as LoopMessage,\n ToolLoopEvent,\n ToolLoopStopReason,\n ToolLoopResult,\n RunToolLoopOptions as AppToolLoopOptions,\n StreamToolLoopOptions as StreamAppToolLoopOptions,\n StreamToolLoopYield as StreamLoopYield,\n} from '@tangle-network/agent-runtime/tool-loop'\n\n/**\n * Events the app's OpenAI-compat stream adapter ({@link toLoopEvents}) yields.\n *\n * This is the app's own `Raw` event type for the streaming loop — the canonical\n * `streamToolLoop<Raw>` is generic over it. It widens the substrate's\n * tool-loop event with `reasoning` (DeepSeek/router `reasoning_content` /\n * `thinking` deltas, rendered as thinking sections) and `usage` (per-message\n * token accounting) — neither belongs in the substrate's loop contract, so they\n * stay here. The adapter maps each into the `streamTurn` seam; `text` and\n * `tool_call` drive the loop, `reasoning` / `usage` pass through to the UI.\n */\nexport type LoopEvent =\n | { type: 'text'; text: string }\n | { type: 'reasoning'; text: string }\n /** The model has begun a tool call: its name is known, its arguments are\n * still streaming. Emitted once per call, before its `tool_call`. Lets a\n * caller start slow work the call will need (resuming a sandbox box for\n * `sandbox_run`) while the arguments arrive. Consumers that do not care\n * ignore it: it never drives the loop. */\n | { type: 'tool_call_start'; toolCallId?: string; toolName: string }\n | {\n type: 'tool_call'\n call: import('@tangle-network/agent-runtime/tool-loop').ToolLoopCall\n }\n | { type: 'usage'; usage: { promptTokens: number; completionTokens: number } }\n | { type: 'other'; event: unknown }\n","/**\n * One conversational turn answered by a model through the Tangle Router, with\n * the app's own tools executed in-process — no sandbox in the path.\n *\n * This is the default runtime for conversational turns in an agent app: the\n * product supplies the principal's tools, the profile prompt and the\n * conversation; the engine streams words as the model writes them, runs tool\n * calls through the bounded `streamAppToolLoop`, and returns one outcome.\n * Long, file or code work belongs to the sandbox, reached through a tool the\n * product adds to `tools`.\n *\n * Every failure is an outcome, never a throw. A durable turn owner retries\n * thrown errors, and a retry after a tool ran would repeat that tool's effect\n * (\"never re-run a turn automatically\", docs/agent-app-lessons.md). The only\n * automatic repeat is one model call that failed before any word or tool.\n */\nimport { streamAppToolLoop, type LoopEvent, type LoopMessage, type LoopToolCall, type ToolLoopStopReason } from './loop'\nimport { DEFAULT_TANGLE_ROUTER_BASE_URL } from './model'\nimport { createOpenAICompatStreamTurn } from './openai-stream'\n\n/** A tool the turn may call. Structurally an `McpToolDefinition` whose env is already bound. */\nexport interface RouterTurnTool {\n name: string\n description: string\n /** JSON Schema for the arguments object. */\n inputSchema: Record<string, unknown>\n run(args: Record<string, unknown>): Promise<unknown>\n}\n\n/** What the turn is doing, in the order it happens, for a live view. */\nexport type RouterTurnEvent =\n | { type: 'text'; segment: number; delta: string }\n | { type: 'tool'; callId: string; toolName: string; status: 'running'; input: Record<string, unknown>; startedAt: number }\n | { type: 'tool'; callId: string; toolName: string; status: 'completed'; output: unknown; startedAt: number; endedAt: number }\n | { type: 'tool'; callId: string; toolName: string; status: 'error'; error: { code: string; message: string }; startedAt: number; endedAt: number }\n | { type: 'usage'; promptTokens: number; completionTokens: number }\n\nexport interface RouterTurnFailure {\n /** `model_http_<status>`, `model_unavailable`, `turn_<stopReason>` or `router_unconfigured`. */\n code: string\n status?: number\n message: string\n}\n\nexport interface RouterTurnOutcome {\n /** Every text segment the model wrote, joined by blank lines. */\n text: string\n /** The model the router reports having served, when it said. */\n servedModel: string | null\n toolCalls: Array<{ callId: string; toolName: string; ok: boolean }>\n /** Token use summed over every model call in the turn, as the router reported it. */\n usage: { promptTokens: number; completionTokens: number; modelCalls: number }\n failure?: RouterTurnFailure\n}\n\nexport interface RouterTurnOptions {\n apiKey: string\n model: string\n /** Defaults to the Tangle Router. */\n baseUrl?: string\n systemPrompt: string\n userMessage: string\n /** Earlier turns. Plain text messages, or OpenAI function-calling history (an assistant message\n * carrying `tool_calls` and the `tool` messages answering them) so the model sees what it did. */\n history?: Array<{ role: 'user' | 'assistant'; content: string } | LoopMessage>\n tools?: RouterTurnTool[]\n /** Wall-clock budget in ms. Default 90 s. A caller whose retry window is shorter passes less. */\n budgetMs?: number\n /** Runaway backstop on model turns. Default 12. */\n maxToolTurns?: number\n maxTokens?: number\n /** Sent as `x-tangle-trace-id` so the router's generation joins the app's trace. */\n traceId?: string\n fetchImpl?: typeof fetch\n onEvent?: (event: RouterTurnEvent) => void\n /** Map a thrown tool error to what the model reads. Default: an error carrying string `code`\n * (and numeric `status`) is reported with its message; anything else is a generic failure. */\n toolError?: (error: unknown) => { code: string; message: string; status?: number } | null\n /** Called for a tool failure the default mapping hides from the model, for the app's logs. */\n onToolFailure?: (toolName: string, error: unknown) => void\n}\n\nconst DEFAULT_BUDGET_MS = 90_000\nconst TOOL_RESULT_LIMIT = 12_000\n\n/** OpenAI-compatible function names allow only `[A-Za-z0-9_-]{1,64}`; app tool names often use dots. */\nexport function routerFunctionName(name: string): string {\n return name.replace(/[^A-Za-z0-9_-]/g, '_').slice(0, 64)\n}\n\n/**\n * The lean system prompt for a Router turn: the profile's system prompt and\n * instructions, then caller context, with tool names rewritten to the function\n * names the model actually calls.\n */\nexport function composeRouterTurnPrompt(\n profile: { prompt?: { systemPrompt?: string; instructions?: readonly string[] } },\n options: { context?: readonly string[]; toolNames?: readonly string[] } = {},\n): string {\n const text = [profile.prompt?.systemPrompt ?? '', ...(profile.prompt?.instructions ?? []), ...(options.context ?? [])]\n .filter(part => part.trim()).join('\\n\\n')\n return [...(options.toolNames ?? [])].sort((a, b) => b.length - a.length)\n .reduce((out, name) => out.split(name).join(routerFunctionName(name)), text)\n}\n\nfunction defaultToolError(error: unknown): { code: string; message: string; status?: number } | null {\n const value = error as { code?: unknown; status?: unknown; message?: unknown; issues?: unknown }\n if (Array.isArray(value?.issues)) {\n return { code: 'invalid_arguments', message: JSON.stringify(value.issues).slice(0, 600) }\n }\n if (typeof value?.code === 'string' && typeof value.message === 'string') {\n return { code: value.code, message: value.message, ...(typeof value.status === 'number' ? { status: value.status } : {}) }\n }\n return null\n}\n\nfunction renderResult(outcome: { ok: true; result: unknown } | { ok: false; code: string; message: string }): string {\n if (!outcome.ok) return `Error (${outcome.code}): ${outcome.message}`\n let text: string\n try { text = typeof outcome.result === 'string' ? outcome.result : JSON.stringify(outcome.result ?? null) }\n catch { text = String(outcome.result) }\n return text.length > TOOL_RESULT_LIMIT ? `${text.slice(0, TOOL_RESULT_LIMIT)}…` : text\n}\n\nexport async function runRouterTurn(options: RouterTurnOptions): Promise<RouterTurnOutcome> {\n if (!options.apiKey) {\n return { text: '', servedModel: null, toolCalls: [], usage: { promptTokens: 0, completionTokens: 0, modelCalls: 0 },\n failure: { code: 'router_unconfigured', message: 'The model credential is not configured.' } }\n }\n const emit = options.onEvent ?? (() => {})\n const byFunction = new Map<string, RouterTurnTool>()\n for (const tool of options.tools ?? []) {\n const fn = routerFunctionName(tool.name)\n if (!byFunction.has(fn)) byFunction.set(fn, tool)\n }\n let servedModel: string | null = null\n const streamTurn = createOpenAICompatStreamTurn({\n baseUrl: options.baseUrl ?? DEFAULT_TANGLE_ROUTER_BASE_URL,\n apiKey: options.apiKey,\n model: options.model,\n tools: [...byFunction.entries()].map(([name, tool]) => ({\n type: 'function', function: { name, description: tool.description, parameters: tool.inputSchema },\n })),\n ...(options.maxTokens ? { extraBody: { max_tokens: options.maxTokens } } : {}),\n ...(options.traceId ? { headers: { 'x-tangle-trace-id': options.traceId } } : {}),\n ...(options.fetchImpl ? { fetchImpl: options.fetchImpl } : {}),\n onServedModel: served => { servedModel = served.servedModel },\n })\n const segments: string[] = []\n const usage = { promptTokens: 0, completionTokens: 0, modelCalls: 0 }\n const toolCalls: RouterTurnOutcome['toolCalls'] = []\n const started = new Map<string, number>()\n let segmentOpen = false\n let toolsRan = 0\n const deadline = Date.now() + (options.budgetMs ?? DEFAULT_BUDGET_MS)\n const callIdOf = (id: string | undefined, toolName: string) => id ?? `${toolName}-${started.size}`\n\n const run = async (): Promise<ToolLoopStopReason> => {\n for await (const step of streamAppToolLoop<LoopEvent>({\n systemPrompt: options.systemPrompt,\n userMessage: options.userMessage,\n priorMessages: (options.history ?? []) as LoopMessage[],\n streamTurn,\n extractText: event => event.type === 'text' ? event.text : '',\n extractToolCall: event => event.type === 'tool_call' ? event.call : null,\n isExecutableTool: name => byFunction.has(name),\n deadlineMs: deadline,\n maxToolTurns: options.maxToolTurns ?? 12,\n renderResult: (_label, outcome) => renderResult(outcome),\n executeToolCall: async (call: LoopToolCall) => {\n const tool = byFunction.get(call.toolName)\n if (!tool) return { ok: false, code: 'unknown_tool', message: `No tool named ${call.toolName}` }\n toolsRan++\n try {\n return { ok: true, result: await tool.run(call.args) }\n } catch (error) {\n const mapped = (options.toolError ?? defaultToolError)(error)\n if (mapped) return { ok: false, ...mapped }\n options.onToolFailure?.(tool.name, error)\n return { ok: false, code: 'tool_failed', message: 'The tool failed; tell the user what could not be completed.' }\n }\n },\n })) {\n if (step.kind === 'event') {\n const event = step.event\n if (event.type === 'text' && event.text) {\n if (!segmentOpen) { segments.push(''); segmentOpen = true }\n segments[segments.length - 1] += event.text\n emit({ type: 'text', segment: segments.length, delta: event.text })\n } else if (event.type === 'usage') {\n usage.promptTokens += event.usage.promptTokens\n usage.completionTokens += event.usage.completionTokens\n usage.modelCalls++\n emit({ type: 'usage', ...event.usage })\n } else if (event.type === 'tool_call') {\n segmentOpen = false\n const tool = byFunction.get(event.call.toolName)\n const callId = callIdOf(event.call.toolCallId, event.call.toolName)\n started.set(callId, Date.now())\n emit({ type: 'tool', callId, toolName: tool?.name ?? event.call.toolName, status: 'running',\n input: event.call.args, startedAt: started.get(callId)! })\n }\n } else if (step.kind === 'tool_result') {\n const tool = byFunction.get(step.toolName)\n const callId = callIdOf(step.toolCallId, step.toolName)\n const startedAt = started.get(callId) ?? Date.now()\n const toolName = tool?.name ?? step.toolName\n toolCalls.push({ callId, toolName, ok: step.outcome.ok })\n emit(step.outcome.ok\n ? { type: 'tool', callId, toolName, status: 'completed', output: step.outcome.result, startedAt, endedAt: Date.now() }\n : { type: 'tool', callId, toolName, status: 'error', startedAt, endedAt: Date.now(),\n error: { code: step.outcome.code, message: step.outcome.message } })\n } else if (step.kind === 'capped') {\n return step.stopReason\n }\n }\n return 'completed'\n }\n\n const outcome = (failure?: RouterTurnFailure): RouterTurnOutcome => ({\n text: segments.map(part => part.trim()).filter(Boolean).join('\\n\\n'),\n servedModel, toolCalls, usage: { ...usage }, ...(failure ? { failure } : {}),\n })\n let stop: ToolLoopStopReason\n try {\n try {\n stop = await run()\n } catch (error) {\n // Safe to repeat only while nothing was said and no tool ran.\n if (toolsRan > 0 || segments.length > 0) throw error\n stop = await run()\n }\n } catch (error) {\n const status = (error as { status?: unknown }).status\n return outcome(typeof status === 'number'\n ? { code: `model_http_${status}`, status, message: 'The model service did not answer.' }\n : { code: 'model_unavailable', message: 'The model service did not answer.' })\n }\n if (stop !== 'completed') return outcome({ code: `turn_${stop}`, message: 'The reply was stopped before it finished.' })\n // A model can end its turn with neither a word nor a tool call (gemini-2.5-flash did on 8 of\n // 53 \"remember\" turns, 2026-10-11). Nothing was said and nothing ran, so one repeat is safe;\n // an answer still blank is a typed failure, never a successful empty reply.\n if (!segments.some(part => part.trim())) {\n if (toolsRan === 0) {\n try { stop = await run() } catch { stop = 'completed' }\n if (stop !== 'completed') return outcome({ code: `turn_${stop}`, message: 'The reply was stopped before it finished.' })\n }\n if (!segments.some(part => part.trim())) {\n return outcome({ code: 'model_empty', message: 'The model finished without writing a reply.' })\n }\n }\n return outcome()\n}\n","import {\n createProtectedAgentCandidateModelPort,\n type AgentCandidateModelGrantClient,\n type AgentCandidateModelPort,\n} from '@tangle-network/agent-runtime/candidate-execution'\n\nconst GATEWAY_ORIGIN = 'https://candidate-router.tangle.tools'\nconst CONTROL_ORIGIN = 'https://router.tangle.tools/v1/candidate-model-grants'\nconst ACTIVATION_NAMES = [\n 'MODEL_GATEWAY_TOKEN', 'MODEL_GATEWAY_BASE_URL', 'OPENAI_API_KEY', 'OPENAI_BASE_URL',\n 'ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_BASE_URL',\n] as const\n\nexport interface RouterProtectedModelPortOptions {\n apiKey: string\n maxCostUsd: number\n clientName?: string\n signal?: AbortSignal\n onSettlement?(receipt: RouterProtectedModelSettlement): Promise<void> | void\n}\n\n/** A validated charge remains authoritative when the product cannot save its audit record. */\nexport class ProtectedModelSettlementError extends Error {\n constructor(readonly settlement: Awaited<ReturnType<AgentCandidateModelPort['settleGrant']>>, cause: unknown) {\n super('Protected model settled, but its audit record could not be saved', { cause })\n this.name = 'ProtectedModelSettlementError'\n }\n}\n\n/** Bind one turn to Router's atomic grant ledger without exposing its parent key. */\nexport function createRouterProtectedModelPort(options: RouterProtectedModelPortOptions): AgentCandidateModelPort {\n if (!options.apiKey || !Number.isFinite(options.maxCostUsd) || options.maxCostUsd <= 0\n || !Number.isSafeInteger(Math.round(options.maxCostUsd * 1_000_000_000))) {\n throw new Error('Protected Router transport requires a parent key and finite positive cap')\n }\n const receipts = new Map<string, RouterProtectedModelSettlement>()\n async function request<T>(operation: string, body: unknown, settling = false): Promise<T> {\n const timeout = AbortSignal.timeout(settling ? 30_000 : 15_000)\n const signal = !settling && options.signal ? AbortSignal.any([timeout, options.signal]) : timeout\n let response: Response\n try {\n response = await fetch(`${CONTROL_ORIGIN}/${operation}`, {\n // Workerd supports manual redirects; non-2xx responses below still fail closed.\n method: 'POST', redirect: 'manual', signal,\n headers: {\n Authorization: `Bearer ${options.apiKey}`,\n 'Content-Type': 'application/json', 'X-Tangle-Client': options.clientName ?? 'agent-app',\n },\n body: JSON.stringify(body),\n })\n } catch {\n if (!settling && options.signal?.aborted) throw options.signal.reason\n throw new Error(`Protected model ${operation} transport failed`)\n }\n if (!response.ok) {\n const body = await response.json().catch(() => null) as { error?: { code?: unknown } } | null\n const code = body?.error?.code\n // Preserve Runtime's draining retry contract without echoing server text or credentials.\n const safeCode = typeof code === 'string' && /^candidate_[a-z_]{1,80}$/.test(code) ? code : 'request_failed'\n throw new Error(`Protected model ${operation}: ${safeCode} (HTTP ${response.status})`)\n }\n return await response.json() as T\n }\n\n const client: AgentCandidateModelGrantClient = {\n reserve: (value) => request('reserve', value),\n activate: async (value) => {\n const activation = await request<Awaited<ReturnType<AgentCandidateModelGrantClient['activate']>>>('activate', value)\n const env = activation?.env\n const token = env?.MODEL_GATEWAY_TOKEN\n if (typeof token !== 'string' || !/^sk-tgr-[A-Za-z0-9_-]{32,}$/.test(token)\n || env.MODEL_GATEWAY_BASE_URL !== `${GATEWAY_ORIGIN}/v1`\n || env.OPENAI_BASE_URL !== `${GATEWAY_ORIGIN}/v1`\n || env.ANTHROPIC_BASE_URL !== GATEWAY_ORIGIN\n || [env.OPENAI_API_KEY, env.ANTHROPIC_API_KEY, env.ANTHROPIC_AUTH_TOKEN].some((value) => value !== token)) {\n throw new Error('Protected model activation changed the gateway or credential binding')\n }\n return activation\n },\n settle: async (value) => {\n const settlement = await request<RouterProtectedModelSettlement>('settle', value, true)\n assertWithinCap(settlement, options.maxCostUsd)\n receipts.set(value.preparationId, settlement)\n return settlement\n },\n }\n const port = createProtectedAgentCandidateModelPort({\n client, resolveModel: (value) => request('resolve', value),\n gatewayDomain: 'candidate-router.tangle.tools', activationEnvNames: ACTIVATION_NAMES,\n })\n return {\n ...port,\n settleGrant: async (value) => {\n const settlement = await port.settleGrant(value)\n const receipt = receipts.get(value.preparationId)\n if (receipt) {\n try {\n await options.onSettlement?.(structuredClone(receipt))\n } catch (error) {\n throw new ProtectedModelSettlementError(settlement, error)\n } finally {\n receipts.delete(value.preparationId)\n }\n }\n return settlement\n },\n }\n}\n\n/**\n * Router's settle response is Runtime's exact settlement ledger. Router keeps\n * the billing hold and charge behind it and refuses a settlement outside the\n * grant's frozen limits; Runtime rejects unknown or missing ledger fields.\n */\nexport type RouterProtectedModelSettlement = Awaited<ReturnType<AgentCandidateModelGrantClient['settle']>>\n\n/** Bound the ledger's cumulative cost by this turn's cap before anything retains it. */\nfunction assertWithinCap(settlement: RouterProtectedModelSettlement, capUsd: number): void {\n if (!Array.isArray(settlement?.calls)) throw new Error('Protected model settlement has no call ledger')\n const capNanos = Math.round(capUsd * 1_000_000_000)\n let cost = 0\n for (const call of settlement.calls) {\n if (!Number.isSafeInteger(call?.costUsdNanos) || call.costUsdNanos < 0) {\n throw new Error('Protected model call cost is invalid')\n }\n cost += call.costUsdNanos\n if (!Number.isSafeInteger(cost) || cost > capNanos) {\n throw new Error('Protected model settlement exceeds its cost cap')\n }\n }\n}\n"],"mappings":";;;;;;;;AAiEA,gBAAuB,aAAa,QAAoE;AACtG,QAAM,QAAQ,oBAAI,IAA6B;AAC/C,mBAAiB,SAAS,QAAQ;AAGhC,QAAI,MAAM,OAAO,iBAAiB,QAAQ,MAAM,OAAO,qBAAqB,MAAM;AAChF,YAAM;AAAA,QACJ,MAAM;AAAA,QACN,OAAO;AAAA,UACL,cAAc,MAAM,MAAM,iBAAiB;AAAA,UAC3C,kBAAkB,MAAM,MAAM,qB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BAA8B,YAAY,KAAK;AAAA,QAC3D,UAAE;AACA,mBAAS,OAAO,MAAM,aAAa;AAAA,QACrC;AAAA,MACF;AACA,aAAO;AAAA,IACT;AAAA,EACF;AACF;AAUA,SAAS,gBAAgB,YAA4C,QAAsB;AACzF,MAAI,CAAC,MAAM,QAAQ,YAAY,KAAK,EAAG,OAAM,IAAI,MAAM,+CAA+C;AACtG,QAAM,WAAW,KAAK,MAAM,SAAS,GAAa;AAClD,MAAI,OAAO;AACX,aAAW,QAAQ,WAAW,OAAO;AACnC,QAAI,CAAC,OAAO,cAAc,MAAM,YAAY,KAAK,KAAK,eAAe,GAAG;AACtE,YAAM,IAAI,MAAM,sCAAsC;AAAA,IACxD;AACA,YAAQ,KAAK;AACb,QAAI,CAAC,OAAO,cAAc,IAAI,KAAK,OAAO,UAAU;AAClD,YAAM,IAAI,MAAM,iDAAiD;AAAA,IACnE;AAAA,EACF;AACF;","names":["outcome","body","value"]}
|
|
@@ -692,7 +692,7 @@ var SLOT_HALF_LIFE_MS = 14 * DAY_MS;
|
|
|
692
692
|
var PING_MARGIN_MS = 2 * 6e4;
|
|
693
693
|
var THRESHOLD_FLOOR = 0.05;
|
|
694
694
|
var THRESHOLD_CEILING = 0.95;
|
|
695
|
-
var DEFAULT_BUDGETED = ["page-open", "member-activity", "predicted", "scheduled"];
|
|
695
|
+
var DEFAULT_BUDGETED = ["page-open", "member-activity", "predicted", "scheduled", "escalation-likely"];
|
|
696
696
|
function warmBinOf(at) {
|
|
697
697
|
return Math.floor((at % DAY_MS + DAY_MS) % DAY_MS / BIN_MS);
|
|
698
698
|
}
|
|
@@ -755,7 +755,7 @@ function createWarmLeases(options) {
|
|
|
755
755
|
} catch {
|
|
756
756
|
}
|
|
757
757
|
};
|
|
758
|
-
const spentToday = (row, at) => row && row.day === utcDay(at) ? row.dayWarmMs : 0;
|
|
758
|
+
const spentToday = (row, at) => (row && row.day === utcDay(at) ? row.dayWarmMs : 0) + (row && row.pendingWarmAt > 0 && utcDay(row.pendingWarmAt) === utcDay(at) ? row.pendingMs : 0);
|
|
759
759
|
function chargeOf(row) {
|
|
760
760
|
if (!row.resumed || row.usedAt > 0 || row.warmAt <= 0) return 0;
|
|
761
761
|
const lastActivity = Math.max(row.warmAt, row.pingAt);
|
|
@@ -803,11 +803,21 @@ function createWarmLeases(options) {
|
|
|
803
803
|
if (hit && before) {
|
|
804
804
|
emit({ type: "warm_hit", key, reason: before.reason ?? "unknown", leadMs: at - before.startedAt });
|
|
805
805
|
}
|
|
806
|
+
let lateHit = false;
|
|
807
|
+
if (before && before.pendingWarmAt > 0 && at < before.pendingWarmAt + before.pendingMs) {
|
|
808
|
+
const unused = Math.max(0, at - before.pendingWarmAt);
|
|
809
|
+
if (await store.settlePending(key, before.pendingWarmAt, utcDay(before.pendingWarmAt), unused)) {
|
|
810
|
+
lateHit = true;
|
|
811
|
+
const reason = before.pendingReason ?? "unknown";
|
|
812
|
+
emit({ type: "warm_hit", key, reason, leadMs: unused });
|
|
813
|
+
if (unused >= 6e4) emit({ type: "warm_wasted", key, reason, minutes: Math.round(unused / 6e4) });
|
|
814
|
+
}
|
|
815
|
+
}
|
|
806
816
|
if (coldArrival) {
|
|
807
817
|
const slots = addColdArrival(before?.slots ?? [], before?.slotsAt ?? 0, at);
|
|
808
818
|
await store.writeProfile(key, slots, at, before?.firstSeenAt || at);
|
|
809
819
|
}
|
|
810
|
-
return { hit, coldArrival };
|
|
820
|
+
return { hit: hit || lateHit, coldArrival };
|
|
811
821
|
}
|
|
812
822
|
async function sweep(sweepOptions = {}) {
|
|
813
823
|
const limit = sweepOptions.limit ?? 50;
|
|
@@ -821,14 +831,18 @@ function createWarmLeases(options) {
|
|
|
821
831
|
const current = row.threshold > 0 ? row.threshold : initialThreshold;
|
|
822
832
|
threshold = Math.min(THRESHOLD_CEILING, Math.max(THRESHOLD_FLOOR, current * (row.usedAt > 0 ? 0.85 : 1.3)));
|
|
823
833
|
}
|
|
824
|
-
await store.end(row.key, row.leaseId, utcDay(row.warmAt || row.startedAt),
|
|
834
|
+
await store.end(row.key, row.leaseId, utcDay(row.warmAt || row.startedAt), 0, threshold);
|
|
835
|
+
if (charge > 0) await store.markPending(row.key, row.warmAt, charge, row.reason ?? "unknown");
|
|
825
836
|
report.ended += 1;
|
|
826
837
|
if (row.warmAt <= 0) {
|
|
827
838
|
report.abandoned += 1;
|
|
828
839
|
emit({ type: "warm_abandoned", key: row.key, reason: row.reason ?? "unknown" });
|
|
829
|
-
}
|
|
840
|
+
}
|
|
841
|
+
}
|
|
842
|
+
for (const row of await store.listPendingDue(at, limit)) {
|
|
843
|
+
if (await store.settlePending(row.key, row.pendingWarmAt, utcDay(row.pendingWarmAt), row.pendingMs)) {
|
|
830
844
|
report.wasted += 1;
|
|
831
|
-
emit({ type: "warm_wasted", key: row.key, reason: row.
|
|
845
|
+
emit({ type: "warm_wasted", key: row.key, reason: row.pendingReason ?? "unknown", minutes: Math.round(row.pendingMs / 6e4) });
|
|
832
846
|
}
|
|
833
847
|
}
|
|
834
848
|
if (options.keepAlive && burstHoldMs > boxIdleMs) {
|
|
@@ -884,9 +898,17 @@ var WARM_LEASE_TABLE_DDL = `CREATE TABLE IF NOT EXISTS ${DEFAULT_WARM_LEASE_TABL
|
|
|
884
898
|
slots_at INTEGER NOT NULL DEFAULT 0,
|
|
885
899
|
first_seen_at INTEGER NOT NULL DEFAULT 0,
|
|
886
900
|
predicted_at INTEGER NOT NULL DEFAULT 0,
|
|
887
|
-
declined_until INTEGER NOT NULL DEFAULT 0
|
|
901
|
+
declined_until INTEGER NOT NULL DEFAULT 0,
|
|
902
|
+
pending_warm_at INTEGER NOT NULL DEFAULT 0,
|
|
903
|
+
pending_ms INTEGER NOT NULL DEFAULT 0,
|
|
904
|
+
pending_reason TEXT
|
|
888
905
|
)`;
|
|
889
906
|
var WARM_LEASE_DECLINED_UNTIL_DDL = `ALTER TABLE ${DEFAULT_WARM_LEASE_TABLE} ADD COLUMN declined_until INTEGER NOT NULL DEFAULT 0`;
|
|
907
|
+
var WARM_LEASE_PENDING_DDL = [
|
|
908
|
+
`ALTER TABLE ${DEFAULT_WARM_LEASE_TABLE} ADD COLUMN pending_warm_at INTEGER NOT NULL DEFAULT 0`,
|
|
909
|
+
`ALTER TABLE ${DEFAULT_WARM_LEASE_TABLE} ADD COLUMN pending_ms INTEGER NOT NULL DEFAULT 0`,
|
|
910
|
+
`ALTER TABLE ${DEFAULT_WARM_LEASE_TABLE} ADD COLUMN pending_reason TEXT`
|
|
911
|
+
];
|
|
890
912
|
var SAFE_IDENTIFIER2 = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
891
913
|
function parseSlots(text) {
|
|
892
914
|
if (!text) return [];
|
|
@@ -916,7 +938,10 @@ function toRow(row) {
|
|
|
916
938
|
slotsAt: row.slots_at,
|
|
917
939
|
firstSeenAt: row.first_seen_at,
|
|
918
940
|
predictedAt: row.predicted_at,
|
|
919
|
-
declinedUntil: row.declined_until ?? 0
|
|
941
|
+
declinedUntil: row.declined_until ?? 0,
|
|
942
|
+
pendingWarmAt: row.pending_warm_at ?? 0,
|
|
943
|
+
pendingMs: row.pending_ms ?? 0,
|
|
944
|
+
pendingReason: row.pending_reason ?? null
|
|
920
945
|
};
|
|
921
946
|
}
|
|
922
947
|
function createD1WarmLeaseStore(db, options = {}) {
|
|
@@ -986,6 +1011,24 @@ WHERE key = ?1 AND lease_id = ?2`;
|
|
|
986
1011
|
async markPinged(key, at) {
|
|
987
1012
|
await q(`UPDATE ${t} SET ping_at = ?2 WHERE key = ?1`, key, at).run();
|
|
988
1013
|
},
|
|
1014
|
+
async markPending(key, warmAt, maxMs, reason) {
|
|
1015
|
+
await q(
|
|
1016
|
+
`UPDATE ${t} SET pending_warm_at = ?2, pending_ms = ?3, pending_reason = ?4 WHERE key = ?1`,
|
|
1017
|
+
key,
|
|
1018
|
+
warmAt,
|
|
1019
|
+
Math.max(0, Math.round(maxMs)),
|
|
1020
|
+
reason
|
|
1021
|
+
).run();
|
|
1022
|
+
},
|
|
1023
|
+
async settlePending(key, warmAt, day, chargeMs) {
|
|
1024
|
+
const settled = await q(`UPDATE ${t} SET
|
|
1025
|
+
day_warm_ms = CASE WHEN day = ?3 THEN day_warm_ms + ?4 WHEN day < ?3 THEN ?4 ELSE day_warm_ms END,
|
|
1026
|
+
day = CASE WHEN day < ?3 THEN ?3 ELSE day END,
|
|
1027
|
+
pending_warm_at = 0, pending_ms = 0, pending_reason = NULL
|
|
1028
|
+
WHERE key = ?1 AND pending_warm_at = ?2 RETURNING key`, key, warmAt, day, Math.max(0, Math.round(chargeMs))).first();
|
|
1029
|
+
return settled != null;
|
|
1030
|
+
},
|
|
1031
|
+
listPendingDue: (now, limit) => list(`SELECT * FROM ${t} WHERE pending_warm_at > 0 AND pending_warm_at + pending_ms <= ?1 ORDER BY pending_warm_at LIMIT ?2`, now, limit),
|
|
989
1032
|
async markDeclined(key, until) {
|
|
990
1033
|
await q(`UPDATE ${t} SET declined_until = ?2 WHERE key = ?1`, key, until).run();
|
|
991
1034
|
},
|
|
@@ -1003,6 +1046,50 @@ WHERE key = ?1 AND lease_id = ?2`;
|
|
|
1003
1046
|
};
|
|
1004
1047
|
}
|
|
1005
1048
|
|
|
1049
|
+
// src/sandbox/escalation-speculator.ts
|
|
1050
|
+
function parsePrewarmHint(value) {
|
|
1051
|
+
return value?.trim().toLowerCase() === "deterministic" ? "deterministic" : "off";
|
|
1052
|
+
}
|
|
1053
|
+
var DEFAULT_ESCALATION_TOOLS = ["sandbox_run", "sandbox_exec"];
|
|
1054
|
+
var PROCESS_MEDIA = /^(application\/(pdf|zip|x-zip|gzip|x-tar|vnd\.openxmlformats|vnd\.ms-excel|vnd\.oasis)|text\/(csv|x-python|x-script))/i;
|
|
1055
|
+
var PROCESS_EXTENSIONS = /\.(pdf|xlsx?|csv|tsv|ods|zip|tar|gz|py|ipynb|js|ts|sh|sql|parquet|json)$/i;
|
|
1056
|
+
var EXECUTION_WORDS = /\b(run|execute|compile|convert|parse|extract|install|script|python|notebook|spreadsheet|csv|xlsx|regex|calculate|plot|chart|test suite|build the)\b/i;
|
|
1057
|
+
function escalationHints(input) {
|
|
1058
|
+
const hints = [];
|
|
1059
|
+
if ((input.attachments ?? []).some((a) => PROCESS_MEDIA.test(a.mediaType ?? "") || PROCESS_EXTENSIONS.test(a.name ?? ""))) {
|
|
1060
|
+
hints.push("attachment");
|
|
1061
|
+
}
|
|
1062
|
+
const text = input.text ?? "";
|
|
1063
|
+
if (/```/.test(text)) hints.push("code-block");
|
|
1064
|
+
if (EXECUTION_WORDS.test(text)) hints.push("execution-words");
|
|
1065
|
+
return hints;
|
|
1066
|
+
}
|
|
1067
|
+
function createEscalationSpeculator(options) {
|
|
1068
|
+
const tools = new Set(options.escalationTools ?? DEFAULT_ESCALATION_TOOLS);
|
|
1069
|
+
let fired = null;
|
|
1070
|
+
const speculate = (hint) => {
|
|
1071
|
+
if (options.mode === "off" || fired) return;
|
|
1072
|
+
fired = hint;
|
|
1073
|
+
try {
|
|
1074
|
+
options.onSpeculate?.(hint);
|
|
1075
|
+
} catch {
|
|
1076
|
+
}
|
|
1077
|
+
void options.leases.signal(options.boxKey, "escalation-likely").catch(() => void 0);
|
|
1078
|
+
};
|
|
1079
|
+
return {
|
|
1080
|
+
onInput(input) {
|
|
1081
|
+
const hint = escalationHints(input)[0];
|
|
1082
|
+
if (hint) speculate(hint);
|
|
1083
|
+
},
|
|
1084
|
+
onEvent(event) {
|
|
1085
|
+
if (event.type === "tool_call_start" && event.toolName && tools.has(event.toolName)) speculate("tool-call-start");
|
|
1086
|
+
},
|
|
1087
|
+
get fired() {
|
|
1088
|
+
return fired;
|
|
1089
|
+
}
|
|
1090
|
+
};
|
|
1091
|
+
}
|
|
1092
|
+
|
|
1006
1093
|
// src/sandbox/index.ts
|
|
1007
1094
|
var DEFAULT_SANDBOX_DIRECT_KEY_NAMES = [
|
|
1008
1095
|
"TCLOUD_SANDBOX_API_KEY",
|
|
@@ -2889,7 +2976,12 @@ export {
|
|
|
2889
2976
|
DEFAULT_WARM_LEASE_TABLE,
|
|
2890
2977
|
WARM_LEASE_TABLE_DDL,
|
|
2891
2978
|
WARM_LEASE_DECLINED_UNTIL_DDL,
|
|
2979
|
+
WARM_LEASE_PENDING_DDL,
|
|
2892
2980
|
createD1WarmLeaseStore,
|
|
2981
|
+
parsePrewarmHint,
|
|
2982
|
+
DEFAULT_ESCALATION_TOOLS,
|
|
2983
|
+
escalationHints,
|
|
2984
|
+
createEscalationSpeculator,
|
|
2893
2985
|
resolveSandboxClientCredentials,
|
|
2894
2986
|
PYPI_EGRESS_DOMAINS,
|
|
2895
2987
|
buildProductEgressPolicy,
|
|
@@ -2943,4 +3035,4 @@ export {
|
|
|
2943
3035
|
isTerminalPromptEvent,
|
|
2944
3036
|
detectInteractiveQuestion
|
|
2945
3037
|
};
|
|
2946
|
-
//# sourceMappingURL=chunk-
|
|
3038
|
+
//# sourceMappingURL=chunk-P2EKAQUB.js.map
|