@tangle-network/agent-app 0.60.84 → 0.60.86

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.
@@ -356,6 +356,47 @@ function createTurnHealthLifecycle(options) {
356
356
  }
357
357
 
358
358
  // src/turn-health/sweep.ts
359
+ var onObject = (expr) => `CASE WHEN p.type = 'object' THEN ${expr} END`;
360
+ var textAt = (path, take = `json_extract(p.value, '${path}')`) => onObject(`CASE WHEN json_type(p.value, '${path}') = 'text' THEN ${take} END`);
361
+ var PART_PROJECTION = [
362
+ `p.type AS partKind`,
363
+ `${textAt("$.type")} AS type`,
364
+ `coalesce(${onObject(`CASE WHEN json_type(p.value, '$.text') = 'text' AND length(trim(json_extract(p.value, '$.text'), char(32, 9, 10, 13))) > 0 THEN 1 ELSE 0 END`)}, 0) AS hasText`,
365
+ `${textAt("$.tool")} AS tool`,
366
+ `${onObject(`json_type(p.value, '$.state')`)} AS stateKind`,
367
+ `${textAt("$.state.status")} AS status`,
368
+ `${textAt("$.state.error", `substr(json_extract(p.value, '$.state.error'), 1, 200)`)} AS stateError`,
369
+ `${onObject(`json_type(p.value, '$.state.input')`)} AS inputKind`,
370
+ `${textAt("$.state.input.error", `substr(json_extract(p.value, '$.state.input.error'), 1, 200)`)} AS inputError`,
371
+ `${textAt("$.state.input.tool")} AS inputTool`,
372
+ `${textAt("$.state.input", `json_valid(json_extract(p.value, '$.state.input'))`)} AS inputValid`,
373
+ `${textAt("$.state.input", `substr(json_extract(p.value, '$.state.input'), 1, 120)`)} AS inputSample`
374
+ ].join(",\n ");
375
+ function slimPart(row) {
376
+ if (row.partKind === "array") return [];
377
+ if (row.partKind !== "object") return null;
378
+ const part = {};
379
+ if (row.type !== null) part.type = row.type;
380
+ if (row.hasText) part.text = "x";
381
+ if (row.tool !== null) part.tool = row.tool;
382
+ if (row.stateKind === "object") {
383
+ const state = {};
384
+ if (row.status !== null) state.status = row.status;
385
+ if (row.stateError !== null) state.error = row.stateError;
386
+ if (row.inputKind === "object") {
387
+ const input = {};
388
+ if (row.inputError !== null) input.error = row.inputError;
389
+ if (row.inputTool !== null) input.tool = row.inputTool;
390
+ state.input = input;
391
+ } else if (row.inputKind === "text") {
392
+ state.input = row.inputValid ? "{}" : `${row.inputSample ?? ""}\0`;
393
+ } else if (row.inputKind !== null) {
394
+ state.input = null;
395
+ }
396
+ part.state = state;
397
+ }
398
+ return part;
399
+ }
359
400
  var TURN_HEALTH_PARTS_BATCH_SIZE = SIZED_READ_BYTES;
360
401
  function partsBatches(rows) {
361
402
  return sizedBatches(rows.map((row) => ({ key: row, size: row.partsSize })), { bytes: TURN_HEALTH_PARTS_BATCH_SIZE });
@@ -661,8 +702,18 @@ function createD1TurnHealthSource(db, options = {}) {
661
702
  },
662
703
  async readParts(ids) {
663
704
  if (ids.length === 0) return /* @__PURE__ */ new Map();
664
- const { results } = await db.prepare(`SELECT id, parts FROM ${message} WHERE id IN (${ids.map((_, i) => `?${i + 1}`).join(", ")})`).bind(...ids).all();
665
- return new Map(results.map((row) => [String(row.id), row.parts]));
705
+ const placeholders = ids.map((_, i) => `?${i + 1}`).join(", ");
706
+ if (options.fullParts) {
707
+ const { results: results2 } = await db.prepare(`SELECT id, parts FROM ${message} WHERE id IN (${placeholders})`).bind(...ids).all();
708
+ return new Map(results2.map((row) => [String(row.id), row.parts]));
709
+ }
710
+ const { results } = await db.prepare(`SELECT m.id AS id, CAST(p.key AS INTEGER) AS idx, ${PART_PROJECTION}
711
+ FROM ${message} m, json_each(CASE WHEN json_valid(m.parts) THEN CASE WHEN json_type(m.parts) = 'array' THEN m.parts ELSE '[]' END ELSE '[]' END) p
712
+ WHERE m.id IN (${placeholders})
713
+ ORDER BY m.id, idx`).bind(...ids).all();
714
+ const parts = new Map(ids.map((id) => [id, []]));
715
+ for (const row of results) parts.get(String(row.id))?.push(slimPart(row));
716
+ return parts;
666
717
  }
667
718
  };
668
719
  function safeIdentifier(name) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/turn-health/classify.ts","../../src/turn-health/sink.ts","../../src/turn-health/lifecycle.ts","../../src/turn-health/sweep.ts"],"sourcesContent":["/**\n * The classifier for turns that FAIL BY RETURNING SUCCESS.\n *\n * Every failure this module names shipped to a customer with HTTP 200, no\n * thrown error, and no log line anyone read. Three were measured in production\n * in a single week:\n *\n * - a turn settled `{\"outcome\":{\"type\":\"completed\"},\"finalText\":\"\",\n * \"tokenUsage\":{\"outputTokens\":0}}` — the customer saw a blank bubble;\n * - six `submit_proposal` tool calls collapsed into ONE whose arguments were\n * a 1,652-character non-JSON string, so zero proposals persisted and\n * nothing errored (agent-runtime #626);\n * - a thread took 255 user messages over 17 days and produced 2 replies,\n * both of them error text.\n *\n * A conventional health check cannot see any of these, because it probes\n * DEPENDENCIES (is the sandbox reachable, is the router up) and every one of\n * these failures happens with all dependencies green. This classifier probes\n * the OUTCOME instead.\n *\n * It is deliberately pure and structural: it reads a settled turn's own\n * projection, so the SAME function judges a live turn through the\n * `/chat-routes` lifecycle seam and a historical row read back out of the\n * store during a sweep. One definition of \"silently broken\", two call sites.\n */\n\n/** How loudly a reason should be routed. `critical` means a customer got\n * nothing usable; `warning` means the turn degraded but still produced\n * something a human could read. */\nexport type TurnHealthSeverity = 'critical' | 'warning'\n\n/** One specific way a turn returned success while failing.\n *\n * Each variant carries the evidence that identified it, so an alert can name\n * the offending value instead of asserting a verdict the reader has to take\n * on faith. */\nexport type TurnHealthReason =\n /** Settled without error and produced nothing a user can read: no text, and\n * no artifact part (file/image/work-product/plan/interaction). This is the\n * verbatim blank-completion capture. */\n | {\n kind: 'empty_completion'\n outputTokens: number | null\n partCount: number\n durationMs?: number\n }\n /** A tool call whose arguments never parsed. The engine surfaces unparseable\n * arguments as a RAW STRING rather than throwing, so the call is neither\n * dropped nor errored — it silently does nothing. Detecting a string-typed\n * tool input that fails `JSON.parse` is the exact fingerprint of the\n * index-less parallel-tool-call collapse. */\n | {\n kind: 'malformed_tool_call'\n tool: string\n inputLength: number\n /** Leading characters of the offending input, for the alert body. */\n sample: string\n }\n /** A tool call that never reached a terminal state carrying output. The call\n * was issued and then simply produced no effect. */\n | {\n kind: 'tool_call_no_effect'\n tool: string\n status: string\n }\n /** The turn failed outright. Not silent by itself — but it becomes silent\n * the moment nothing is watching, which is how 16 days of\n * `TANGLE_HUB_URL is required` reached customers unnoticed. */\n | { kind: 'turn_failed'; reason: string }\n /** A tool call the harness REJECTED, settled as `completed`.\n *\n * Found live in legal-agent production, and missed by every other rule here:\n * the model called `submit_proposal`, the harness answered \"Model tried to\n * call unavailable tool 'submit_proposal'\", and the part persisted as\n * `{\"tool\":\"invalid\",\"state\":{\"status\":\"completed\",\"input\":{\"error\":\"…\"}}}`.\n *\n * Status is `completed`, the arguments parse cleanly, and the turn has text —\n * so the blank-completion, malformed-argument and no-effect rules all pass it.\n * Six deliverables were requested and silently discarded while the product\n * reported success six times.\n *\n * Detected structurally, on the presence of an `error` in the settled state\n * rather than on any harness's name for a rejected call — `invalid` is one\n * harness's convention and must not be baked into the shell. */\n | {\n kind: 'tool_call_rejected'\n /** The tool the model was trying to reach, when the payload names it. */\n tool: string\n error: string\n }\n /** The turn was answered without the model ever running — a pre-producer gate\n * short-circuited and returned the product's own response.\n *\n * Reported as a `warning`, never `critical`: gating an unready turn is a\n * legitimate design (an intake flow SHOULD answer before spending a model\n * call). What is pathological is the RATE, which only the caller's own\n * threshold can judge — so this variant exists to be COUNTED, and alerting\n * on it is opt-in. It is the per-turn evidence behind a dead tool surface:\n * a gate that answers every turn means the agent never runs at all. */\n | { kind: 'answered_without_model' }\n /** The detector could not read this turn.\n *\n * Every part carried a type outside the vocabulary this classifier\n * understands — which is what field-level encryption at rest looks like from\n * the outside (tax-agent persists `{\"type\":\"__encrypted_parts__\"}`, its own\n * convention, and 32 of its 129 assistant rows are exactly that).\n *\n * This exists because the alternative is the bug this whole module hunts.\n * An unreadable row has no text, no artifact and no tool part, so every\n * other rule here would happily conclude \"nothing wrong\" — a detector\n * reporting health from data it cannot see. Blindness is a finding, not a\n * pass, so it gets its own reason and its own counter. */\n | { kind: 'unreadable_turn'; partTypes: string[] }\n\n/** A settled turn, in the narrowest shape both call sites can supply.\n *\n * Structural on purpose: the lifecycle seam supplies `finalText`/`usage`, a\n * store sweep supplies `content`/`parts` read back from a row, and neither\n * has to import the other's types. */\nexport interface TurnOutcomeInput {\n /** The turn's final assistant text. */\n finalText?: string | null\n /** The persisted assistant parts. Untyped by design — a sweep reads these\n * out of a JSON column and must not be forced to validate them first. */\n parts?: readonly unknown[] | null\n /** Output tokens, when the caller has usage. `null`/absent is unknown, which\n * is NOT the same as zero and is never treated as evidence. */\n outputTokens?: number | null\n /** Set when the turn surfaced a terminal error event. */\n failed?: boolean\n failureReason?: string | null\n durationMs?: number\n /** Set when a pre-producer gate answered this turn and the model never ran.\n * Supplied by `/chat-routes`' lifecycle seam, which stamps `gated` on the\n * completion it now fires for a `contextGate` short-circuit. */\n gated?: boolean\n}\n\n/** The verdict for one turn. `healthy` is exactly `reasons.length === 0`, kept\n * as a field so callers read intent rather than an array length. */\nexport interface TurnHealthVerdict {\n healthy: boolean\n severity: TurnHealthSeverity | null\n reasons: TurnHealthReason[]\n /** How many tool parts this turn carried.\n *\n * Zero is NOT a per-turn defect — plenty of good turns answer from context\n * without touching a tool, and paging on each one would be pure noise. It is\n * reported so a WINDOW can be judged: a product whose deliverable is tool\n * output and which produced zero tool calls across every turn in the\n * lookback has a dead tool surface, and that is the shape no per-turn rule\n * can see.\n *\n * Only meaningful alongside {@link interpretedParts} > 0. Zero tool calls\n * read off a row that persisted NO parts is not an observation about the\n * tool surface — it is the absence of one. */\n toolCalls: number\n /** True when nothing about this turn could be judged — no interpretable part\n * AND no visible text. Callers MUST exclude these from any healthy/unhealthy\n * ratio, because counting an unreadable turn as healthy is how a detector\n * reports green on data it never read. */\n unreadable: boolean\n /** False when this turn carried parts that could not be interpreted.\n *\n * Separate from {@link unreadable} because the two blindnesses have\n * different consequences, and production has a row that is one but not the\n * other: tax-agent persists CIPHERTEXT as `content` alongside an encrypted\n * `parts` blob, so the turn plainly delivered something (there is text) while\n * its tool calls are completely invisible.\n *\n * Any conclusion ABOUT TOOLS — above all the dead-tool-surface verdict — may\n * only be drawn over turns where this is true. Reading \"no tool parts\" off an\n * encrypted blob and declaring the tool surface dead would be the same\n * crime as declaring it healthy: a finding asserted from data never read. */\n partsReadable: boolean\n /** The part types that could not be interpreted. Empty when\n * {@link partsReadable}. Named in the alert so a reader can see EXACTLY what\n * the detector was blind to instead of taking \"unreadable\" on faith. */\n opaquePartTypes: string[]\n /** How many parts this module actually READ (text, artifact, tool, or a known\n * non-output kind).\n *\n * The third blindness, and the one that shipped a false page. `partsReadable`\n * only says nothing was *uninterpretable*; a row that persisted NO parts at\n * all satisfies that vacuously. Production: 97 of tax-agent's 156 assistant\n * rows predate parts persistence entirely and store `[]`, and reading \"zero\n * tool calls\" off them raised a critical `dead_tool_surface` against a\n * product whose own `turn_events` table holds 243 `tool_call` frames.\n *\n * So a tool verdict requires BOTH `partsReadable` AND this being > 0 —\n * evidence that was read, not merely evidence that failed to be unreadable. */\n interpretedParts: number\n}\n\n/** Part kinds that count as something a user actually receives.\n *\n * A tool part is deliberately NOT here. A turn that ran six tools and said\n * nothing, with no artifact to show for it, is the malformed-tool-call\n * disaster — counting a tool chip as output would suppress the very alert\n * this module exists to raise. */\nconst ARTIFACT_PART_KINDS = new Set(['file', 'image', 'work-product', 'plan', 'interaction'])\n\n/** Part types that carry no user-visible output but ARE understood.\n *\n * The distinction matters: a turn made of nothing but `reasoning` parts\n * thought hard and said nothing, which is a real empty completion. A turn made\n * of types this module has never heard of is a turn it cannot read. Only the\n * second is blindness — so these are enumerated rather than lumped in with the\n * unknown.\n *\n * Grounded in what the fleet actually persists, not guessed: a scan of every\n * assistant part in the gtm / legal / tax production tables returns exactly\n * `tool` (138), `text` (69), `reasoning` (26), `step-start` (3),\n * `step-finish` (3) and tax's opaque `__encrypted_parts__` (32). */\nconst KNOWN_NON_OUTPUT_PART_KINDS = new Set([\n 'reasoning',\n 'step-start',\n 'step-finish',\n 'source',\n 'source-url',\n 'data',\n])\n\nconst SAMPLE_CHARS = 120\n\nfunction asRecord(value: unknown): Record<string, unknown> | null {\n return typeof value === 'object' && value !== null ? (value as Record<string, unknown>) : null\n}\n\nfunction nonEmptyString(value: unknown): string | null {\n return typeof value === 'string' && value.trim().length > 0 ? value : null\n}\n\n/** True when a string is not parseable JSON.\n *\n * Only meaningful for tool INPUT, where the engine's contract is that a\n * well-formed call carries an object (or a string that parses into one). A\n * string that fails to parse means the arguments were concatenated or\n * truncated upstream. */\nfunction isUnparseableJson(value: string): boolean {\n const trimmed = value.trim()\n if (trimmed.length === 0) return false\n try {\n JSON.parse(trimmed)\n return false\n } catch {\n return true\n }\n}\n\n/** Tool statuses that mean the call actually landed.\n *\n * Anything else — `pending`, `running`, `error`, an unknown string — left no\n * persisted effect by the time the turn settled. */\nconst SETTLED_TOOL_STATUSES = new Set(['completed', 'complete', 'success', 'done'])\n\n/**\n * Judge one settled turn.\n *\n * Never throws: a malformed `parts` blob is a thing this function REPORTS on,\n * so it must not be a thing it dies on. Telemetry that can crash the turn it\n * measures is worse than no telemetry.\n */\nexport function classifyTurnOutcome(input: TurnOutcomeInput): TurnHealthVerdict {\n const reasons: TurnHealthReason[] = []\n\n if (input.failed) {\n reasons.push({\n kind: 'turn_failed',\n reason: nonEmptyString(input.failureReason) ?? 'unspecified',\n })\n }\n\n const parts = Array.isArray(input.parts) ? input.parts : []\n\n let hasVisibleText = nonEmptyString(input.finalText) !== null\n let artifactCount = 0\n let toolCalls = 0\n // Part types this module could not interpret. Tracked so blindness can be\n // reported as blindness instead of silently reading as health.\n const opaqueTypes: string[] = []\n let interpretedParts = 0\n\n for (const raw of parts) {\n const part = asRecord(raw)\n if (!part) continue\n const type = typeof part.type === 'string' ? part.type : ''\n\n if (type === 'text') {\n interpretedParts += 1\n if (nonEmptyString(part.text) !== null) hasVisibleText = true\n continue\n }\n if (ARTIFACT_PART_KINDS.has(type)) {\n interpretedParts += 1\n artifactCount += 1\n continue\n }\n if (KNOWN_NON_OUTPUT_PART_KINDS.has(type)) {\n interpretedParts += 1\n continue\n }\n if (type !== 'tool') {\n opaqueTypes.push(type || '(missing type)')\n continue\n }\n interpretedParts += 1\n toolCalls += 1\n\n const tool = nonEmptyString(part.tool) ?? 'unknown'\n const state = asRecord(part.state)\n const status = typeof state?.status === 'string' ? state.status : 'unknown'\n\n // The #626 fingerprint: arguments surfaced as a raw string because they\n // failed to parse upstream. Checked before the status gate — a malformed\n // call can still be marked completed, which is precisely why it is silent.\n // A rejected call settles as `completed` and carries its rejection in the\n // state. Checked BEFORE the status gate for the same reason as the\n // malformed case: the status is exactly what makes it silent.\n const toolInput = state?.input\n const inputRecord = asRecord(toolInput)\n const rejection =\n nonEmptyString(inputRecord?.error) ?? nonEmptyString((state as Record<string, unknown>)?.error)\n if (rejection) {\n reasons.push({\n kind: 'tool_call_rejected',\n // The payload names the tool the model MEANT to call; the part's own\n // `tool` is the harness's placeholder for a rejected call.\n tool: nonEmptyString(inputRecord?.tool) ?? tool,\n error: rejection.slice(0, 200),\n })\n continue\n }\n if (typeof toolInput === 'string' && isUnparseableJson(toolInput)) {\n reasons.push({\n kind: 'malformed_tool_call',\n tool,\n inputLength: toolInput.length,\n sample: toolInput.slice(0, SAMPLE_CHARS),\n })\n continue\n }\n\n if (!SETTLED_TOOL_STATUSES.has(status)) {\n reasons.push({ kind: 'tool_call_no_effect', tool, status })\n }\n }\n\n // A turn whose parts were ALL uninterpretable cannot be judged. Reported as\n // blindness and returned early, because every rule below would otherwise read\n // \"no text, no artifact\" off data that was simply encrypted and call it a\n // blank completion — a false page that would train readers to ignore this\n // module, which is the same ending as no detector at all.\n const partsReadable = opaqueTypes.length === 0\n const uniqueOpaque = [...new Set(opaqueTypes)]\n const unreadable = opaqueTypes.length > 0 && interpretedParts === 0 && !hasVisibleText\n if (unreadable) {\n reasons.push({ kind: 'unreadable_turn', partTypes: uniqueOpaque })\n return {\n healthy: false,\n severity: 'warning',\n reasons,\n toolCalls,\n unreadable: true,\n partsReadable: false,\n opaquePartTypes: uniqueOpaque,\n // Structurally 0 here — `unreadable` is only reached when\n // `interpretedParts === 0`. Carried rather than hardcoded so the field\n // has one source on every return path.\n interpretedParts,\n }\n }\n\n // A gate answered before the producer ran. Recorded rather than judged: see\n // `answered_without_model`. It also SUPPRESSES the empty-completion rule\n // below — the model producing no text is the expected outcome when the model\n // never ran, and firing `empty_completion` here would page on every healthy\n // intake turn.\n if (input.gated) {\n reasons.push({ kind: 'answered_without_model' })\n } else if (!input.failed && !hasVisibleText && artifactCount === 0) {\n // `outputTokens` is corroborating evidence, never the trigger: a turn can\n // spend tokens on reasoning and still deliver nothing, and a turn with\n // unknown usage can still be perfectly fine.\n reasons.push({\n kind: 'empty_completion',\n outputTokens: input.outputTokens ?? null,\n partCount: parts.length,\n ...(input.durationMs !== undefined ? { durationMs: input.durationMs } : {}),\n })\n }\n\n return {\n healthy: reasons.length === 0,\n severity: severityOf(reasons),\n reasons,\n toolCalls,\n unreadable: false,\n partsReadable,\n opaquePartTypes: uniqueOpaque,\n interpretedParts,\n }\n}\n\n/** `critical` when the customer got nothing usable out of the turn. A\n * malformed tool call alongside readable text is a `warning` — degraded, but\n * a human still received an answer. */\nfunction severityOf(reasons: TurnHealthReason[]): TurnHealthSeverity | null {\n if (reasons.length === 0) return null\n // A rejected tool call is critical even alongside readable prose: the\n // customer got words where they should have got a filed deliverable.\n const critical = reasons.some(\n (r) =>\n r.kind === 'empty_completion' ||\n r.kind === 'turn_failed' ||\n r.kind === 'tool_call_rejected',\n )\n return critical ? 'critical' : 'warning'\n}\n\n/** One-line human summary of a reason, for an alert body. */\nexport function describeReason(reason: TurnHealthReason): string {\n switch (reason.kind) {\n case 'empty_completion':\n return `completed with NO output (${reason.partCount} parts, outputTokens=${\n reason.outputTokens ?? 'unknown'\n })`\n case 'malformed_tool_call':\n return `tool \\`${reason.tool}\\` arguments did not parse (${reason.inputLength} chars): ${reason.sample}`\n case 'tool_call_no_effect':\n return `tool \\`${reason.tool}\\` left no effect (status=${reason.status})`\n case 'turn_failed':\n return `turn failed: ${reason.reason}`\n case 'tool_call_rejected':\n return `tool \\`${reason.tool}\\` was REJECTED but settled as completed: ${reason.error}`\n case 'answered_without_model':\n return 'answered by a pre-producer gate — the model never ran'\n case 'unreadable_turn':\n return `turn could not be read: every part had an uninterpretable type (${reason.partTypes.join(\n ', ',\n )})`\n }\n}\n","/**\n * Where a silent-failure verdict GOES.\n *\n * The detection half is worthless without this half. Every failure this module\n * finds was already visible in the database the whole time — 255 unanswered\n * messages sat in a table for 17 days. What was missing was not the data, it\n * was delivery to a human who had not thought to look.\n *\n * So the sink is a seam, not a channel: the product supplies the transport,\n * and agent-app ships the two shapes the fleet already has credentials for\n * (an ops webhook, and stderr). No new channel is invented here.\n */\n\nimport { postSlackAlert } from '../alerting/slack.js'\nimport { describeReason, type TurnHealthReason, type TurnHealthSeverity } from './classify.js'\n\n/** One deliverable alert. */\nexport interface TurnHealthAlert {\n /** Which product raised it (`projectId`). Alerts from four products land in\n * one channel, so this is what makes the message actionable. */\n product: string\n severity: TurnHealthSeverity\n /** Stable grouping key. Throttling is keyed on this, so it must NOT contain\n * a turn id or a timestamp or every alert is unique and nothing dedupes. */\n key: string\n title: string\n /** Human-readable lines. */\n details: string[]\n /** Structured payload for a machine consumer. */\n data?: Record<string, unknown>\n at: number\n}\n\n/** Deliver an alert. Implementations MUST NOT throw — see\n * {@link createGuardedAlertSink}. */\nexport interface AlertSink {\n deliver(alert: TurnHealthAlert): Promise<void>\n}\n\n/** Build the alert for a set of reasons found on one turn. */\nexport function turnAlert(input: {\n product: string\n severity: TurnHealthSeverity\n reasons: TurnHealthReason[]\n threadId?: string\n turnId?: string\n model?: string\n at?: number\n}): TurnHealthAlert {\n const kinds = [...new Set(input.reasons.map((r) => r.kind))].sort()\n return {\n product: input.product,\n severity: input.severity,\n // Keyed by product + reason kinds ONLY. A blank-completion storm across\n // 200 turns is one incident, not 200 pages.\n key: `turn:${input.product}:${kinds.join('+')}`,\n title: `${input.product}: turn completed but delivered nothing (${kinds.join(', ')})`,\n details: input.reasons.map(describeReason),\n data: {\n kinds,\n ...(input.threadId ? { threadId: input.threadId } : {}),\n ...(input.turnId ? { turnId: input.turnId } : {}),\n ...(input.model ? { model: input.model } : {}),\n },\n at: input.at ?? Date.now(),\n }\n}\n\n// ── transports ────────────────────────────────────────────────────────────\n\n/** Minimal structural fetch, so this module has no lib-dom dependency and can\n * be driven by a fake in tests. */\nexport type FetchLike = (\n url: string,\n init: { method: string; headers: Record<string, string>; body: string },\n) => Promise<{ ok: boolean; status: number; text?(): Promise<string> }>\n\n/**\n * POST to an incoming webhook in the Slack message format.\n *\n * Chosen because the org already runs one (`SLACK_OPS_WEBHOOK_URL`) and\n * gtm-agent's outbound webhook code already speaks this exact shape — the\n * instruction was to route somewhere humans already look, not to stand up a\n * new channel. Discord and most log drains accept the same `{text}` body.\n */\nexport function createWebhookAlertSink(options: {\n webhookUrl: string\n fetchImpl?: FetchLike\n}): AlertSink {\n const fetchImpl = options.fetchImpl ?? (globalThis.fetch as unknown as FetchLike)\n return {\n async deliver(alert) {\n const icon = alert.severity === 'critical' ? ':rotating_light:' : ':warning:'\n const lines = [\n `${icon} *${alert.title}*`,\n ...alert.details.map((d) => `• ${d}`),\n `_${new Date(alert.at).toISOString()}_`,\n ]\n const response = await fetchImpl(options.webhookUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ text: lines.join('\\n') }),\n })\n if (!response.ok) {\n // A dropped alert is a silent failure of the silent-failure detector.\n // It must be loud in the one place that is still working: the log.\n throw new Error(`alert webhook responded ${response.status}`)\n }\n },\n }\n}\n\n/**\n * POST to Slack `chat.postMessage` with a bot token.\n *\n * This is the transport the org actually has. A survey of the four product\n * repos found NO ops alert path of any kind — no incoming webhook, no pager, no\n * notifier — which is the mechanical reason a 17-day outage never reached a\n * human. What does exist is a Slack bot token in the shared secrets store, and\n * `@tangle-network/agent-integrations` already speaks this exact API, so this\n * routes alerts through the channel the org runs rather than standing up a new\n * one.\n *\n * Slack answers `200 OK` with `{\"ok\": false, \"error\": \"...\"}` for an invalid\n * token or channel, so the body is checked and not just the status — a\n * transport that reports success on a rejected post would make the alerter\n * itself a silent failure.\n */\nexport function createSlackBotAlertSink(options: {\n botToken: string\n channel: string\n fetchImpl?: FetchLike\n}): AlertSink {\n const fetchImpl = options.fetchImpl ?? (globalThis.fetch as unknown as FetchLike)\n return {\n async deliver(alert) {\n const icon = alert.severity === 'critical' ? ':rotating_light:' : ':warning:'\n const lines = [\n `${icon} *${alert.title}*`,\n ...alert.details.map((d) => `• ${d}`),\n `_${new Date(alert.at).toISOString()}_`,\n ]\n const outcome = await postSlackAlert({\n token: options.botToken, channel: options.channel, text: lines.join('\\n'), attempts: 1,\n // Preserve the public minimal-fetch seam without owning a second Slack\n // request builder or response parser. Real callers use native fetch.\n fetchImpl: options.fetchImpl ? (async (url, init) => {\n const response = await fetchImpl(String(url), {\n method: init?.method ?? 'POST',\n headers: Object.fromEntries(new Headers(init?.headers)),\n body: String(init?.body ?? ''),\n })\n return new Response(await response.text?.() ?? '', { status: response.status })\n }) : undefined,\n })\n if (!outcome.delivered) throw new Error(`Slack alert failed (${outcome.reason}): ${outcome.detail}`)\n },\n }\n}\n\n/** stderr sink. The zero-config fallback so a product that has not yet been\n * given a webhook still emits something a log search can find. */\nexport function createConsoleAlertSink(log: (message: string) => void = console.error): AlertSink {\n return {\n async deliver(alert) {\n log(\n `[turn-health] ${alert.severity.toUpperCase()} ${alert.title} :: ${alert.details.join(' | ')}`,\n )\n },\n }\n}\n\n/** Fan out to several sinks. One failing transport must not stop the others. */\nexport function createMultiAlertSink(sinks: readonly AlertSink[]): AlertSink {\n return {\n async deliver(alert) {\n const settled = await Promise.allSettled(sinks.map((s) => s.deliver(alert)))\n const failures = settled.filter((r) => r.status === 'rejected')\n if (failures.length === sinks.length && sinks.length > 0) {\n throw new Error('every alert sink failed')\n }\n },\n }\n}\n\n// ── throttling ────────────────────────────────────────────────────────────\n\n/** Records the last time a key was alerted on. A product backs this with KV,\n * D1, or a Durable Object; the in-memory default is correct for a sweep that\n * runs as a single cron invocation. */\nexport interface AlertThrottleStore {\n lastSentAt(key: string): Promise<number | null>\n markSent(key: string, at: number): Promise<void>\n}\n\n/** Process-local throttle store. */\nexport function createMemoryThrottleStore(): AlertThrottleStore {\n const seen = new Map<string, number>()\n return {\n async lastSentAt(key) {\n return seen.get(key) ?? null\n },\n async markSent(key, at) {\n seen.set(key, at)\n },\n }\n}\n\n/**\n * Collapse repeats of the same `key` inside `windowMs`.\n *\n * Deliberately re-alerts once per window rather than going silent after the\n * first: an incident that is still burning must keep saying so. Going quiet\n * after one message is how a 17-day outage stays invisible after someone\n * dismisses the first notification.\n */\nexport function createThrottledAlertSink(\n inner: AlertSink,\n options: { windowMs: number; store?: AlertThrottleStore },\n): AlertSink {\n const store = options.store ?? createMemoryThrottleStore()\n return {\n async deliver(alert) {\n const last = await store.lastSentAt(alert.key)\n if (last !== null && alert.at - last < options.windowMs) return\n await inner.deliver(alert)\n await store.markSent(alert.key, alert.at)\n },\n }\n}\n\n/**\n * Swallow transport errors so telemetry can never fail the turn it measures.\n *\n * Use this at the LIVE lifecycle call site only. A sweep should let the error\n * surface, because a sweep that cannot deliver has done nothing at all and its\n * cron run should go red.\n */\nexport function createGuardedAlertSink(\n inner: AlertSink,\n onError: (error: unknown) => void = (e) => console.error('[turn-health] alert delivery failed', e),\n): AlertSink {\n return {\n async deliver(alert) {\n try {\n await inner.deliver(alert)\n } catch (error) {\n onError(error)\n }\n },\n }\n}\n","/**\n * The LIVE half: judge each turn the moment it settles.\n *\n * This adds no control flow. `createChatTurnRoutes` already exposes a\n * `lifecycle` seam that fires exactly one of `onTurnComplete`/`onTurnError`\n * after a turn settles, and already swallows hook errors so telemetry cannot\n * fail a turn. That seam was shipped and then wired by nobody, which is a fair\n * description of why the outage lasted 17 days. This function fills it.\n *\n * The shape is declared structurally rather than imported from\n * `/chat-routes`, so `/turn-health` stays free of the server chat vertical and\n * can be used by any turn driver that reports the same three moments.\n */\n\nimport { classifyTurnOutcome } from './classify.js'\nimport { type AlertSink, createGuardedAlertSink, turnAlert } from './sink.js'\n\n/** Structural mirror of `/chat-routes`' `ChatTurnLifecycle` complete payload. */\nexport interface TurnHealthCompleteInfo {\n finalText: string\n usage?: { outputTokens?: number | null } | null\n durationMs: number\n threadId?: string\n turnStreamId?: string\n executionId?: string\n /** `/chat-routes` sets this when a `contextGate` short-circuited the turn and\n * the producer never ran. */\n gated?: boolean\n}\n\n/** Structural mirror of the lifecycle error payload. */\nexport interface TurnHealthErrorInfo {\n error: unknown\n durationMs: number\n threadId?: string\n turnStreamId?: string\n executionId?: string\n}\n\n/** What {@link createTurnHealthLifecycle} returns — assignable to\n * `createChatTurnRoutes`' `lifecycle` option. */\nexport interface TurnHealthLifecycle {\n onTurnComplete(info: TurnHealthCompleteInfo): Promise<void>\n onTurnError(info: TurnHealthErrorInfo): Promise<void>\n}\n\nexport interface TurnHealthLifecycleOptions {\n /** Names the product in every alert. */\n product: string\n sink: AlertSink\n /** Called for every verdict, healthy or not — the hook for a counter or a\n * metrics push. Alerts are for humans; this is for graphs. */\n onVerdict?(verdict: {\n product: string\n healthy: boolean\n kinds: string[]\n durationMs: number\n }): void\n /** Page when a turn was answered by a gate instead of the model.\n *\n * Default `false`, and the default is the honest one: gating is a legitimate\n * design and a product that gates its intake would otherwise page on every\n * healthy turn. Whether the rate is pathological is domain knowledge, so it\n * stays a product decision — the verdict is ALWAYS reported through\n * {@link TurnHealthLifecycleOptions.onVerdict} so a counter can watch the\n * rate even when nobody is paged. */\n alertOnGatedTurn?: boolean\n}\n\nfunction errorText(error: unknown): string {\n if (error instanceof Error) return error.message\n if (typeof error === 'string') return error\n return String(error)\n}\n\n/**\n * Build the lifecycle hooks that page on a turn which succeeded at nothing.\n *\n * The live lane sees `finalText` and usage but not the persisted parts, so it\n * catches the blank-completion and hard-failure shapes immediately. The\n * parts-dependent shapes (a tool call whose arguments never parsed, a tool\n * call that left no effect) are caught by {@link sweepSilentFailures}, which\n * reads what was actually written to the store — the honest place to ask\n * whether an effect persisted.\n */\nexport function createTurnHealthLifecycle(\n options: TurnHealthLifecycleOptions,\n): TurnHealthLifecycle {\n // Guarded: a paging failure must never take down a customer's turn.\n const sink = createGuardedAlertSink(options.sink)\n\n return {\n async onTurnComplete(info) {\n const verdict = classifyTurnOutcome({\n finalText: info.finalText,\n outputTokens: info.usage?.outputTokens ?? null,\n durationMs: info.durationMs,\n ...(info.gated ? { gated: true } : {}),\n })\n options.onVerdict?.({\n product: options.product,\n healthy: verdict.healthy,\n kinds: verdict.reasons.map((r) => r.kind),\n durationMs: info.durationMs,\n })\n if (verdict.healthy || verdict.severity === null) return\n // Counted above, paged only on request — see `alertOnGatedTurn`.\n if (!options.alertOnGatedTurn && verdict.reasons.every((r) => r.kind === 'answered_without_model')) {\n return\n }\n await sink.deliver(\n turnAlert({\n product: options.product,\n severity: verdict.severity,\n reasons: verdict.reasons,\n ...(info.threadId ? { threadId: info.threadId } : {}),\n ...(info.executionId ? { turnId: info.executionId } : {}),\n }),\n )\n },\n\n async onTurnError(info) {\n const verdict = classifyTurnOutcome({\n failed: true,\n failureReason: errorText(info.error),\n durationMs: info.durationMs,\n })\n options.onVerdict?.({\n product: options.product,\n healthy: false,\n kinds: verdict.reasons.map((r) => r.kind),\n durationMs: info.durationMs,\n })\n await sink.deliver(\n turnAlert({\n product: options.product,\n severity: 'critical',\n reasons: verdict.reasons,\n ...(info.threadId ? { threadId: info.threadId } : {}),\n ...(info.executionId ? { turnId: info.executionId } : {}),\n }),\n )\n },\n }\n}\n","/**\n * The SWEEP half: ask the store what it has been quietly accumulating.\n *\n * A live per-turn hook cannot see the failure that matters most, because the\n * worst outage produced NO turns at all to hook: gtm-agent took 9–21 user\n * messages a day for sixteen straight days and wrote zero real assistant\n * replies. Nothing crashed on a schedule; the product simply stopped\n * answering. The only thing that could have noticed is something that\n * periodically counts what arrived against what was answered.\n *\n * That is this. It runs on a cron, reads the shared `/chat-store` schema, and\n * pages when the ratio breaks.\n *\n * The queries live HERE and not in each product because all four products\n * (gtm, tax, legal, workcomp) persist to the same `message`/`thread` tables —\n * four copies of this cron is exactly the duplication the repo's engine/shell\n * rule exists to prevent.\n */\n\nimport { classifyTurnOutcome, describeReason, type TurnHealthReason } from './classify.js'\nimport type { AlertSink, TurnHealthAlert } from './sink.js'\nimport { SIZED_READ_BYTES, sizedBatches } from '../launch-invariants/sized-reads.js'\n\n/** A thread that has taken user messages with no reply since. */\nexport interface UnansweredThread {\n threadId: string\n /** User messages newer than the newest real assistant reply. */\n pendingMessages: number\n /** Age of the OLDEST unanswered user message, in ms. */\n oldestAgeMs: number\n}\n\n/** A persisted assistant row, as the sweep needs to judge it. */\nexport interface PersistedTurnRow {\n id: string\n threadId: string\n content: string\n /** Raw `parts` column. A JSON string or an already-parsed array; the sweep\n * accepts both because D1 drivers differ. Left undefined by a source that\n * lists rows by {@link partsSize} and serves parts through\n * {@link TurnHealthSource.readParts}. */\n parts: unknown\n /** Stored length of `parts` (SQLite `length()`), set when the row was listed\n * without them. The sweep batches {@link TurnHealthSource.readParts} by it. */\n partsSize?: number | null\n outputTokens?: number | null\n model?: string | null\n createdAt: number\n}\n\n/** What the sweep needs from a store. A product on a non-standard schema\n * implements these two reads; everything else is shared. */\nexport interface TurnHealthSource {\n findUnansweredThreads(input: {\n minAgeMs: number\n /** Ignore user messages older than this. See {@link SweepOptions.maxAgeMs}. */\n maxAgeMs: number\n now: number\n }): Promise<UnansweredThread[]>\n listRecentAssistantTurns(input: { sinceMs: number; now: number; limit: number }): Promise<\n PersistedTurnRow[]\n >\n /**\n * The stored `parts` of these rows, by id, for a source that lists rows\n * without them. The sweep asks for at most {@link TURN_HEALTH_PARTS_BATCH_SIZE}\n * of parts at a time and judges each batch before it reads the next, so memory\n * holds one batch rather than the whole window.\n *\n * On 2026-10-10 gtm-agent's 500 newest assistant rows carried 122 MB of\n * parts (the largest 2.8 MB). Read in one query they exceeded the Worker's\n * 128 MB, which stopped the hourly cron and every sweep queued after this one.\n */\n readParts?(ids: readonly string[]): Promise<Map<string, unknown>>\n}\n\n/** Most stored parts the sweep reads in one batch; a larger row is read alone. */\nexport const TURN_HEALTH_PARTS_BATCH_SIZE = SIZED_READ_BYTES\n\n/** Consecutive rows whose listed parts size fits one read. */\nfunction partsBatches(rows: readonly PersistedTurnRow[]): PersistedTurnRow[][] {\n return sizedBatches(rows.map((row) => ({ key: row, size: row.partsSize })), { bytes: TURN_HEALTH_PARTS_BATCH_SIZE })\n}\n\n/** The listed rows with their parts, read one batch at a time when the source listed them without. */\nasync function* withParts(rows: readonly PersistedTurnRow[], source: TurnHealthSource): AsyncGenerator<PersistedTurnRow> {\n for (const batch of partsBatches(rows)) {\n const unread = batch.filter((row) => row.parts === undefined && (row.partsSize ?? 0) > 0).map((row) => row.id)\n // A read failure propagates, like the listing's, so the caller retries the sweep.\n const read = unread.length > 0 && source.readParts ? await source.readParts(unread) : null\n for (const row of batch) yield read?.has(row.id) ? { ...row, parts: read.get(row.id) } : row\n }\n}\n\nexport interface SweepOptions {\n product: string\n source: TurnHealthSource\n sink: AlertSink\n /** A user message must go unanswered this long before it counts. Guards\n * against alerting on a turn that is simply still streaming. Default 15 min. */\n minAgeMs?: number\n /**\n * A user message OLDER than this is abandoned, not unanswered — it stops\n * counting. Default 7 days.\n *\n * Without this bound the sweep is worse than useless. gtm-agent's table\n * holds 384 unanswered messages whose oldest is 1,676 h (70 days) old;\n * paging hourly on a backlog nobody will ever reply to is exactly how an\n * alert channel gets muted, and a muted channel is the state this module\n * exists to escape. The alert has to mean \"something broke recently\".\n */\n maxAgeMs?: number\n /** How far back to judge settled turns. Default 24 h. */\n lookbackMs?: number\n /** Cap on rows judged per sweep. Default 500. */\n limit?: number\n /** Fraction of recent turns allowed to be silently broken before paging.\n * Default 0.05 — the measured blank-completion rate on the tax tool surface\n * was 12.2%, so 5% separates a real regression from noise. */\n emptyRateThreshold?: number\n /** Absolute floor: never page on a rate computed from fewer turns than this. */\n minTurnsForRate?: number\n /** Declare that this product's deliverable comes from TOOL calls, which\n * switches on the dead-tool-surface detector.\n *\n * Opt-in because only the product knows: a copilot that answers from context\n * is perfectly healthy with zero tool calls, while an agent whose entire job\n * is to file, draft, or submit something is broken the moment its tool\n * surface goes quiet — and broken INVISIBLY, because every turn still\n * returns fluent prose and HTTP 200.\n *\n * This is the fourth failure shape, and the only one no per-turn rule can\n * see.\n *\n * The verdict is drawn ONLY over turns whose parts were present and\n * readable. An earlier revision counted rows that stored no parts, and the\n * production example this comment used to cite was that bug rather than a\n * finding: tax-agent's 97 parts-less rows all predate its parts persistence\n * (they stop at 2026-07-17T02:20Z, the encrypted rows start 02:58Z), while\n * the same database's `turn_events` table holds 243 `tool_call` frames over\n * 15 turns. The tool surface was never dead; the rows were empty. */\n expectsToolCalls?: boolean\n /** Turns needed before a dead tool surface is called. Default 10. */\n minTurnsForToolSurface?: number\n /**\n * Make an at-rest parts encoding readable, so this sweep can judge a product\n * that does not store parts in the clear.\n *\n * Without it, a product that encrypts `parts` (tax-agent wraps the whole\n * array in one `__encrypted_parts__` part) is permanently UNMEASURABLE by the\n * tool-surface rule: every row is opaque, so the honest verdict is \"cannot\n * certify\" forever. This seam is how such a product gets a real verdict\n * instead of permanent blindness — the sweep stays domain-free and the\n * product supplies the decoder.\n *\n * Return the decoded parts value (it is parsed exactly like a stored one).\n * Returning `null`/`undefined` or THROWING leaves the row's stored value in\n * place, so a decoder that fails reports the row as opaque. It must never\n * report success as an empty array: that manufactures the exact absent-parts\n * blindness this module now refuses to draw conclusions from.\n */\n decodeParts?: (raw: unknown, row: PersistedTurnRow) => Promise<unknown> | unknown\n now?: number\n}\n\n/** Apply the optional decoder, falling back to the stored value on any failure\n * so a broken decoder degrades to blindness (reported) rather than to a fake\n * empty parts array (silent). */\nasync function decodeRowParts(\n decode: SweepOptions['decodeParts'],\n row: PersistedTurnRow,\n): Promise<unknown> {\n if (!decode) return row.parts\n try {\n const decoded = await decode(row.parts, row)\n return decoded ?? row.parts\n } catch {\n return row.parts\n }\n}\n\n/** What the sweep found. Returned as well as alerted, so a cron can log it and\n * a test can assert on it. */\nexport interface SweepResult {\n product: string\n unansweredThreads: number\n pendingUserMessages: number\n oldestUnansweredMs: number\n turnsJudged: number\n unhealthyTurns: number\n emptyCompletions: number\n malformedToolCalls: number\n toolCallsWithoutEffect: number\n /** Tool calls the harness rejected while settling them as `completed`. */\n rejectedToolCalls: number\n /** Turns carrying at least one tool part. */\n turnsWithToolCalls: number\n /** Total tool parts across the window. */\n toolCalls: number\n /** Turns the classifier could not interpret at all (encrypted at rest, or a\n * part vocabulary this module does not know). These are EXCLUDED from\n * `turnsJudged`-based rates — a rate computed over rows nobody could read is\n * a fabricated number. */\n unreadableTurns: number\n /** Turns whose PARTS could not be interpreted. A superset of\n * {@link unreadableTurns} (a row can have readable text and opaque parts).\n * No tool verdict is drawn over these. */\n opaquePartsTurns: number\n /** Turns that persisted NO parts at all. Distinct from\n * {@link opaquePartsTurns}: nothing failed to parse, there was simply\n * nothing there. Also excluded from every tool verdict. */\n noPartsTurns: number\n /** Turns a tool verdict may actually be drawn from — parts present AND\n * interpretable. The denominator behind `dead_tool_surface`. */\n toolReadableTurns: number\n alerts: TurnHealthAlert[]\n}\n\nfunction parseParts(raw: unknown): unknown[] {\n if (Array.isArray(raw)) return raw\n if (typeof raw !== 'string' || raw.trim().length === 0) return []\n try {\n const parsed = JSON.parse(raw)\n return Array.isArray(parsed) ? parsed : []\n } catch {\n // A parts column that is not JSON is itself a corruption worth seeing, but\n // it is not this detector's job — treat as no parts rather than throwing.\n return []\n }\n}\n\nconst HOUR_MS = 3_600_000\n\n/**\n * Assistant-row openers agent-app writes ITSELF when a sandbox turn fails.\n *\n * Kept byte-identical to the strings `createSandboxChatProducer` composes\n * (`src/chat-routes/sandbox-producer.ts`). They are shell vocabulary, not\n * product domain, so recognising them is this package's job — a product on\n * the shared producer gets a correct sweep with no configuration.\n *\n * `tests/turn-health/turn-health.test.ts` pins these against the producer, so\n * changing the producer's wording without changing this list fails CI rather\n * than silently making dead threads look answered.\n */\n/** D1's maximum LIKE pattern length, including the trailing `%`. Measured, not\n * documented: 50 succeeds, 51 raises `SQLITE_ERROR: LIKE or GLOB pattern too\n * complex`. */\nexport const D1_MAX_LIKE_PATTERN_LENGTH = 50\n\nexport const SHELL_ERROR_REPLY_PREFIXES: readonly string[] = [\n 'The sandbox model stream stopped before a clean completion.',\n 'The sandbox agent returned an error before producing a visible answer.',\n]\n\n/**\n * Run one sweep and deliver whatever it finds.\n *\n * Errors from the sink are NOT swallowed here (unlike the live lane): a sweep\n * that could not deliver has accomplished nothing, and its cron invocation\n * should go red rather than report a clean run.\n */\nexport async function sweepSilentFailures(options: SweepOptions): Promise<SweepResult> {\n const now = options.now ?? Date.now()\n const minAgeMs = options.minAgeMs ?? 15 * 60_000\n const maxAgeMs = options.maxAgeMs ?? 7 * 24 * HOUR_MS\n const lookbackMs = options.lookbackMs ?? 24 * HOUR_MS\n const limit = options.limit ?? 500\n const emptyRateThreshold = options.emptyRateThreshold ?? 0.05\n const minTurnsForRate = options.minTurnsForRate ?? 10\n const minTurnsForToolSurface = options.minTurnsForToolSurface ?? 10\n // Half the window opaque means the sweep is guessing. Fixed rather than\n // configurable: a product must not be able to tune its own blindness report\n // into silence.\n const blindThreshold = 0.5\n\n const [unanswered, turns] = await Promise.all([\n options.source.findUnansweredThreads({ minAgeMs, maxAgeMs, now }),\n options.source.listRecentAssistantTurns({ sinceMs: now - lookbackMs, now, limit }),\n ])\n\n const alerts: TurnHealthAlert[] = []\n\n // ── silence: messages in, nothing out ──────────────────────────────────\n const pendingUserMessages = unanswered.reduce((sum, t) => sum + t.pendingMessages, 0)\n const oldestUnansweredMs = unanswered.reduce((max, t) => Math.max(max, t.oldestAgeMs), 0)\n\n if (unanswered.length > 0) {\n const hours = (oldestUnansweredMs / HOUR_MS).toFixed(1)\n alerts.push({\n product: options.product,\n // A day of total silence is not a warning.\n severity: oldestUnansweredMs >= 24 * HOUR_MS ? 'critical' : 'warning',\n key: `sweep:${options.product}:unanswered_threads`,\n title: `${options.product}: ${pendingUserMessages} user message(s) unanswered across ${unanswered.length} thread(s)`,\n details: [\n `oldest unanswered message: ${hours}h`,\n ...unanswered\n .slice(0, 5)\n .map(\n (t) =>\n `thread ${t.threadId}: ${t.pendingMessages} pending, oldest ${(\n t.oldestAgeMs / HOUR_MS\n ).toFixed(1)}h`,\n ),\n ],\n data: {\n unansweredThreads: unanswered.length,\n pendingUserMessages,\n oldestUnansweredMs,\n },\n at: now,\n })\n }\n\n // ── success that delivered nothing ─────────────────────────────────────\n let emptyCompletions = 0\n let malformedToolCalls = 0\n let toolCallsWithoutEffect = 0\n let rejectedToolCalls = 0\n let unhealthyTurns = 0\n let turnsWithToolCalls = 0\n let toolCalls = 0\n let unreadableTurns = 0\n // Turns whose PARTS were interpretable — the only rows a tool verdict may be\n // drawn from. Distinct from `unreadableTurns`, which is the harder blindness\n // (nothing judgeable at all).\n let toolReadableTurns = 0\n let opaquePartsTurns = 0\n // Rows that persisted NO parts at all. Not opaque (nothing failed to parse)\n // and not evidence either — counted separately so the coverage line can say\n // which of the two blindnesses applies.\n let noPartsTurns = 0\n const opaqueTypes = new Set<string>()\n const malformedSamples: TurnHealthReason[] = []\n const rejectedSamples: TurnHealthReason[] = []\n\n for await (const row of withParts(turns, options.source)) {\n const verdict = classifyTurnOutcome({\n finalText: row.content,\n parts: parseParts(await decodeRowParts(options.decodeParts, row)),\n outputTokens: row.outputTokens ?? null,\n })\n toolCalls += verdict.toolCalls\n if (verdict.toolCalls > 0) turnsWithToolCalls += 1\n // A tool verdict needs evidence that was READ. `partsReadable` alone is\n // satisfied vacuously by a row that persisted no parts, which is how a\n // product with 243 real tool calls was paged as having a dead tool surface.\n if (verdict.partsReadable && verdict.interpretedParts > 0) toolReadableTurns += 1\n else if (verdict.partsReadable) noPartsTurns += 1\n else {\n opaquePartsTurns += 1\n for (const t of verdict.opaquePartTypes) opaqueTypes.add(t)\n }\n if (verdict.unreadable) {\n unreadableTurns += 1\n continue\n }\n if (verdict.healthy) continue\n unhealthyTurns += 1\n for (const reason of verdict.reasons) {\n if (reason.kind === 'empty_completion') emptyCompletions += 1\n if (reason.kind === 'malformed_tool_call') {\n malformedToolCalls += 1\n if (malformedSamples.length < 3) malformedSamples.push(reason)\n }\n if (reason.kind === 'tool_call_no_effect') toolCallsWithoutEffect += 1\n if (reason.kind === 'tool_call_rejected') {\n rejectedToolCalls += 1\n if (rejectedSamples.length < 3) rejectedSamples.push(reason)\n }\n }\n }\n\n // Turns this sweep could actually judge. Every rate below divides by THIS,\n // never by the raw row count.\n const readableTurns = turns.length - unreadableTurns\n\n // A malformed tool call is never acceptable at any rate — it means a\n // deliverable was requested and silently discarded. Page on the first one.\n if (malformedToolCalls > 0) {\n alerts.push({\n product: options.product,\n severity: 'critical',\n key: `sweep:${options.product}:malformed_tool_call`,\n title: `${options.product}: ${malformedToolCalls} tool call(s) had unparseable arguments — deliverables silently dropped`,\n details: malformedSamples.map(describeReason),\n data: { malformedToolCalls, turnsJudged: turns.length },\n at: now,\n })\n }\n\n // A rejected call means a deliverable was requested and thrown away while the\n // turn reported success. Never acceptable at any rate.\n if (rejectedToolCalls > 0) {\n alerts.push({\n product: options.product,\n severity: 'critical',\n key: `sweep:${options.product}:tool_call_rejected`,\n title: `${options.product}: ${rejectedToolCalls} tool call(s) were REJECTED but settled as completed — deliverables silently dropped`,\n details: rejectedSamples.map(describeReason),\n data: { rejectedToolCalls, turnsJudged: readableTurns },\n at: now,\n })\n }\n\n if (readableTurns >= minTurnsForRate) {\n const rate = emptyCompletions / readableTurns\n if (rate > emptyRateThreshold) {\n alerts.push({\n product: options.product,\n severity: 'critical',\n key: `sweep:${options.product}:empty_completion_rate`,\n title: `${options.product}: ${(rate * 100).toFixed(1)}% of turns completed with no output`,\n details: [\n `${emptyCompletions} of ${readableTurns} readable settled turns delivered nothing`,\n `threshold ${(emptyRateThreshold * 100).toFixed(1)}%`,\n ],\n data: { emptyCompletions, turnsJudged: readableTurns, rate },\n at: now,\n })\n }\n }\n\n // ── the fourth shape: a tool surface that has gone quiet ───────────────\n //\n // Nothing errors, every turn answers fluently, and the product stops DOING\n // anything. Only visible across a window, which is why it needs its own pass\n // rather than a rule inside the per-turn classifier.\n // Judged ONLY over turns whose parts could be interpreted, and the count of\n // rows that could not is stated in the alert — a verdict that names its own\n // coverage can be trusted; one that hides it cannot.\n if (options.expectsToolCalls && toolReadableTurns >= minTurnsForToolSurface && toolCalls === 0) {\n alerts.push({\n product: options.product,\n severity: 'critical',\n key: `sweep:${options.product}:dead_tool_surface`,\n title: `${options.product}: ZERO tool calls across ${toolReadableTurns} turns — the tool surface is dead`,\n details: [\n `${toolReadableTurns} assistant turns with readable parts in the lookback, none of which called a tool`,\n 'the product declares its deliverable comes from tool calls, so it has answered without doing anything',\n ...(opaquePartsTurns > 0\n ? [`${opaquePartsTurns} further turn(s) had unreadable parts and were not judged`]\n : []),\n ...(noPartsTurns > 0\n ? [`${noPartsTurns} further turn(s) persisted no parts at all and were not judged`]\n : []),\n ],\n data: {\n turnsJudged: toolReadableTurns,\n toolCalls: 0,\n turnsWithToolCalls: 0,\n turnsNotJudged: opaquePartsTurns + noPartsTurns,\n opaquePartsTurns,\n noPartsTurns,\n },\n at: now,\n })\n }\n\n // A product that ASKED for a tool-surface verdict and did not get one must be\n // told that, or the absence of a page reads as a pass. This is the honest\n // form of the alert above: same question, and the answer is \"I could not\n // see\", which is a real finding about the product's observability rather than\n // a fabricated finding about its behaviour.\n if (\n options.expectsToolCalls &&\n toolReadableTurns < minTurnsForToolSurface &&\n opaquePartsTurns + noPartsTurns > 0\n ) {\n alerts.push({\n product: options.product,\n severity: 'warning',\n key: `sweep:${options.product}:tool_surface_unmeasurable`,\n title: `${options.product}: tool surface could not be certified — only ${toolReadableTurns} of ${turns.length} turns carried readable parts`,\n details: [\n ...(noPartsTurns > 0\n ? [`${noPartsTurns} turn(s) persisted no parts at all — nothing to read a tool call from`]\n : []),\n ...(opaquePartsTurns > 0\n ? [\n `${opaquePartsTurns} turn(s) stored parts this sweep cannot interpret (${\n [...opaqueTypes].join(', ') || 'unnamed'\n }) — supply \\`decodeParts\\` to make them readable`,\n ]\n : []),\n 'this is NOT a dead tool surface finding; it is the absence of evidence either way',\n ],\n data: {\n toolReadableTurns,\n noPartsTurns,\n opaquePartsTurns,\n turnsSeen: turns.length,\n opaqueTypes: [...opaqueTypes],\n },\n at: now,\n })\n }\n\n // ── the detector reporting on ITSELF ───────────────────────────────────\n //\n // The one verdict this module must never give is \"healthy\" derived from rows\n // it could not read. If most of the window was opaque, that fact is the\n // alert — silence here would be the module committing the exact failure it\n // was built to catch.\n if (opaquePartsTurns > 0 && opaquePartsTurns >= turns.length * blindThreshold) {\n alerts.push({\n product: options.product,\n severity: 'warning',\n key: `sweep:${options.product}:detector_blind`,\n title: `${options.product}: ${opaquePartsTurns} of ${turns.length} turns have unreadable parts — this sweep cannot certify them`,\n details: [\n `uninterpretable part types: ${[...opaqueTypes].join(', ') || '(none named)'}`,\n 'these rows are excluded from every verdict above; treat them as UNMEASURED, not healthy',\n ],\n data: {\n opaquePartsTurns,\n unreadableTurns,\n turnsSeen: turns.length,\n opaqueTypes: [...opaqueTypes],\n },\n at: now,\n })\n }\n\n for (const alert of alerts) await options.sink.deliver(alert)\n\n return {\n product: options.product,\n unansweredThreads: unanswered.length,\n pendingUserMessages,\n oldestUnansweredMs,\n turnsJudged: turns.length,\n unhealthyTurns,\n emptyCompletions,\n malformedToolCalls,\n toolCallsWithoutEffect,\n rejectedToolCalls,\n turnsWithToolCalls,\n toolCalls,\n unreadableTurns,\n opaquePartsTurns,\n noPartsTurns,\n toolReadableTurns,\n alerts,\n }\n}\n\n// ── D1 source for the shared chat-store schema ────────────────────────────\n\n/** Minimal structural D1 contract (Cloudflare's `D1Database` satisfies it). */\nexport interface D1LikeForHealth {\n prepare(sql: string): {\n bind(...values: unknown[]): {\n all<T = Record<string, unknown>>(): Promise<{ results: T[] }>\n }\n }\n}\n\n/**\n * The sweep source for products on the canonical `/chat-store` tables.\n *\n * \"Answered\" deliberately means an assistant row with NON-EMPTY content. A\n * blank assistant row is what a broken turn writes, so counting it as an\n * answer would let the exact failure being hunted mark itself resolved. That\n * single predicate is the difference between this catching the gtm outage and\n * sleeping through it — during those sixteen days the table was NOT empty.\n *\n * The query deliberately does NOT join the thread table. Products do not all\n * keep one: tax-agent's `thread` table holds zero rows because it groups by\n * its own `tax_sessions`, and an inner join against it silently reported \"0\n * unanswered threads, healthy\" while 18 real messages sat unanswered. A\n * detector that reports healthy because its join found nothing is the same\n * bug class it was built to catch.\n */\nexport function createD1TurnHealthSource(\n db: D1LikeForHealth,\n options: {\n messageTable?: string\n threadTable?: string\n /**\n * Content prefixes that mark an assistant row as an ERROR SURFACE rather\n * than an answer. A row matching one of these stops counting as a reply,\n * so the thread keeps reporting as unanswered.\n *\n * This exists because the obvious rule — \"an assistant row with non-empty\n * content is an answer\" — is wrong in the exact case that matters. On\n * 2026-07-27 gtm-agent's newest assistant row read:\n *\n * \"The sandbox model stream stopped before a clean completion.\n * Error: All 2 model(s) failed. gpt-5-mini: TANGLE_HUB_URL is required …\"\n *\n * 246 characters of well-formed prose that answers nothing. Counting it\n * marks a dead product healthy — the same failure-returning-success shape\n * this module exists to catch, recursing into the detector itself.\n *\n * There is no schema-level way to recognise it: `output_tokens IS NULL`\n * looked promising until legal-agent showed 22 of 25 GENUINE replies with\n * null usage — it would have reported a working product broken.\n *\n * Defaults to {@link SHELL_ERROR_REPLY_PREFIXES}, the openers agent-app\n * ITSELF writes in `createSandboxChatProducer`. Those are not domain —\n * this package composed them, so this package is what must recognise\n * them, and every product on the shared producer is correct with no\n * configuration. Pass your own list to ADD product-specific error prose;\n * pass `[]` to disable the rule.\n *\n * Prefixes are bound as query parameters, never interpolated.\n */\n errorReplyPrefixes?: readonly string[]\n } = {},\n): TurnHealthSource {\n // Table names are identifiers and cannot be bound as parameters. They come\n // from deploy-time product config, never from a request, and are validated\n // here so this can never become an injection point.\n const message = safeIdentifier(options.messageTable ?? 'message')\n const thread = safeIdentifier(options.threadTable ?? 'thread')\n // D1 rejects a LIKE pattern longer than 50 characters with\n // `SQLITE_ERROR: LIKE or GLOB pattern too complex`, and the pattern is the\n // prefix PLUS the trailing `%`. Measured against production D1 on\n // 2026-07-27: a 49-char prefix (50-char pattern) succeeds, 50 fails.\n //\n // Both shipped defaults are longer than that (55 and 70 characters), so\n // before this clamp `findUnansweredThreads` threw on every product database\n // — the detector could not run at all against the only store the fleet uses.\n //\n // Truncating is safe in the one direction that matters: a shorter prefix\n // matches MORE rows as non-answers, so a thread is reported unanswered\n // rather than silently marked healthy. The first 49 characters of each\n // default are still unambiguous.\n const errorPrefixes = [...(options.errorReplyPrefixes ?? SHELL_ERROR_REPLY_PREFIXES)].map((p) =>\n p.slice(0, D1_MAX_LIKE_PATTERN_LENGTH - 1),\n )\n\n return {\n async findUnansweredThreads({ minAgeMs, maxAgeMs, now }) {\n const cutoffSeconds = Math.floor((now - minAgeMs) / 1000)\n const floorSeconds = Math.floor((now - maxAgeMs) / 1000)\n // Each prefix becomes one bound `NOT LIKE ?||'%'` term. Parameters, not\n // interpolation — a product-supplied string never reaches the SQL text.\n const errorClause = errorPrefixes\n .map((_, i) => ` AND a.content NOT LIKE ?${i + 3} || '%'`)\n .join('')\n const { results } = await db\n .prepare(\n `SELECT m.thread_id AS threadId,\n COUNT(*) AS pendingMessages,\n MIN(m.created_at) AS oldestCreatedAt\n FROM ${message} m\n WHERE m.role = 'user'\n AND m.created_at <= ?1\n AND m.created_at >= ?2\n AND m.created_at > COALESCE(\n (SELECT MAX(a.created_at)\n FROM ${message} a\n WHERE a.thread_id = m.thread_id\n AND a.role = 'assistant'\n AND length(trim(a.content)) > 0${errorClause}), 0)\n GROUP BY m.thread_id\n ORDER BY oldestCreatedAt ASC`,\n )\n .bind(cutoffSeconds, floorSeconds, ...errorPrefixes)\n .all<{ threadId: string; pendingMessages: number; oldestCreatedAt: number }>()\n\n return results.map((row) => ({\n threadId: row.threadId,\n pendingMessages: Number(row.pendingMessages),\n oldestAgeMs: now - Number(row.oldestCreatedAt) * 1000,\n }))\n },\n\n async listRecentAssistantTurns({ sinceMs, limit }) {\n const sinceSeconds = Math.floor(sinceMs / 1000)\n const { results } = await db\n .prepare(\n `SELECT id, thread_id AS threadId, content, length(parts) AS partsSize,\n output_tokens AS outputTokens, model, created_at AS createdAt\n FROM ${message}\n WHERE role = 'assistant' AND created_at >= ?1\n ORDER BY created_at DESC\n LIMIT ?2`,\n )\n .bind(sinceSeconds, limit)\n .all<Record<string, unknown>>()\n\n return results.map((row) => ({\n id: String(row.id),\n threadId: String(row.threadId),\n content: typeof row.content === 'string' ? row.content : '',\n parts: undefined,\n partsSize: row.partsSize === null ? null : Number(row.partsSize),\n outputTokens: row.outputTokens === null ? null : Number(row.outputTokens),\n model: (row.model as string | null) ?? null,\n createdAt: Number(row.createdAt) * 1000,\n }))\n },\n\n async readParts(ids) {\n if (ids.length === 0) return new Map()\n const { results } = await db\n .prepare(`SELECT id, parts FROM ${message} WHERE id IN (${ids.map((_, i) => `?${i + 1}`).join(', ')})`)\n .bind(...ids)\n .all<{ id: string; parts: unknown }>()\n return new Map(results.map((row) => [String(row.id), row.parts]))\n },\n }\n\n function safeIdentifier(name: string): string {\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) {\n throw new Error(`unsafe table identifier: ${name}`)\n }\n return name\n }\n}\n"],"mappings":";;;;;;;;;AAwMA,IAAM,sBAAsB,oBAAI,IAAI,CAAC,QAAQ,SAAS,gBAAgB,QAAQ,aAAa,CAAC;AAc5F,IAAM,8BAA8B,oBAAI,IAAI;AAAA,EAC1C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAED,IAAM,eAAe;AA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,CAAC,SAAS;AAAA,QAC3B,IAAI,OAAO,IAAI,EAAE;AAAA,QACjB,UAAU,OAAO,IAAI,QAAQ;AAAA,QAC7B,SAAS,OAAO,IAAI,YAAY,WAAW,IAAI,UAAU;AAAA,QACzD,OAAO;AAAA,QACP,WAAW,IAAI,cAAc,OAAO,OAAO,OAAO,IAAI,SAAS;AAAA,QAC/D,cAAc,IAAI,iBAAiB,OAAO,OAAO,OAAO,IAAI,YAAY;AAAA,QACxE,OAAQ,IAAI,SAA2B;AAAA,QACvC,WAAW,OAAO,IAAI,SAAS,IAAI;AAAA,MACrC,EAAE;AAAA,IACJ;AAAA,IAEA,MAAM,UAAU,KAAK;AACnB,UAAI,IAAI,WAAW,EAAG,QAAO,oBAAI,IAAI;AACrC,YAAM,EAAE,QAAQ,IAAI,MAAM,GACvB,QAAQ,yBAAyB,OAAO,iBAAiB,IAAI,IAAI,CAAC,GAAG,MAAM,IAAI,IAAI,CAAC,EAAE,EAAE,KAAK,IAAI,CAAC,GAAG,EACrG,KAAK,GAAG,GAAG,EACX,IAAoC;AACvC,aAAO,IAAI,IAAI,QAAQ,IAAI,CAAC,QAAQ,CAAC,OAAO,IAAI,EAAE,GAAG,IAAI,KAAK,CAAC,CAAC;AAAA,IAClE;AAAA,EACF;AAEA,WAAS,eAAe,MAAsB;AAC5C,QAAI,CAAC,2BAA2B,KAAK,IAAI,GAAG;AAC1C,YAAM,IAAI,MAAM,4BAA4B,IAAI,EAAE;AAAA,IACpD;AACA,WAAO;AAAA,EACT;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/turn-health/classify.ts","../../src/turn-health/sink.ts","../../src/turn-health/lifecycle.ts","../../src/turn-health/sweep.ts"],"sourcesContent":["/**\n * The classifier for turns that FAIL BY RETURNING SUCCESS.\n *\n * Every failure this module names shipped to a customer with HTTP 200, no\n * thrown error, and no log line anyone read. Three were measured in production\n * in a single week:\n *\n * - a turn settled `{\"outcome\":{\"type\":\"completed\"},\"finalText\":\"\",\n * \"tokenUsage\":{\"outputTokens\":0}}` — the customer saw a blank bubble;\n * - six `submit_proposal` tool calls collapsed into ONE whose arguments were\n * a 1,652-character non-JSON string, so zero proposals persisted and\n * nothing errored (agent-runtime #626);\n * - a thread took 255 user messages over 17 days and produced 2 replies,\n * both of them error text.\n *\n * A conventional health check cannot see any of these, because it probes\n * DEPENDENCIES (is the sandbox reachable, is the router up) and every one of\n * these failures happens with all dependencies green. This classifier probes\n * the OUTCOME instead.\n *\n * It is deliberately pure and structural: it reads a settled turn's own\n * projection, so the SAME function judges a live turn through the\n * `/chat-routes` lifecycle seam and a historical row read back out of the\n * store during a sweep. One definition of \"silently broken\", two call sites.\n */\n\n/** How loudly a reason should be routed. `critical` means a customer got\n * nothing usable; `warning` means the turn degraded but still produced\n * something a human could read. */\nexport type TurnHealthSeverity = 'critical' | 'warning'\n\n/** One specific way a turn returned success while failing.\n *\n * Each variant carries the evidence that identified it, so an alert can name\n * the offending value instead of asserting a verdict the reader has to take\n * on faith. */\nexport type TurnHealthReason =\n /** Settled without error and produced nothing a user can read: no text, and\n * no artifact part (file/image/work-product/plan/interaction). This is the\n * verbatim blank-completion capture. */\n | {\n kind: 'empty_completion'\n outputTokens: number | null\n partCount: number\n durationMs?: number\n }\n /** A tool call whose arguments never parsed. The engine surfaces unparseable\n * arguments as a RAW STRING rather than throwing, so the call is neither\n * dropped nor errored — it silently does nothing. Detecting a string-typed\n * tool input that fails `JSON.parse` is the exact fingerprint of the\n * index-less parallel-tool-call collapse. */\n | {\n kind: 'malformed_tool_call'\n tool: string\n inputLength: number\n /** Leading characters of the offending input, for the alert body. */\n sample: string\n }\n /** A tool call that never reached a terminal state carrying output. The call\n * was issued and then simply produced no effect. */\n | {\n kind: 'tool_call_no_effect'\n tool: string\n status: string\n }\n /** The turn failed outright. Not silent by itself — but it becomes silent\n * the moment nothing is watching, which is how 16 days of\n * `TANGLE_HUB_URL is required` reached customers unnoticed. */\n | { kind: 'turn_failed'; reason: string }\n /** A tool call the harness REJECTED, settled as `completed`.\n *\n * Found live in legal-agent production, and missed by every other rule here:\n * the model called `submit_proposal`, the harness answered \"Model tried to\n * call unavailable tool 'submit_proposal'\", and the part persisted as\n * `{\"tool\":\"invalid\",\"state\":{\"status\":\"completed\",\"input\":{\"error\":\"…\"}}}`.\n *\n * Status is `completed`, the arguments parse cleanly, and the turn has text —\n * so the blank-completion, malformed-argument and no-effect rules all pass it.\n * Six deliverables were requested and silently discarded while the product\n * reported success six times.\n *\n * Detected structurally, on the presence of an `error` in the settled state\n * rather than on any harness's name for a rejected call — `invalid` is one\n * harness's convention and must not be baked into the shell. */\n | {\n kind: 'tool_call_rejected'\n /** The tool the model was trying to reach, when the payload names it. */\n tool: string\n error: string\n }\n /** The turn was answered without the model ever running — a pre-producer gate\n * short-circuited and returned the product's own response.\n *\n * Reported as a `warning`, never `critical`: gating an unready turn is a\n * legitimate design (an intake flow SHOULD answer before spending a model\n * call). What is pathological is the RATE, which only the caller's own\n * threshold can judge — so this variant exists to be COUNTED, and alerting\n * on it is opt-in. It is the per-turn evidence behind a dead tool surface:\n * a gate that answers every turn means the agent never runs at all. */\n | { kind: 'answered_without_model' }\n /** The detector could not read this turn.\n *\n * Every part carried a type outside the vocabulary this classifier\n * understands — which is what field-level encryption at rest looks like from\n * the outside (tax-agent persists `{\"type\":\"__encrypted_parts__\"}`, its own\n * convention, and 32 of its 129 assistant rows are exactly that).\n *\n * This exists because the alternative is the bug this whole module hunts.\n * An unreadable row has no text, no artifact and no tool part, so every\n * other rule here would happily conclude \"nothing wrong\" — a detector\n * reporting health from data it cannot see. Blindness is a finding, not a\n * pass, so it gets its own reason and its own counter. */\n | { kind: 'unreadable_turn'; partTypes: string[] }\n\n/** A settled turn, in the narrowest shape both call sites can supply.\n *\n * Structural on purpose: the lifecycle seam supplies `finalText`/`usage`, a\n * store sweep supplies `content`/`parts` read back from a row, and neither\n * has to import the other's types. */\nexport interface TurnOutcomeInput {\n /** The turn's final assistant text. */\n finalText?: string | null\n /** The persisted assistant parts. Untyped by design — a sweep reads these\n * out of a JSON column and must not be forced to validate them first. */\n parts?: readonly unknown[] | null\n /** Output tokens, when the caller has usage. `null`/absent is unknown, which\n * is NOT the same as zero and is never treated as evidence. */\n outputTokens?: number | null\n /** Set when the turn surfaced a terminal error event. */\n failed?: boolean\n failureReason?: string | null\n durationMs?: number\n /** Set when a pre-producer gate answered this turn and the model never ran.\n * Supplied by `/chat-routes`' lifecycle seam, which stamps `gated` on the\n * completion it now fires for a `contextGate` short-circuit. */\n gated?: boolean\n}\n\n/** The verdict for one turn. `healthy` is exactly `reasons.length === 0`, kept\n * as a field so callers read intent rather than an array length. */\nexport interface TurnHealthVerdict {\n healthy: boolean\n severity: TurnHealthSeverity | null\n reasons: TurnHealthReason[]\n /** How many tool parts this turn carried.\n *\n * Zero is NOT a per-turn defect — plenty of good turns answer from context\n * without touching a tool, and paging on each one would be pure noise. It is\n * reported so a WINDOW can be judged: a product whose deliverable is tool\n * output and which produced zero tool calls across every turn in the\n * lookback has a dead tool surface, and that is the shape no per-turn rule\n * can see.\n *\n * Only meaningful alongside {@link interpretedParts} > 0. Zero tool calls\n * read off a row that persisted NO parts is not an observation about the\n * tool surface — it is the absence of one. */\n toolCalls: number\n /** True when nothing about this turn could be judged — no interpretable part\n * AND no visible text. Callers MUST exclude these from any healthy/unhealthy\n * ratio, because counting an unreadable turn as healthy is how a detector\n * reports green on data it never read. */\n unreadable: boolean\n /** False when this turn carried parts that could not be interpreted.\n *\n * Separate from {@link unreadable} because the two blindnesses have\n * different consequences, and production has a row that is one but not the\n * other: tax-agent persists CIPHERTEXT as `content` alongside an encrypted\n * `parts` blob, so the turn plainly delivered something (there is text) while\n * its tool calls are completely invisible.\n *\n * Any conclusion ABOUT TOOLS — above all the dead-tool-surface verdict — may\n * only be drawn over turns where this is true. Reading \"no tool parts\" off an\n * encrypted blob and declaring the tool surface dead would be the same\n * crime as declaring it healthy: a finding asserted from data never read. */\n partsReadable: boolean\n /** The part types that could not be interpreted. Empty when\n * {@link partsReadable}. Named in the alert so a reader can see EXACTLY what\n * the detector was blind to instead of taking \"unreadable\" on faith. */\n opaquePartTypes: string[]\n /** How many parts this module actually READ (text, artifact, tool, or a known\n * non-output kind).\n *\n * The third blindness, and the one that shipped a false page. `partsReadable`\n * only says nothing was *uninterpretable*; a row that persisted NO parts at\n * all satisfies that vacuously. Production: 97 of tax-agent's 156 assistant\n * rows predate parts persistence entirely and store `[]`, and reading \"zero\n * tool calls\" off them raised a critical `dead_tool_surface` against a\n * product whose own `turn_events` table holds 243 `tool_call` frames.\n *\n * So a tool verdict requires BOTH `partsReadable` AND this being > 0 —\n * evidence that was read, not merely evidence that failed to be unreadable. */\n interpretedParts: number\n}\n\n/** Part kinds that count as something a user actually receives.\n *\n * A tool part is deliberately NOT here. A turn that ran six tools and said\n * nothing, with no artifact to show for it, is the malformed-tool-call\n * disaster — counting a tool chip as output would suppress the very alert\n * this module exists to raise. */\nconst ARTIFACT_PART_KINDS = new Set(['file', 'image', 'work-product', 'plan', 'interaction'])\n\n/** Part types that carry no user-visible output but ARE understood.\n *\n * The distinction matters: a turn made of nothing but `reasoning` parts\n * thought hard and said nothing, which is a real empty completion. A turn made\n * of types this module has never heard of is a turn it cannot read. Only the\n * second is blindness — so these are enumerated rather than lumped in with the\n * unknown.\n *\n * Grounded in what the fleet actually persists, not guessed: a scan of every\n * assistant part in the gtm / legal / tax production tables returns exactly\n * `tool` (138), `text` (69), `reasoning` (26), `step-start` (3),\n * `step-finish` (3) and tax's opaque `__encrypted_parts__` (32). */\nconst KNOWN_NON_OUTPUT_PART_KINDS = new Set([\n 'reasoning',\n 'step-start',\n 'step-finish',\n 'source',\n 'source-url',\n 'data',\n])\n\nconst SAMPLE_CHARS = 120\n\nfunction asRecord(value: unknown): Record<string, unknown> | null {\n return typeof value === 'object' && value !== null ? (value as Record<string, unknown>) : null\n}\n\nfunction nonEmptyString(value: unknown): string | null {\n return typeof value === 'string' && value.trim().length > 0 ? value : null\n}\n\n/** True when a string is not parseable JSON.\n *\n * Only meaningful for tool INPUT, where the engine's contract is that a\n * well-formed call carries an object (or a string that parses into one). A\n * string that fails to parse means the arguments were concatenated or\n * truncated upstream. */\nfunction isUnparseableJson(value: string): boolean {\n const trimmed = value.trim()\n if (trimmed.length === 0) return false\n try {\n JSON.parse(trimmed)\n return false\n } catch {\n return true\n }\n}\n\n/** Tool statuses that mean the call actually landed.\n *\n * Anything else — `pending`, `running`, `error`, an unknown string — left no\n * persisted effect by the time the turn settled. */\nconst SETTLED_TOOL_STATUSES = new Set(['completed', 'complete', 'success', 'done'])\n\n/**\n * Judge one settled turn.\n *\n * Never throws: a malformed `parts` blob is a thing this function REPORTS on,\n * so it must not be a thing it dies on. Telemetry that can crash the turn it\n * measures is worse than no telemetry.\n */\nexport function classifyTurnOutcome(input: TurnOutcomeInput): TurnHealthVerdict {\n const reasons: TurnHealthReason[] = []\n\n if (input.failed) {\n reasons.push({\n kind: 'turn_failed',\n reason: nonEmptyString(input.failureReason) ?? 'unspecified',\n })\n }\n\n const parts = Array.isArray(input.parts) ? input.parts : []\n\n let hasVisibleText = nonEmptyString(input.finalText) !== null\n let artifactCount = 0\n let toolCalls = 0\n // Part types this module could not interpret. Tracked so blindness can be\n // reported as blindness instead of silently reading as health.\n const opaqueTypes: string[] = []\n let interpretedParts = 0\n\n for (const raw of parts) {\n const part = asRecord(raw)\n if (!part) continue\n const type = typeof part.type === 'string' ? part.type : ''\n\n if (type === 'text') {\n interpretedParts += 1\n if (nonEmptyString(part.text) !== null) hasVisibleText = true\n continue\n }\n if (ARTIFACT_PART_KINDS.has(type)) {\n interpretedParts += 1\n artifactCount += 1\n continue\n }\n if (KNOWN_NON_OUTPUT_PART_KINDS.has(type)) {\n interpretedParts += 1\n continue\n }\n if (type !== 'tool') {\n opaqueTypes.push(type || '(missing type)')\n continue\n }\n interpretedParts += 1\n toolCalls += 1\n\n const tool = nonEmptyString(part.tool) ?? 'unknown'\n const state = asRecord(part.state)\n const status = typeof state?.status === 'string' ? state.status : 'unknown'\n\n // The #626 fingerprint: arguments surfaced as a raw string because they\n // failed to parse upstream. Checked before the status gate — a malformed\n // call can still be marked completed, which is precisely why it is silent.\n // A rejected call settles as `completed` and carries its rejection in the\n // state. Checked BEFORE the status gate for the same reason as the\n // malformed case: the status is exactly what makes it silent.\n const toolInput = state?.input\n const inputRecord = asRecord(toolInput)\n const rejection =\n nonEmptyString(inputRecord?.error) ?? nonEmptyString((state as Record<string, unknown>)?.error)\n if (rejection) {\n reasons.push({\n kind: 'tool_call_rejected',\n // The payload names the tool the model MEANT to call; the part's own\n // `tool` is the harness's placeholder for a rejected call.\n tool: nonEmptyString(inputRecord?.tool) ?? tool,\n error: rejection.slice(0, 200),\n })\n continue\n }\n if (typeof toolInput === 'string' && isUnparseableJson(toolInput)) {\n reasons.push({\n kind: 'malformed_tool_call',\n tool,\n inputLength: toolInput.length,\n sample: toolInput.slice(0, SAMPLE_CHARS),\n })\n continue\n }\n\n if (!SETTLED_TOOL_STATUSES.has(status)) {\n reasons.push({ kind: 'tool_call_no_effect', tool, status })\n }\n }\n\n // A turn whose parts were ALL uninterpretable cannot be judged. Reported as\n // blindness and returned early, because every rule below would otherwise read\n // \"no text, no artifact\" off data that was simply encrypted and call it a\n // blank completion — a false page that would train readers to ignore this\n // module, which is the same ending as no detector at all.\n const partsReadable = opaqueTypes.length === 0\n const uniqueOpaque = [...new Set(opaqueTypes)]\n const unreadable = opaqueTypes.length > 0 && interpretedParts === 0 && !hasVisibleText\n if (unreadable) {\n reasons.push({ kind: 'unreadable_turn', partTypes: uniqueOpaque })\n return {\n healthy: false,\n severity: 'warning',\n reasons,\n toolCalls,\n unreadable: true,\n partsReadable: false,\n opaquePartTypes: uniqueOpaque,\n // Structurally 0 here — `unreadable` is only reached when\n // `interpretedParts === 0`. Carried rather than hardcoded so the field\n // has one source on every return path.\n interpretedParts,\n }\n }\n\n // A gate answered before the producer ran. Recorded rather than judged: see\n // `answered_without_model`. It also SUPPRESSES the empty-completion rule\n // below — the model producing no text is the expected outcome when the model\n // never ran, and firing `empty_completion` here would page on every healthy\n // intake turn.\n if (input.gated) {\n reasons.push({ kind: 'answered_without_model' })\n } else if (!input.failed && !hasVisibleText && artifactCount === 0) {\n // `outputTokens` is corroborating evidence, never the trigger: a turn can\n // spend tokens on reasoning and still deliver nothing, and a turn with\n // unknown usage can still be perfectly fine.\n reasons.push({\n kind: 'empty_completion',\n outputTokens: input.outputTokens ?? null,\n partCount: parts.length,\n ...(input.durationMs !== undefined ? { durationMs: input.durationMs } : {}),\n })\n }\n\n return {\n healthy: reasons.length === 0,\n severity: severityOf(reasons),\n reasons,\n toolCalls,\n unreadable: false,\n partsReadable,\n opaquePartTypes: uniqueOpaque,\n interpretedParts,\n }\n}\n\n/** `critical` when the customer got nothing usable out of the turn. A\n * malformed tool call alongside readable text is a `warning` — degraded, but\n * a human still received an answer. */\nfunction severityOf(reasons: TurnHealthReason[]): TurnHealthSeverity | null {\n if (reasons.length === 0) return null\n // A rejected tool call is critical even alongside readable prose: the\n // customer got words where they should have got a filed deliverable.\n const critical = reasons.some(\n (r) =>\n r.kind === 'empty_completion' ||\n r.kind === 'turn_failed' ||\n r.kind === 'tool_call_rejected',\n )\n return critical ? 'critical' : 'warning'\n}\n\n/** One-line human summary of a reason, for an alert body. */\nexport function describeReason(reason: TurnHealthReason): string {\n switch (reason.kind) {\n case 'empty_completion':\n return `completed with NO output (${reason.partCount} parts, outputTokens=${\n reason.outputTokens ?? 'unknown'\n })`\n case 'malformed_tool_call':\n return `tool \\`${reason.tool}\\` arguments did not parse (${reason.inputLength} chars): ${reason.sample}`\n case 'tool_call_no_effect':\n return `tool \\`${reason.tool}\\` left no effect (status=${reason.status})`\n case 'turn_failed':\n return `turn failed: ${reason.reason}`\n case 'tool_call_rejected':\n return `tool \\`${reason.tool}\\` was REJECTED but settled as completed: ${reason.error}`\n case 'answered_without_model':\n return 'answered by a pre-producer gate — the model never ran'\n case 'unreadable_turn':\n return `turn could not be read: every part had an uninterpretable type (${reason.partTypes.join(\n ', ',\n )})`\n }\n}\n","/**\n * Where a silent-failure verdict GOES.\n *\n * The detection half is worthless without this half. Every failure this module\n * finds was already visible in the database the whole time — 255 unanswered\n * messages sat in a table for 17 days. What was missing was not the data, it\n * was delivery to a human who had not thought to look.\n *\n * So the sink is a seam, not a channel: the product supplies the transport,\n * and agent-app ships the two shapes the fleet already has credentials for\n * (an ops webhook, and stderr). No new channel is invented here.\n */\n\nimport { postSlackAlert } from '../alerting/slack.js'\nimport { describeReason, type TurnHealthReason, type TurnHealthSeverity } from './classify.js'\n\n/** One deliverable alert. */\nexport interface TurnHealthAlert {\n /** Which product raised it (`projectId`). Alerts from four products land in\n * one channel, so this is what makes the message actionable. */\n product: string\n severity: TurnHealthSeverity\n /** Stable grouping key. Throttling is keyed on this, so it must NOT contain\n * a turn id or a timestamp or every alert is unique and nothing dedupes. */\n key: string\n title: string\n /** Human-readable lines. */\n details: string[]\n /** Structured payload for a machine consumer. */\n data?: Record<string, unknown>\n at: number\n}\n\n/** Deliver an alert. Implementations MUST NOT throw — see\n * {@link createGuardedAlertSink}. */\nexport interface AlertSink {\n deliver(alert: TurnHealthAlert): Promise<void>\n}\n\n/** Build the alert for a set of reasons found on one turn. */\nexport function turnAlert(input: {\n product: string\n severity: TurnHealthSeverity\n reasons: TurnHealthReason[]\n threadId?: string\n turnId?: string\n model?: string\n at?: number\n}): TurnHealthAlert {\n const kinds = [...new Set(input.reasons.map((r) => r.kind))].sort()\n return {\n product: input.product,\n severity: input.severity,\n // Keyed by product + reason kinds ONLY. A blank-completion storm across\n // 200 turns is one incident, not 200 pages.\n key: `turn:${input.product}:${kinds.join('+')}`,\n title: `${input.product}: turn completed but delivered nothing (${kinds.join(', ')})`,\n details: input.reasons.map(describeReason),\n data: {\n kinds,\n ...(input.threadId ? { threadId: input.threadId } : {}),\n ...(input.turnId ? { turnId: input.turnId } : {}),\n ...(input.model ? { model: input.model } : {}),\n },\n at: input.at ?? Date.now(),\n }\n}\n\n// ── transports ────────────────────────────────────────────────────────────\n\n/** Minimal structural fetch, so this module has no lib-dom dependency and can\n * be driven by a fake in tests. */\nexport type FetchLike = (\n url: string,\n init: { method: string; headers: Record<string, string>; body: string },\n) => Promise<{ ok: boolean; status: number; text?(): Promise<string> }>\n\n/**\n * POST to an incoming webhook in the Slack message format.\n *\n * Chosen because the org already runs one (`SLACK_OPS_WEBHOOK_URL`) and\n * gtm-agent's outbound webhook code already speaks this exact shape — the\n * instruction was to route somewhere humans already look, not to stand up a\n * new channel. Discord and most log drains accept the same `{text}` body.\n */\nexport function createWebhookAlertSink(options: {\n webhookUrl: string\n fetchImpl?: FetchLike\n}): AlertSink {\n const fetchImpl = options.fetchImpl ?? (globalThis.fetch as unknown as FetchLike)\n return {\n async deliver(alert) {\n const icon = alert.severity === 'critical' ? ':rotating_light:' : ':warning:'\n const lines = [\n `${icon} *${alert.title}*`,\n ...alert.details.map((d) => `• ${d}`),\n `_${new Date(alert.at).toISOString()}_`,\n ]\n const response = await fetchImpl(options.webhookUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ text: lines.join('\\n') }),\n })\n if (!response.ok) {\n // A dropped alert is a silent failure of the silent-failure detector.\n // It must be loud in the one place that is still working: the log.\n throw new Error(`alert webhook responded ${response.status}`)\n }\n },\n }\n}\n\n/**\n * POST to Slack `chat.postMessage` with a bot token.\n *\n * This is the transport the org actually has. A survey of the four product\n * repos found NO ops alert path of any kind — no incoming webhook, no pager, no\n * notifier — which is the mechanical reason a 17-day outage never reached a\n * human. What does exist is a Slack bot token in the shared secrets store, and\n * `@tangle-network/agent-integrations` already speaks this exact API, so this\n * routes alerts through the channel the org runs rather than standing up a new\n * one.\n *\n * Slack answers `200 OK` with `{\"ok\": false, \"error\": \"...\"}` for an invalid\n * token or channel, so the body is checked and not just the status — a\n * transport that reports success on a rejected post would make the alerter\n * itself a silent failure.\n */\nexport function createSlackBotAlertSink(options: {\n botToken: string\n channel: string\n fetchImpl?: FetchLike\n}): AlertSink {\n const fetchImpl = options.fetchImpl ?? (globalThis.fetch as unknown as FetchLike)\n return {\n async deliver(alert) {\n const icon = alert.severity === 'critical' ? ':rotating_light:' : ':warning:'\n const lines = [\n `${icon} *${alert.title}*`,\n ...alert.details.map((d) => `• ${d}`),\n `_${new Date(alert.at).toISOString()}_`,\n ]\n const outcome = await postSlackAlert({\n token: options.botToken, channel: options.channel, text: lines.join('\\n'), attempts: 1,\n // Preserve the public minimal-fetch seam without owning a second Slack\n // request builder or response parser. Real callers use native fetch.\n fetchImpl: options.fetchImpl ? (async (url, init) => {\n const response = await fetchImpl(String(url), {\n method: init?.method ?? 'POST',\n headers: Object.fromEntries(new Headers(init?.headers)),\n body: String(init?.body ?? ''),\n })\n return new Response(await response.text?.() ?? '', { status: response.status })\n }) : undefined,\n })\n if (!outcome.delivered) throw new Error(`Slack alert failed (${outcome.reason}): ${outcome.detail}`)\n },\n }\n}\n\n/** stderr sink. The zero-config fallback so a product that has not yet been\n * given a webhook still emits something a log search can find. */\nexport function createConsoleAlertSink(log: (message: string) => void = console.error): AlertSink {\n return {\n async deliver(alert) {\n log(\n `[turn-health] ${alert.severity.toUpperCase()} ${alert.title} :: ${alert.details.join(' | ')}`,\n )\n },\n }\n}\n\n/** Fan out to several sinks. One failing transport must not stop the others. */\nexport function createMultiAlertSink(sinks: readonly AlertSink[]): AlertSink {\n return {\n async deliver(alert) {\n const settled = await Promise.allSettled(sinks.map((s) => s.deliver(alert)))\n const failures = settled.filter((r) => r.status === 'rejected')\n if (failures.length === sinks.length && sinks.length > 0) {\n throw new Error('every alert sink failed')\n }\n },\n }\n}\n\n// ── throttling ────────────────────────────────────────────────────────────\n\n/** Records the last time a key was alerted on. A product backs this with KV,\n * D1, or a Durable Object; the in-memory default is correct for a sweep that\n * runs as a single cron invocation. */\nexport interface AlertThrottleStore {\n lastSentAt(key: string): Promise<number | null>\n markSent(key: string, at: number): Promise<void>\n}\n\n/** Process-local throttle store. */\nexport function createMemoryThrottleStore(): AlertThrottleStore {\n const seen = new Map<string, number>()\n return {\n async lastSentAt(key) {\n return seen.get(key) ?? null\n },\n async markSent(key, at) {\n seen.set(key, at)\n },\n }\n}\n\n/**\n * Collapse repeats of the same `key` inside `windowMs`.\n *\n * Deliberately re-alerts once per window rather than going silent after the\n * first: an incident that is still burning must keep saying so. Going quiet\n * after one message is how a 17-day outage stays invisible after someone\n * dismisses the first notification.\n */\nexport function createThrottledAlertSink(\n inner: AlertSink,\n options: { windowMs: number; store?: AlertThrottleStore },\n): AlertSink {\n const store = options.store ?? createMemoryThrottleStore()\n return {\n async deliver(alert) {\n const last = await store.lastSentAt(alert.key)\n if (last !== null && alert.at - last < options.windowMs) return\n await inner.deliver(alert)\n await store.markSent(alert.key, alert.at)\n },\n }\n}\n\n/**\n * Swallow transport errors so telemetry can never fail the turn it measures.\n *\n * Use this at the LIVE lifecycle call site only. A sweep should let the error\n * surface, because a sweep that cannot deliver has done nothing at all and its\n * cron run should go red.\n */\nexport function createGuardedAlertSink(\n inner: AlertSink,\n onError: (error: unknown) => void = (e) => console.error('[turn-health] alert delivery failed', e),\n): AlertSink {\n return {\n async deliver(alert) {\n try {\n await inner.deliver(alert)\n } catch (error) {\n onError(error)\n }\n },\n }\n}\n","/**\n * The LIVE half: judge each turn the moment it settles.\n *\n * This adds no control flow. `createChatTurnRoutes` already exposes a\n * `lifecycle` seam that fires exactly one of `onTurnComplete`/`onTurnError`\n * after a turn settles, and already swallows hook errors so telemetry cannot\n * fail a turn. That seam was shipped and then wired by nobody, which is a fair\n * description of why the outage lasted 17 days. This function fills it.\n *\n * The shape is declared structurally rather than imported from\n * `/chat-routes`, so `/turn-health` stays free of the server chat vertical and\n * can be used by any turn driver that reports the same three moments.\n */\n\nimport { classifyTurnOutcome } from './classify.js'\nimport { type AlertSink, createGuardedAlertSink, turnAlert } from './sink.js'\n\n/** Structural mirror of `/chat-routes`' `ChatTurnLifecycle` complete payload. */\nexport interface TurnHealthCompleteInfo {\n finalText: string\n usage?: { outputTokens?: number | null } | null\n durationMs: number\n threadId?: string\n turnStreamId?: string\n executionId?: string\n /** `/chat-routes` sets this when a `contextGate` short-circuited the turn and\n * the producer never ran. */\n gated?: boolean\n}\n\n/** Structural mirror of the lifecycle error payload. */\nexport interface TurnHealthErrorInfo {\n error: unknown\n durationMs: number\n threadId?: string\n turnStreamId?: string\n executionId?: string\n}\n\n/** What {@link createTurnHealthLifecycle} returns — assignable to\n * `createChatTurnRoutes`' `lifecycle` option. */\nexport interface TurnHealthLifecycle {\n onTurnComplete(info: TurnHealthCompleteInfo): Promise<void>\n onTurnError(info: TurnHealthErrorInfo): Promise<void>\n}\n\nexport interface TurnHealthLifecycleOptions {\n /** Names the product in every alert. */\n product: string\n sink: AlertSink\n /** Called for every verdict, healthy or not — the hook for a counter or a\n * metrics push. Alerts are for humans; this is for graphs. */\n onVerdict?(verdict: {\n product: string\n healthy: boolean\n kinds: string[]\n durationMs: number\n }): void\n /** Page when a turn was answered by a gate instead of the model.\n *\n * Default `false`, and the default is the honest one: gating is a legitimate\n * design and a product that gates its intake would otherwise page on every\n * healthy turn. Whether the rate is pathological is domain knowledge, so it\n * stays a product decision — the verdict is ALWAYS reported through\n * {@link TurnHealthLifecycleOptions.onVerdict} so a counter can watch the\n * rate even when nobody is paged. */\n alertOnGatedTurn?: boolean\n}\n\nfunction errorText(error: unknown): string {\n if (error instanceof Error) return error.message\n if (typeof error === 'string') return error\n return String(error)\n}\n\n/**\n * Build the lifecycle hooks that page on a turn which succeeded at nothing.\n *\n * The live lane sees `finalText` and usage but not the persisted parts, so it\n * catches the blank-completion and hard-failure shapes immediately. The\n * parts-dependent shapes (a tool call whose arguments never parsed, a tool\n * call that left no effect) are caught by {@link sweepSilentFailures}, which\n * reads what was actually written to the store — the honest place to ask\n * whether an effect persisted.\n */\nexport function createTurnHealthLifecycle(\n options: TurnHealthLifecycleOptions,\n): TurnHealthLifecycle {\n // Guarded: a paging failure must never take down a customer's turn.\n const sink = createGuardedAlertSink(options.sink)\n\n return {\n async onTurnComplete(info) {\n const verdict = classifyTurnOutcome({\n finalText: info.finalText,\n outputTokens: info.usage?.outputTokens ?? null,\n durationMs: info.durationMs,\n ...(info.gated ? { gated: true } : {}),\n })\n options.onVerdict?.({\n product: options.product,\n healthy: verdict.healthy,\n kinds: verdict.reasons.map((r) => r.kind),\n durationMs: info.durationMs,\n })\n if (verdict.healthy || verdict.severity === null) return\n // Counted above, paged only on request — see `alertOnGatedTurn`.\n if (!options.alertOnGatedTurn && verdict.reasons.every((r) => r.kind === 'answered_without_model')) {\n return\n }\n await sink.deliver(\n turnAlert({\n product: options.product,\n severity: verdict.severity,\n reasons: verdict.reasons,\n ...(info.threadId ? { threadId: info.threadId } : {}),\n ...(info.executionId ? { turnId: info.executionId } : {}),\n }),\n )\n },\n\n async onTurnError(info) {\n const verdict = classifyTurnOutcome({\n failed: true,\n failureReason: errorText(info.error),\n durationMs: info.durationMs,\n })\n options.onVerdict?.({\n product: options.product,\n healthy: false,\n kinds: verdict.reasons.map((r) => r.kind),\n durationMs: info.durationMs,\n })\n await sink.deliver(\n turnAlert({\n product: options.product,\n severity: 'critical',\n reasons: verdict.reasons,\n ...(info.threadId ? { threadId: info.threadId } : {}),\n ...(info.executionId ? { turnId: info.executionId } : {}),\n }),\n )\n },\n }\n}\n","/**\n * The SWEEP half: ask the store what it has been quietly accumulating.\n *\n * A live per-turn hook cannot see the failure that matters most, because the\n * worst outage produced NO turns at all to hook: gtm-agent took 9–21 user\n * messages a day for sixteen straight days and wrote zero real assistant\n * replies. Nothing crashed on a schedule; the product simply stopped\n * answering. The only thing that could have noticed is something that\n * periodically counts what arrived against what was answered.\n *\n * That is this. It runs on a cron, reads the shared `/chat-store` schema, and\n * pages when the ratio breaks.\n *\n * The queries live HERE and not in each product because all four products\n * (gtm, tax, legal, workcomp) persist to the same `message`/`thread` tables —\n * four copies of this cron is exactly the duplication the repo's engine/shell\n * rule exists to prevent.\n */\n\nimport { classifyTurnOutcome, describeReason, type TurnHealthReason } from './classify.js'\nimport type { AlertSink, TurnHealthAlert } from './sink.js'\nimport { SIZED_READ_BYTES, sizedBatches } from '../launch-invariants/sized-reads.js'\n\n/** A thread that has taken user messages with no reply since. */\nexport interface UnansweredThread {\n threadId: string\n /** User messages newer than the newest real assistant reply. */\n pendingMessages: number\n /** Age of the OLDEST unanswered user message, in ms. */\n oldestAgeMs: number\n}\n\n/** A persisted assistant row, as the sweep needs to judge it. */\nexport interface PersistedTurnRow {\n id: string\n threadId: string\n content: string\n /** Raw `parts` column. A JSON string or an already-parsed array; the sweep\n * accepts both because D1 drivers differ. Left undefined by a source that\n * lists rows by {@link partsSize} and serves parts through\n * {@link TurnHealthSource.readParts}. */\n parts: unknown\n /** Stored length of `parts` (SQLite `length()`), set when the row was listed\n * without them. The sweep batches {@link TurnHealthSource.readParts} by it. */\n partsSize?: number | null\n outputTokens?: number | null\n model?: string | null\n createdAt: number\n}\n\n/** What the sweep needs from a store. A product on a non-standard schema\n * implements these two reads; everything else is shared. */\nexport interface TurnHealthSource {\n findUnansweredThreads(input: {\n minAgeMs: number\n /** Ignore user messages older than this. See {@link SweepOptions.maxAgeMs}. */\n maxAgeMs: number\n now: number\n }): Promise<UnansweredThread[]>\n listRecentAssistantTurns(input: { sinceMs: number; now: number; limit: number }): Promise<\n PersistedTurnRow[]\n >\n /**\n * The stored `parts` of these rows, by id, for a source that lists rows\n * without them. The sweep asks for at most {@link TURN_HEALTH_PARTS_BATCH_SIZE}\n * of parts at a time and judges each batch before it reads the next, so memory\n * holds one batch rather than the whole window.\n *\n * On 2026-10-10 gtm-agent's 500 newest assistant rows carried 122 MB of\n * parts (the largest 2.8 MB). Read in one query they exceeded the Worker's\n * 128 MB, which stopped the hourly cron and every sweep queued after this one.\n */\n readParts?(ids: readonly string[]): Promise<Map<string, unknown>>\n}\n\n/**\n * The part fields classifyTurnOutcome reads, as SQL over one `json_each` row.\n * Each string field is taken only when its JSON type is text, so a non-string\n * value reads exactly as the classifier would see it in the full part.\n */\n/** `expr` evaluated only on an object part: json_type and json_extract raise on a bare string element. */\nconst onObject = (expr: string) => `CASE WHEN p.type = 'object' THEN ${expr} END`\n/** The value at `path` when it is a JSON string, else NULL. */\nconst textAt = (path: string, take = `json_extract(p.value, '${path}')`) => onObject(`CASE WHEN json_type(p.value, '${path}') = 'text' THEN ${take} END`)\nconst PART_PROJECTION = [\n `p.type AS partKind`,\n `${textAt('$.type')} AS type`,\n `coalesce(${onObject(`CASE WHEN json_type(p.value, '$.text') = 'text' AND length(trim(json_extract(p.value, '$.text'), char(32, 9, 10, 13))) > 0 THEN 1 ELSE 0 END`)}, 0) AS hasText`,\n `${textAt('$.tool')} AS tool`,\n `${onObject(`json_type(p.value, '$.state')`)} AS stateKind`,\n `${textAt('$.state.status')} AS status`,\n `${textAt('$.state.error', `substr(json_extract(p.value, '$.state.error'), 1, 200)`)} AS stateError`,\n `${onObject(`json_type(p.value, '$.state.input')`)} AS inputKind`,\n `${textAt('$.state.input.error', `substr(json_extract(p.value, '$.state.input.error'), 1, 200)`)} AS inputError`,\n `${textAt('$.state.input.tool')} AS inputTool`,\n `${textAt('$.state.input', `json_valid(json_extract(p.value, '$.state.input'))`)} AS inputValid`,\n `${textAt('$.state.input', `substr(json_extract(p.value, '$.state.input'), 1, 120)`)} AS inputSample`,\n].join(',\\n ')\n\ninterface ProjectedPart {\n partKind: string | null\n type: string | null\n hasText: number\n tool: string | null\n stateKind: string | null\n status: string | null\n stateError: string | null\n inputKind: string | null\n inputError: string | null\n inputTool: string | null\n inputValid: number | null\n inputSample: string | null\n}\n\n/** A part rebuilt from its projection, judged by classifyTurnOutcome as the stored part would be. */\nfunction slimPart(row: ProjectedPart): unknown {\n // classifyTurnOutcome treats an array part as a record with no type (an opaque part) and skips any other non-object.\n if (row.partKind === 'array') return []\n if (row.partKind !== 'object') return null\n const part: Record<string, unknown> = {}\n if (row.type !== null) part.type = row.type\n if (row.hasText) part.text = 'x'\n if (row.tool !== null) part.tool = row.tool\n if (row.stateKind === 'object') {\n const state: Record<string, unknown> = {}\n if (row.status !== null) state.status = row.status\n if (row.stateError !== null) state.error = row.stateError\n if (row.inputKind === 'object') {\n const input: Record<string, unknown> = {}\n if (row.inputError !== null) input.error = row.inputError\n if (row.inputTool !== null) input.tool = row.inputTool\n state.input = input\n } else if (row.inputKind === 'text') {\n // A parseable string reads as parseable; an unparseable one keeps its sample and a NUL after it, so its prefix\n // can never parse by accident.\n state.input = row.inputValid ? '{}' : `${row.inputSample ?? ''}\\u0000`\n } else if (row.inputKind !== null) {\n state.input = null\n }\n part.state = state\n }\n return part\n}\n\n/** Most stored parts the sweep reads in one batch; a larger row is read alone. */\nexport const TURN_HEALTH_PARTS_BATCH_SIZE = SIZED_READ_BYTES\n\n/** Consecutive rows whose listed parts size fits one read. */\nfunction partsBatches(rows: readonly PersistedTurnRow[]): PersistedTurnRow[][] {\n return sizedBatches(rows.map((row) => ({ key: row, size: row.partsSize })), { bytes: TURN_HEALTH_PARTS_BATCH_SIZE })\n}\n\n/** The listed rows with their parts, read one batch at a time when the source listed them without. */\nasync function* withParts(rows: readonly PersistedTurnRow[], source: TurnHealthSource): AsyncGenerator<PersistedTurnRow> {\n for (const batch of partsBatches(rows)) {\n const unread = batch.filter((row) => row.parts === undefined && (row.partsSize ?? 0) > 0).map((row) => row.id)\n // A read failure propagates, like the listing's, so the caller retries the sweep.\n const read = unread.length > 0 && source.readParts ? await source.readParts(unread) : null\n for (const row of batch) yield read?.has(row.id) ? { ...row, parts: read.get(row.id) } : row\n }\n}\n\nexport interface SweepOptions {\n product: string\n source: TurnHealthSource\n sink: AlertSink\n /** A user message must go unanswered this long before it counts. Guards\n * against alerting on a turn that is simply still streaming. Default 15 min. */\n minAgeMs?: number\n /**\n * A user message OLDER than this is abandoned, not unanswered — it stops\n * counting. Default 7 days.\n *\n * Without this bound the sweep is worse than useless. gtm-agent's table\n * holds 384 unanswered messages whose oldest is 1,676 h (70 days) old;\n * paging hourly on a backlog nobody will ever reply to is exactly how an\n * alert channel gets muted, and a muted channel is the state this module\n * exists to escape. The alert has to mean \"something broke recently\".\n */\n maxAgeMs?: number\n /** How far back to judge settled turns. Default 24 h. */\n lookbackMs?: number\n /** Cap on rows judged per sweep. Default 500. */\n limit?: number\n /** Fraction of recent turns allowed to be silently broken before paging.\n * Default 0.05 — the measured blank-completion rate on the tax tool surface\n * was 12.2%, so 5% separates a real regression from noise. */\n emptyRateThreshold?: number\n /** Absolute floor: never page on a rate computed from fewer turns than this. */\n minTurnsForRate?: number\n /** Declare that this product's deliverable comes from TOOL calls, which\n * switches on the dead-tool-surface detector.\n *\n * Opt-in because only the product knows: a copilot that answers from context\n * is perfectly healthy with zero tool calls, while an agent whose entire job\n * is to file, draft, or submit something is broken the moment its tool\n * surface goes quiet — and broken INVISIBLY, because every turn still\n * returns fluent prose and HTTP 200.\n *\n * This is the fourth failure shape, and the only one no per-turn rule can\n * see.\n *\n * The verdict is drawn ONLY over turns whose parts were present and\n * readable. An earlier revision counted rows that stored no parts, and the\n * production example this comment used to cite was that bug rather than a\n * finding: tax-agent's 97 parts-less rows all predate its parts persistence\n * (they stop at 2026-07-17T02:20Z, the encrypted rows start 02:58Z), while\n * the same database's `turn_events` table holds 243 `tool_call` frames over\n * 15 turns. The tool surface was never dead; the rows were empty. */\n expectsToolCalls?: boolean\n /** Turns needed before a dead tool surface is called. Default 10. */\n minTurnsForToolSurface?: number\n /**\n * Make an at-rest parts encoding readable, so this sweep can judge a product\n * that does not store parts in the clear.\n *\n * Without it, a product that encrypts `parts` (tax-agent wraps the whole\n * array in one `__encrypted_parts__` part) is permanently UNMEASURABLE by the\n * tool-surface rule: every row is opaque, so the honest verdict is \"cannot\n * certify\" forever. This seam is how such a product gets a real verdict\n * instead of permanent blindness — the sweep stays domain-free and the\n * product supplies the decoder.\n *\n * Return the decoded parts value (it is parsed exactly like a stored one).\n * Returning `null`/`undefined` or THROWING leaves the row's stored value in\n * place, so a decoder that fails reports the row as opaque. It must never\n * report success as an empty array: that manufactures the exact absent-parts\n * blindness this module now refuses to draw conclusions from.\n */\n decodeParts?: (raw: unknown, row: PersistedTurnRow) => Promise<unknown> | unknown\n now?: number\n}\n\n/** Apply the optional decoder, falling back to the stored value on any failure\n * so a broken decoder degrades to blindness (reported) rather than to a fake\n * empty parts array (silent). */\nasync function decodeRowParts(\n decode: SweepOptions['decodeParts'],\n row: PersistedTurnRow,\n): Promise<unknown> {\n if (!decode) return row.parts\n try {\n const decoded = await decode(row.parts, row)\n return decoded ?? row.parts\n } catch {\n return row.parts\n }\n}\n\n/** What the sweep found. Returned as well as alerted, so a cron can log it and\n * a test can assert on it. */\nexport interface SweepResult {\n product: string\n unansweredThreads: number\n pendingUserMessages: number\n oldestUnansweredMs: number\n turnsJudged: number\n unhealthyTurns: number\n emptyCompletions: number\n malformedToolCalls: number\n toolCallsWithoutEffect: number\n /** Tool calls the harness rejected while settling them as `completed`. */\n rejectedToolCalls: number\n /** Turns carrying at least one tool part. */\n turnsWithToolCalls: number\n /** Total tool parts across the window. */\n toolCalls: number\n /** Turns the classifier could not interpret at all (encrypted at rest, or a\n * part vocabulary this module does not know). These are EXCLUDED from\n * `turnsJudged`-based rates — a rate computed over rows nobody could read is\n * a fabricated number. */\n unreadableTurns: number\n /** Turns whose PARTS could not be interpreted. A superset of\n * {@link unreadableTurns} (a row can have readable text and opaque parts).\n * No tool verdict is drawn over these. */\n opaquePartsTurns: number\n /** Turns that persisted NO parts at all. Distinct from\n * {@link opaquePartsTurns}: nothing failed to parse, there was simply\n * nothing there. Also excluded from every tool verdict. */\n noPartsTurns: number\n /** Turns a tool verdict may actually be drawn from — parts present AND\n * interpretable. The denominator behind `dead_tool_surface`. */\n toolReadableTurns: number\n alerts: TurnHealthAlert[]\n}\n\nfunction parseParts(raw: unknown): unknown[] {\n if (Array.isArray(raw)) return raw\n if (typeof raw !== 'string' || raw.trim().length === 0) return []\n try {\n const parsed = JSON.parse(raw)\n return Array.isArray(parsed) ? parsed : []\n } catch {\n // A parts column that is not JSON is itself a corruption worth seeing, but\n // it is not this detector's job — treat as no parts rather than throwing.\n return []\n }\n}\n\nconst HOUR_MS = 3_600_000\n\n/**\n * Assistant-row openers agent-app writes ITSELF when a sandbox turn fails.\n *\n * Kept byte-identical to the strings `createSandboxChatProducer` composes\n * (`src/chat-routes/sandbox-producer.ts`). They are shell vocabulary, not\n * product domain, so recognising them is this package's job — a product on\n * the shared producer gets a correct sweep with no configuration.\n *\n * `tests/turn-health/turn-health.test.ts` pins these against the producer, so\n * changing the producer's wording without changing this list fails CI rather\n * than silently making dead threads look answered.\n */\n/** D1's maximum LIKE pattern length, including the trailing `%`. Measured, not\n * documented: 50 succeeds, 51 raises `SQLITE_ERROR: LIKE or GLOB pattern too\n * complex`. */\nexport const D1_MAX_LIKE_PATTERN_LENGTH = 50\n\nexport const SHELL_ERROR_REPLY_PREFIXES: readonly string[] = [\n 'The sandbox model stream stopped before a clean completion.',\n 'The sandbox agent returned an error before producing a visible answer.',\n]\n\n/**\n * Run one sweep and deliver whatever it finds.\n *\n * Errors from the sink are NOT swallowed here (unlike the live lane): a sweep\n * that could not deliver has accomplished nothing, and its cron invocation\n * should go red rather than report a clean run.\n */\nexport async function sweepSilentFailures(options: SweepOptions): Promise<SweepResult> {\n const now = options.now ?? Date.now()\n const minAgeMs = options.minAgeMs ?? 15 * 60_000\n const maxAgeMs = options.maxAgeMs ?? 7 * 24 * HOUR_MS\n const lookbackMs = options.lookbackMs ?? 24 * HOUR_MS\n const limit = options.limit ?? 500\n const emptyRateThreshold = options.emptyRateThreshold ?? 0.05\n const minTurnsForRate = options.minTurnsForRate ?? 10\n const minTurnsForToolSurface = options.minTurnsForToolSurface ?? 10\n // Half the window opaque means the sweep is guessing. Fixed rather than\n // configurable: a product must not be able to tune its own blindness report\n // into silence.\n const blindThreshold = 0.5\n\n const [unanswered, turns] = await Promise.all([\n options.source.findUnansweredThreads({ minAgeMs, maxAgeMs, now }),\n options.source.listRecentAssistantTurns({ sinceMs: now - lookbackMs, now, limit }),\n ])\n\n const alerts: TurnHealthAlert[] = []\n\n // ── silence: messages in, nothing out ──────────────────────────────────\n const pendingUserMessages = unanswered.reduce((sum, t) => sum + t.pendingMessages, 0)\n const oldestUnansweredMs = unanswered.reduce((max, t) => Math.max(max, t.oldestAgeMs), 0)\n\n if (unanswered.length > 0) {\n const hours = (oldestUnansweredMs / HOUR_MS).toFixed(1)\n alerts.push({\n product: options.product,\n // A day of total silence is not a warning.\n severity: oldestUnansweredMs >= 24 * HOUR_MS ? 'critical' : 'warning',\n key: `sweep:${options.product}:unanswered_threads`,\n title: `${options.product}: ${pendingUserMessages} user message(s) unanswered across ${unanswered.length} thread(s)`,\n details: [\n `oldest unanswered message: ${hours}h`,\n ...unanswered\n .slice(0, 5)\n .map(\n (t) =>\n `thread ${t.threadId}: ${t.pendingMessages} pending, oldest ${(\n t.oldestAgeMs / HOUR_MS\n ).toFixed(1)}h`,\n ),\n ],\n data: {\n unansweredThreads: unanswered.length,\n pendingUserMessages,\n oldestUnansweredMs,\n },\n at: now,\n })\n }\n\n // ── success that delivered nothing ─────────────────────────────────────\n let emptyCompletions = 0\n let malformedToolCalls = 0\n let toolCallsWithoutEffect = 0\n let rejectedToolCalls = 0\n let unhealthyTurns = 0\n let turnsWithToolCalls = 0\n let toolCalls = 0\n let unreadableTurns = 0\n // Turns whose PARTS were interpretable — the only rows a tool verdict may be\n // drawn from. Distinct from `unreadableTurns`, which is the harder blindness\n // (nothing judgeable at all).\n let toolReadableTurns = 0\n let opaquePartsTurns = 0\n // Rows that persisted NO parts at all. Not opaque (nothing failed to parse)\n // and not evidence either — counted separately so the coverage line can say\n // which of the two blindnesses applies.\n let noPartsTurns = 0\n const opaqueTypes = new Set<string>()\n const malformedSamples: TurnHealthReason[] = []\n const rejectedSamples: TurnHealthReason[] = []\n\n for await (const row of withParts(turns, options.source)) {\n const verdict = classifyTurnOutcome({\n finalText: row.content,\n parts: parseParts(await decodeRowParts(options.decodeParts, row)),\n outputTokens: row.outputTokens ?? null,\n })\n toolCalls += verdict.toolCalls\n if (verdict.toolCalls > 0) turnsWithToolCalls += 1\n // A tool verdict needs evidence that was READ. `partsReadable` alone is\n // satisfied vacuously by a row that persisted no parts, which is how a\n // product with 243 real tool calls was paged as having a dead tool surface.\n if (verdict.partsReadable && verdict.interpretedParts > 0) toolReadableTurns += 1\n else if (verdict.partsReadable) noPartsTurns += 1\n else {\n opaquePartsTurns += 1\n for (const t of verdict.opaquePartTypes) opaqueTypes.add(t)\n }\n if (verdict.unreadable) {\n unreadableTurns += 1\n continue\n }\n if (verdict.healthy) continue\n unhealthyTurns += 1\n for (const reason of verdict.reasons) {\n if (reason.kind === 'empty_completion') emptyCompletions += 1\n if (reason.kind === 'malformed_tool_call') {\n malformedToolCalls += 1\n if (malformedSamples.length < 3) malformedSamples.push(reason)\n }\n if (reason.kind === 'tool_call_no_effect') toolCallsWithoutEffect += 1\n if (reason.kind === 'tool_call_rejected') {\n rejectedToolCalls += 1\n if (rejectedSamples.length < 3) rejectedSamples.push(reason)\n }\n }\n }\n\n // Turns this sweep could actually judge. Every rate below divides by THIS,\n // never by the raw row count.\n const readableTurns = turns.length - unreadableTurns\n\n // A malformed tool call is never acceptable at any rate — it means a\n // deliverable was requested and silently discarded. Page on the first one.\n if (malformedToolCalls > 0) {\n alerts.push({\n product: options.product,\n severity: 'critical',\n key: `sweep:${options.product}:malformed_tool_call`,\n title: `${options.product}: ${malformedToolCalls} tool call(s) had unparseable arguments — deliverables silently dropped`,\n details: malformedSamples.map(describeReason),\n data: { malformedToolCalls, turnsJudged: turns.length },\n at: now,\n })\n }\n\n // A rejected call means a deliverable was requested and thrown away while the\n // turn reported success. Never acceptable at any rate.\n if (rejectedToolCalls > 0) {\n alerts.push({\n product: options.product,\n severity: 'critical',\n key: `sweep:${options.product}:tool_call_rejected`,\n title: `${options.product}: ${rejectedToolCalls} tool call(s) were REJECTED but settled as completed — deliverables silently dropped`,\n details: rejectedSamples.map(describeReason),\n data: { rejectedToolCalls, turnsJudged: readableTurns },\n at: now,\n })\n }\n\n if (readableTurns >= minTurnsForRate) {\n const rate = emptyCompletions / readableTurns\n if (rate > emptyRateThreshold) {\n alerts.push({\n product: options.product,\n severity: 'critical',\n key: `sweep:${options.product}:empty_completion_rate`,\n title: `${options.product}: ${(rate * 100).toFixed(1)}% of turns completed with no output`,\n details: [\n `${emptyCompletions} of ${readableTurns} readable settled turns delivered nothing`,\n `threshold ${(emptyRateThreshold * 100).toFixed(1)}%`,\n ],\n data: { emptyCompletions, turnsJudged: readableTurns, rate },\n at: now,\n })\n }\n }\n\n // ── the fourth shape: a tool surface that has gone quiet ───────────────\n //\n // Nothing errors, every turn answers fluently, and the product stops DOING\n // anything. Only visible across a window, which is why it needs its own pass\n // rather than a rule inside the per-turn classifier.\n // Judged ONLY over turns whose parts could be interpreted, and the count of\n // rows that could not is stated in the alert — a verdict that names its own\n // coverage can be trusted; one that hides it cannot.\n if (options.expectsToolCalls && toolReadableTurns >= minTurnsForToolSurface && toolCalls === 0) {\n alerts.push({\n product: options.product,\n severity: 'critical',\n key: `sweep:${options.product}:dead_tool_surface`,\n title: `${options.product}: ZERO tool calls across ${toolReadableTurns} turns — the tool surface is dead`,\n details: [\n `${toolReadableTurns} assistant turns with readable parts in the lookback, none of which called a tool`,\n 'the product declares its deliverable comes from tool calls, so it has answered without doing anything',\n ...(opaquePartsTurns > 0\n ? [`${opaquePartsTurns} further turn(s) had unreadable parts and were not judged`]\n : []),\n ...(noPartsTurns > 0\n ? [`${noPartsTurns} further turn(s) persisted no parts at all and were not judged`]\n : []),\n ],\n data: {\n turnsJudged: toolReadableTurns,\n toolCalls: 0,\n turnsWithToolCalls: 0,\n turnsNotJudged: opaquePartsTurns + noPartsTurns,\n opaquePartsTurns,\n noPartsTurns,\n },\n at: now,\n })\n }\n\n // A product that ASKED for a tool-surface verdict and did not get one must be\n // told that, or the absence of a page reads as a pass. This is the honest\n // form of the alert above: same question, and the answer is \"I could not\n // see\", which is a real finding about the product's observability rather than\n // a fabricated finding about its behaviour.\n if (\n options.expectsToolCalls &&\n toolReadableTurns < minTurnsForToolSurface &&\n opaquePartsTurns + noPartsTurns > 0\n ) {\n alerts.push({\n product: options.product,\n severity: 'warning',\n key: `sweep:${options.product}:tool_surface_unmeasurable`,\n title: `${options.product}: tool surface could not be certified — only ${toolReadableTurns} of ${turns.length} turns carried readable parts`,\n details: [\n ...(noPartsTurns > 0\n ? [`${noPartsTurns} turn(s) persisted no parts at all — nothing to read a tool call from`]\n : []),\n ...(opaquePartsTurns > 0\n ? [\n `${opaquePartsTurns} turn(s) stored parts this sweep cannot interpret (${\n [...opaqueTypes].join(', ') || 'unnamed'\n }) — supply \\`decodeParts\\` to make them readable`,\n ]\n : []),\n 'this is NOT a dead tool surface finding; it is the absence of evidence either way',\n ],\n data: {\n toolReadableTurns,\n noPartsTurns,\n opaquePartsTurns,\n turnsSeen: turns.length,\n opaqueTypes: [...opaqueTypes],\n },\n at: now,\n })\n }\n\n // ── the detector reporting on ITSELF ───────────────────────────────────\n //\n // The one verdict this module must never give is \"healthy\" derived from rows\n // it could not read. If most of the window was opaque, that fact is the\n // alert — silence here would be the module committing the exact failure it\n // was built to catch.\n if (opaquePartsTurns > 0 && opaquePartsTurns >= turns.length * blindThreshold) {\n alerts.push({\n product: options.product,\n severity: 'warning',\n key: `sweep:${options.product}:detector_blind`,\n title: `${options.product}: ${opaquePartsTurns} of ${turns.length} turns have unreadable parts — this sweep cannot certify them`,\n details: [\n `uninterpretable part types: ${[...opaqueTypes].join(', ') || '(none named)'}`,\n 'these rows are excluded from every verdict above; treat them as UNMEASURED, not healthy',\n ],\n data: {\n opaquePartsTurns,\n unreadableTurns,\n turnsSeen: turns.length,\n opaqueTypes: [...opaqueTypes],\n },\n at: now,\n })\n }\n\n for (const alert of alerts) await options.sink.deliver(alert)\n\n return {\n product: options.product,\n unansweredThreads: unanswered.length,\n pendingUserMessages,\n oldestUnansweredMs,\n turnsJudged: turns.length,\n unhealthyTurns,\n emptyCompletions,\n malformedToolCalls,\n toolCallsWithoutEffect,\n rejectedToolCalls,\n turnsWithToolCalls,\n toolCalls,\n unreadableTurns,\n opaquePartsTurns,\n noPartsTurns,\n toolReadableTurns,\n alerts,\n }\n}\n\n// ── D1 source for the shared chat-store schema ────────────────────────────\n\n/** Minimal structural D1 contract (Cloudflare's `D1Database` satisfies it). */\nexport interface D1LikeForHealth {\n prepare(sql: string): {\n bind(...values: unknown[]): {\n all<T = Record<string, unknown>>(): Promise<{ results: T[] }>\n }\n }\n}\n\n/**\n * The sweep source for products on the canonical `/chat-store` tables.\n *\n * \"Answered\" deliberately means an assistant row with NON-EMPTY content. A\n * blank assistant row is what a broken turn writes, so counting it as an\n * answer would let the exact failure being hunted mark itself resolved. That\n * single predicate is the difference between this catching the gtm outage and\n * sleeping through it — during those sixteen days the table was NOT empty.\n *\n * The query deliberately does NOT join the thread table. Products do not all\n * keep one: tax-agent's `thread` table holds zero rows because it groups by\n * its own `tax_sessions`, and an inner join against it silently reported \"0\n * unanswered threads, healthy\" while 18 real messages sat unanswered. A\n * detector that reports healthy because its join found nothing is the same\n * bug class it was built to catch.\n */\nexport function createD1TurnHealthSource(\n db: D1LikeForHealth,\n options: {\n messageTable?: string\n threadTable?: string\n /**\n * Content prefixes that mark an assistant row as an ERROR SURFACE rather\n * than an answer. A row matching one of these stops counting as a reply,\n * so the thread keeps reporting as unanswered.\n *\n * This exists because the obvious rule — \"an assistant row with non-empty\n * content is an answer\" — is wrong in the exact case that matters. On\n * 2026-07-27 gtm-agent's newest assistant row read:\n *\n * \"The sandbox model stream stopped before a clean completion.\n * Error: All 2 model(s) failed. gpt-5-mini: TANGLE_HUB_URL is required …\"\n *\n * 246 characters of well-formed prose that answers nothing. Counting it\n * marks a dead product healthy — the same failure-returning-success shape\n * this module exists to catch, recursing into the detector itself.\n *\n * There is no schema-level way to recognise it: `output_tokens IS NULL`\n * looked promising until legal-agent showed 22 of 25 GENUINE replies with\n * null usage — it would have reported a working product broken.\n *\n * Defaults to {@link SHELL_ERROR_REPLY_PREFIXES}, the openers agent-app\n * ITSELF writes in `createSandboxChatProducer`. Those are not domain —\n * this package composed them, so this package is what must recognise\n * them, and every product on the shared producer is correct with no\n * configuration. Pass your own list to ADD product-specific error prose;\n * pass `[]` to disable the rule.\n *\n * Prefixes are bound as query parameters, never interpolated.\n */\n errorReplyPrefixes?: readonly string[]\n /**\n * Read each row's whole `parts` instead of the fields the classifier reads.\n * Only a product whose `decodeParts` needs the stored bytes (an encrypted\n * parts envelope) sets this; the default reads a small projection.\n */\n fullParts?: boolean\n } = {},\n): TurnHealthSource {\n // Table names are identifiers and cannot be bound as parameters. They come\n // from deploy-time product config, never from a request, and are validated\n // here so this can never become an injection point.\n const message = safeIdentifier(options.messageTable ?? 'message')\n const thread = safeIdentifier(options.threadTable ?? 'thread')\n // D1 rejects a LIKE pattern longer than 50 characters with\n // `SQLITE_ERROR: LIKE or GLOB pattern too complex`, and the pattern is the\n // prefix PLUS the trailing `%`. Measured against production D1 on\n // 2026-07-27: a 49-char prefix (50-char pattern) succeeds, 50 fails.\n //\n // Both shipped defaults are longer than that (55 and 70 characters), so\n // before this clamp `findUnansweredThreads` threw on every product database\n // — the detector could not run at all against the only store the fleet uses.\n //\n // Truncating is safe in the one direction that matters: a shorter prefix\n // matches MORE rows as non-answers, so a thread is reported unanswered\n // rather than silently marked healthy. The first 49 characters of each\n // default are still unambiguous.\n const errorPrefixes = [...(options.errorReplyPrefixes ?? SHELL_ERROR_REPLY_PREFIXES)].map((p) =>\n p.slice(0, D1_MAX_LIKE_PATTERN_LENGTH - 1),\n )\n\n return {\n async findUnansweredThreads({ minAgeMs, maxAgeMs, now }) {\n const cutoffSeconds = Math.floor((now - minAgeMs) / 1000)\n const floorSeconds = Math.floor((now - maxAgeMs) / 1000)\n // Each prefix becomes one bound `NOT LIKE ?||'%'` term. Parameters, not\n // interpolation — a product-supplied string never reaches the SQL text.\n const errorClause = errorPrefixes\n .map((_, i) => ` AND a.content NOT LIKE ?${i + 3} || '%'`)\n .join('')\n const { results } = await db\n .prepare(\n `SELECT m.thread_id AS threadId,\n COUNT(*) AS pendingMessages,\n MIN(m.created_at) AS oldestCreatedAt\n FROM ${message} m\n WHERE m.role = 'user'\n AND m.created_at <= ?1\n AND m.created_at >= ?2\n AND m.created_at > COALESCE(\n (SELECT MAX(a.created_at)\n FROM ${message} a\n WHERE a.thread_id = m.thread_id\n AND a.role = 'assistant'\n AND length(trim(a.content)) > 0${errorClause}), 0)\n GROUP BY m.thread_id\n ORDER BY oldestCreatedAt ASC`,\n )\n .bind(cutoffSeconds, floorSeconds, ...errorPrefixes)\n .all<{ threadId: string; pendingMessages: number; oldestCreatedAt: number }>()\n\n return results.map((row) => ({\n threadId: row.threadId,\n pendingMessages: Number(row.pendingMessages),\n oldestAgeMs: now - Number(row.oldestCreatedAt) * 1000,\n }))\n },\n\n async listRecentAssistantTurns({ sinceMs, limit }) {\n const sinceSeconds = Math.floor(sinceMs / 1000)\n const { results } = await db\n .prepare(\n `SELECT id, thread_id AS threadId, content, length(parts) AS partsSize,\n output_tokens AS outputTokens, model, created_at AS createdAt\n FROM ${message}\n WHERE role = 'assistant' AND created_at >= ?1\n ORDER BY created_at DESC\n LIMIT ?2`,\n )\n .bind(sinceSeconds, limit)\n .all<Record<string, unknown>>()\n\n return results.map((row) => ({\n id: String(row.id),\n threadId: String(row.threadId),\n content: typeof row.content === 'string' ? row.content : '',\n parts: undefined,\n partsSize: row.partsSize === null ? null : Number(row.partsSize),\n outputTokens: row.outputTokens === null ? null : Number(row.outputTokens),\n model: (row.model as string | null) ?? null,\n createdAt: Number(row.createdAt) * 1000,\n }))\n },\n\n async readParts(ids) {\n if (ids.length === 0) return new Map()\n const placeholders = ids.map((_, i) => `?${i + 1}`).join(', ')\n if (options.fullParts) {\n const { results } = await db\n .prepare(`SELECT id, parts FROM ${message} WHERE id IN (${placeholders})`)\n .bind(...ids)\n .all<{ id: string; parts: unknown }>()\n return new Map(results.map((row) => [String(row.id), row.parts]))\n }\n // One row per part with only what classifyTurnOutcome reads, so a day of\n // tool output never leaves the database: on 2026-10-11 the full read\n // returned 141.9 MB per run for 500 turns.\n const { results } = await db\n .prepare(`SELECT m.id AS id, CAST(p.key AS INTEGER) AS idx, ${PART_PROJECTION}\n FROM ${message} m, json_each(CASE WHEN json_valid(m.parts) THEN CASE WHEN json_type(m.parts) = 'array' THEN m.parts ELSE '[]' END ELSE '[]' END) p\n WHERE m.id IN (${placeholders})\n ORDER BY m.id, idx`)\n .bind(...ids)\n .all<ProjectedPart & { id: string }>()\n const parts = new Map<string, unknown[]>(ids.map((id) => [id, []]))\n for (const row of results) parts.get(String(row.id))?.push(slimPart(row))\n return parts\n },\n }\n\n function safeIdentifier(name: string): string {\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) {\n throw new Error(`unsafe table identifier: ${name}`)\n }\n return name\n }\n}\n"],"mappings":";;;;;;;;;AAwMA,IAAM,sBAAsB,oBAAI,IAAI,CAAC,QAAQ,SAAS,gBAAgB,QAAQ,aAAa,CAAC;AAc5F,IAAM,8BAA8B,oBAAI,IAAI;AAAA,EAC1C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAED,IAAM,eAAe;AAErB,SAAS,SAAS,OAAgD;AAChE,SAAO,OAAO,UAAU,YAAY,UAAU,OAAQ,QAAoC;AAC5F;AAEA,SAAS,eAAe,OAA+B;AACrD,SAAO,OAAO,UAAU,YAAY,MAAM,KAAK,EAAE,SAAS,IAAI,QAAQ;AACxE;AAQA,SAAS,kBAAkB,OAAwB;AACjD,QAAM,UAAU,MAAM,KAAK;AAC3B,MAAI,QAAQ,WAAW,EAAG,QAAO;AACjC,MAAI;AACF,SAAK,MAAM,OAAO;AAClB,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAMA,IAAM,wBAAwB,oBAAI,IAAI,CAAC,aAAa,YAAY,WAAW,MAAM,CAAC;AAS3E,SAAS,oBAAoB,O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A,QAC/D,cAAc,IAAI,iBAAiB,OAAO,OAAO,OAAO,IAAI,YAAY;AAAA,QACxE,OAAQ,IAAI,SAA2B;AAAA,QACvC,WAAW,OAAO,IAAI,SAAS,IAAI;AAAA,MACrC,EAAE;AAAA,IACJ;AAAA,IAEA,MAAM,UAAU,KAAK;AACnB,UAAI,IAAI,WAAW,EAAG,QAAO,oBAAI,IAAI;AACrC,YAAM,eAAe,IAAI,IAAI,CAAC,GAAG,MAAM,IAAI,IAAI,CAAC,EAAE,EAAE,KAAK,IAAI;AAC7D,UAAI,QAAQ,WAAW;AACrB,cAAM,EAAE,SAAAA,SAAQ,IAAI,MAAM,GACvB,QAAQ,yBAAyB,OAAO,iBAAiB,YAAY,GAAG,EACxE,KAAK,GAAG,GAAG,EACX,IAAoC;AACvC,eAAO,IAAI,IAAIA,SAAQ,IAAI,CAAC,QAAQ,CAAC,OAAO,IAAI,EAAE,GAAG,IAAI,KAAK,CAAC,CAAC;AAAA,MAClE;AAIA,YAAM,EAAE,QAAQ,IAAI,MAAM,GACvB,QAAQ,qDAAqD,eAAe;AAAA,oBACjE,OAAO;AAAA,6BACE,YAAY;AAAA,+BACV,EACtB,KAAK,GAAG,GAAG,EACX,IAAoC;AACvC,YAAM,QAAQ,IAAI,IAAuB,IAAI,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAClE,iBAAW,OAAO,QAAS,OAAM,IAAI,OAAO,IAAI,EAAE,CAAC,GAAG,KAAK,SAAS,GAAG,CAAC;AACxE,aAAO;AAAA,IACT;AAAA,EACF;AAEA,WAAS,eAAe,MAAsB;AAC5C,QAAI,CAAC,2BAA2B,KAAK,IAAI,GAAG;AAC1C,YAAM,IAAI,MAAM,4BAA4B,IAAI,EAAE;AAAA,IACpD;AACA,WAAO;AAAA,EACT;AACF;","names":["results"]}
@@ -260,4 +260,10 @@ export declare function createD1TurnHealthSource(db: D1LikeForHealth, options?:
260
260
  * Prefixes are bound as query parameters, never interpolated.
261
261
  */
262
262
  errorReplyPrefixes?: readonly string[];
263
+ /**
264
+ * Read each row's whole `parts` instead of the fields the classifier reads.
265
+ * Only a product whose `decodeParts` needs the stored bytes (an encrypted
266
+ * parts envelope) sets this; the default reads a small projection.
267
+ */
268
+ fullParts?: boolean;
263
269
  }): TurnHealthSource;
@@ -1131,6 +1131,16 @@ function createExportEngine(options) {
1131
1131
  return job;
1132
1132
  } catch (err) {
1133
1133
  if (err instanceof LeaseLost) return (await loadJob(workspaceId, id))?.job ?? null;
1134
+ clearInterval(heartbeat);
1135
+ await saving.catch(() => {
1136
+ });
1137
+ const leaseId = job.lease?.id;
1138
+ const stored = leaseId ? await loadJob(workspaceId, id).catch(() => null) : null;
1139
+ if (stored && stored.job.lease?.id === leaseId) {
1140
+ stored.job.lease = void 0;
1141
+ await saveJob(stored.job, stored.etag).catch(() => {
1142
+ });
1143
+ }
1134
1144
  throw err;
1135
1145
  } finally {
1136
1146
  clearInterval(heartbeat);
@@ -1336,7 +1346,10 @@ function createWorkspaceExport(options) {
1336
1346
  return job ? json(await withProgress(job, mount)) : refuse(404, "not_found", "Export not found");
1337
1347
  }
1338
1348
  return refuse(404, "not_found", "Not found");
1339
- } catch {
1349
+ } catch (err) {
1350
+ const known = await Promise.resolve(options.knownSecrets?.({ workspaceId })).catch(() => void 0);
1351
+ const text = err instanceof Error ? err.message : String(err);
1352
+ console.error(`workspace-export: ${method} ${path || "/"} failed: ${createSecretScanner({ knownSecrets: known ?? [] }).maskText(text).text.slice(0, 300)}`);
1340
1353
  return refuse(500, "export_error", "The export request failed");
1341
1354
  }
1342
1355
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/workspace-export/checksum.ts","../../src/workspace-export/secrets.ts","../../src/workspace-export/tar.ts","../../src/workspace-export/zip.ts","../../src/workspace-export/engine.ts","../../src/workspace-export/routes.ts","../../src/workspace-export/storage.ts","../../src/workspace-export/d1.ts","../../src/workspace-export/sources.ts","../../src/workspace-export/sandbox.ts"],"sourcesContent":["/**\n * Incremental CRC-32 (the zip checksum) and SHA-256 (the manifest checksum).\n *\n * Both run over a stream one chunk at a time so an export never buffers a whole\n * file. SHA-256 uses the Workers-native `crypto.DigestStream` when present and a\n * small pure implementation otherwise (Node, tests); both produce identical hex.\n */\n\nconst CRC_TABLE = (() => {\n const table = new Uint32Array(256)\n for (let n = 0; n < 256; n += 1) {\n let c = n\n for (let k = 0; k < 8; k += 1) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1\n table[n] = c >>> 0\n }\n return table\n})()\n\n/** Continue a CRC-32 over `bytes`. Start with `0`; the result is the finished CRC. */\nexport function crc32Update(crc: number, bytes: Uint8Array): number {\n let c = (crc ^ 0xffffffff) >>> 0\n for (let i = 0; i < bytes.length; i += 1) c = (CRC_TABLE[(c ^ bytes[i]!) & 0xff]! ^ (c >>> 8)) >>> 0\n return (c ^ 0xffffffff) >>> 0\n}\n\nexport interface Sha256Hasher {\n update(bytes: Uint8Array): Promise<void>\n digestHex(): Promise<string>\n}\n\ninterface DigestStreamLike extends WritableStream<Uint8Array> {\n digest: Promise<ArrayBuffer>\n}\n\nfunction toHex(bytes: Uint8Array): string {\n let out = ''\n for (const b of bytes) out += b.toString(16).padStart(2, '0')\n return out\n}\n\n/** A streaming SHA-256. Prefers the runtime's native digest stream. */\nexport function createSha256(): Sha256Hasher {\n const DigestStream = (globalThis.crypto as unknown as {\n DigestStream?: new (algorithm: string) => DigestStreamLike\n }).DigestStream\n if (DigestStream) {\n const stream = new DigestStream('SHA-256')\n const writer = stream.getWriter()\n return {\n update: (bytes) => writer.write(bytes),\n async digestHex() {\n await writer.close()\n return toHex(new Uint8Array(await stream.digest))\n },\n }\n }\n const pure = new PureSha256()\n return {\n async update(bytes) {\n pure.update(bytes)\n },\n async digestHex() {\n return toHex(pure.digest())\n },\n }\n}\n\nconst K = new Uint32Array([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,\n])\n\nclass PureSha256 {\n private h = new Uint32Array([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n ])\n private block = new Uint8Array(64)\n private blockLength = 0\n private totalLength = 0\n private w = new Uint32Array(64)\n\n update(bytes: Uint8Array): void {\n this.totalLength += bytes.length\n let offset = 0\n while (offset < bytes.length) {\n const take = Math.min(64 - this.blockLength, bytes.length - offset)\n this.block.set(bytes.subarray(offset, offset + take), this.blockLength)\n this.blockLength += take\n offset += take\n if (this.blockLength === 64) {\n this.compress(this.block)\n this.blockLength = 0\n }\n }\n }\n\n digest(): Uint8Array {\n const bitLength = this.totalLength * 8\n const padLength = this.blockLength < 56 ? 56 - this.blockLength : 120 - this.blockLength\n const pad = new Uint8Array(padLength + 8)\n pad[0] = 0x80\n const view = new DataView(pad.buffer)\n view.setUint32(padLength, Math.floor(bitLength / 0x100000000))\n view.setUint32(padLength + 4, bitLength >>> 0)\n const total = this.totalLength\n this.update(pad)\n this.totalLength = total\n const out = new Uint8Array(32)\n const outView = new DataView(out.buffer)\n for (let i = 0; i < 8; i += 1) outView.setUint32(i * 4, this.h[i]!)\n return out\n }\n\n private compress(chunk: Uint8Array): void {\n const w = this.w\n const view = new DataView(chunk.buffer, chunk.byteOffset, 64)\n for (let i = 0; i < 16; i += 1) w[i] = view.getUint32(i * 4)\n for (let i = 16; i < 64; i += 1) {\n const a = w[i - 15]!\n const b = w[i - 2]!\n const s0 = ((a >>> 7) | (a << 25)) ^ ((a >>> 18) | (a << 14)) ^ (a >>> 3)\n const s1 = ((b >>> 17) | (b << 15)) ^ ((b >>> 19) | (b << 13)) ^ (b >>> 10)\n w[i] = (w[i - 16]! + s0 + w[i - 7]! + s1) >>> 0\n }\n let [a, b, c, d, e, f, g, h] = this.h as unknown as number[]\n for (let i = 0; i < 64; i += 1) {\n const S1 = ((e! >>> 6) | (e! << 26)) ^ ((e! >>> 11) | (e! << 21)) ^ ((e! >>> 25) | (e! << 7))\n const ch = (e! & f!) ^ (~e! & g!)\n const t1 = (h! + S1 + ch + K[i]! + w[i]!) >>> 0\n const S0 = ((a! >>> 2) | (a! << 30)) ^ ((a! >>> 13) | (a! << 19)) ^ ((a! >>> 22) | (a! << 10))\n const maj = (a! & b!) ^ (a! & c!) ^ (b! & c!)\n const t2 = (S0 + maj) >>> 0\n h = g\n g = f\n f = e\n e = (d! + t1) >>> 0\n d = c\n c = b\n b = a\n a = (t1 + t2) >>> 0\n }\n this.h[0] = (this.h[0]! + a!) >>> 0\n this.h[1] = (this.h[1]! + b!) >>> 0\n this.h[2] = (this.h[2]! + c!) >>> 0\n this.h[3] = (this.h[3]! + d!) >>> 0\n this.h[4] = (this.h[4]! + e!) >>> 0\n this.h[5] = (this.h[5]! + f!) >>> 0\n this.h[6] = (this.h[6]! + g!) >>> 0\n this.h[7] = (this.h[7]! + h!) >>> 0\n }\n}\n","/**\n * Keeps credentials out of workspace exports.\n *\n * Three layers, applied to every byte an export writes:\n * 1. Column and JSON-key names that hold credentials are replaced with\n * `[redacted]` (`password`, `*_token`, `*_api_key`, `*_ciphertext`, ...).\n * 2. Values that look like credentials (provider key prefixes, JWTs, private\n * keys) and the exact values the product passes as `knownSecrets` are masked\n * wherever they appear: in row values, in nested JSON, and in file bytes.\n * 3. Well-known credential files inside a sandbox tar are blanked.\n *\n * Byte masking is same-length (`*`), so tar headers and offsets stay valid.\n * Everything here fails toward redaction: a false positive costs the owner one\n * masked value; a false negative would publish a credential.\n */\n\nexport const REDACTED = '[redacted]'\nconst MASK_BYTE = 0x2a\n\nconst CREDENTIAL_PATTERNS: readonly string[] = [\n String.raw`sk-ant-[A-Za-z0-9_-]{16,}`,\n String.raw`sk-(?:proj-|tan-|or-v1-|svcacct-)?[A-Za-z0-9_-]{20,}`,\n String.raw`(?:sk|rk)_(?:live|test|sb)_[A-Za-z0-9_]{12,}`,\n String.raw`whsec_[A-Za-z0-9+/=]{16,}`,\n String.raw`gh[pousr]_[A-Za-z0-9]{30,}`,\n String.raw`github_pat_[A-Za-z0-9_]{40,}`,\n String.raw`xox[abposr]-[A-Za-z0-9-]{10,}`,\n String.raw`AKIA[0-9A-Z]{16}`,\n String.raw`AIza[0-9A-Za-z_-]{35}`,\n String.raw`ya29\\.[0-9A-Za-z_-]{20,}`,\n String.raw`glpat-[A-Za-z0-9_-]{20,}`,\n String.raw`npm_[A-Za-z0-9]{36}`,\n String.raw`hf_[A-Za-z0-9]{30,}`,\n String.raw`r8_[A-Za-z0-9]{30,}`,\n String.raw`gsk_[A-Za-z0-9]{40,}`,\n String.raw`xai-[A-Za-z0-9]{40,}`,\n String.raw`lak_[A-Za-z0-9_-]{16,}`,\n String.raw`eyJ[A-Za-z0-9_-]{10,}\\.eyJ[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{10,}`,\n String.raw`-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[A-Za-z0-9+/=\\r\\n\\t ]*(?:-----END [A-Z0-9 ]*PRIVATE KEY-----)?`,\n]\n\n/** Names whose value is a credential, after camelCase is folded to snake_case. */\nconst SECRET_NAME =\n /(^|_)(secret|secrets|password|passwd|passphrase|token|credential|credentials|ciphertext|encrypted|bearer|apikey|privatekey|cookie)(_|$)|api_?key|private_?key|(key|secret|token|password|challenge|state|nonce|credential)_(hash|digest)$/\n/** Usage counters that merely mention tokens. */\nconst TOKEN_METRIC = /token_(count|counts|usage|budget|limit|cost)$|^(input|output|total|max|prompt|completion|reasoning|cached)_tokens?$/\n\nfunction snake(name: string): string {\n return name\n .replace(/([a-z0-9])([A-Z])/g, '$1_$2')\n .replace(/[-\\s.]+/g, '_')\n .toLowerCase()\n}\n\n/** True when a column or JSON key named `name` holds a credential. */\nexport function isSecretName(name: string): boolean {\n const folded = snake(name)\n if (TOKEN_METRIC.test(folded)) return false\n return SECRET_NAME.test(folded)\n}\n\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n}\n\nexport interface SecretScanner {\n /** Replace credential-shaped substrings. Returns the count replaced. */\n maskText(text: string): { text: string; count: number }\n /** Redact a row or any JSON value: credential names and credential values. */\n redactValue(value: unknown): { value: unknown; count: number }\n /** A same-length byte masker for file contents. `onMask` receives each count. */\n maskBytes(onMask: (count: number) => void): TransformStream<Uint8Array, Uint8Array>\n}\n\n/**\n * Build the scanner for one export. `knownSecrets` are exact values the product\n * holds (its own API keys, the workspace's sandbox key) that must never appear,\n * whatever their shape. Values shorter than 8 characters are ignored.\n */\nexport function createSecretScanner(options: { knownSecrets?: readonly string[] } = {}): SecretScanner {\n const known = [...new Set(options.knownSecrets ?? [])]\n .filter((s) => typeof s === 'string' && s.length >= 8)\n .sort((a, b) => b.length - a.length)\n .map(escapeRegExp)\n const source = [...known, ...CREDENTIAL_PATTERNS].join('|')\n const pattern = () => new RegExp(source, 'g')\n\n function maskText(text: string): { text: string; count: number } {\n let count = 0\n const out = text.replace(pattern(), () => {\n count += 1\n return REDACTED\n })\n return { text: out, count }\n }\n\n function redactJson(value: unknown, depth: number): { value: unknown; count: number } {\n if (typeof value === 'string') {\n const masked = maskText(value)\n return { value: masked.text, count: masked.count }\n }\n if (depth > 64 || value === null || typeof value !== 'object') return { value, count: 0 }\n let count = 0\n if (Array.isArray(value)) {\n const out = value.map((item) => {\n const result = redactJson(item, depth + 1)\n count += result.count\n return result.value\n })\n return { value: out, count }\n }\n const out: Record<string, unknown> = {}\n for (const [key, item] of Object.entries(value)) {\n if (isSecretName(key) && item !== null && item !== '' && typeof item !== 'boolean') {\n out[key] = REDACTED\n count += 1\n continue\n }\n const result = redactJson(item, depth + 1)\n out[key] = result.value\n count += result.count\n }\n return { value: out, count }\n }\n\n function redactValue(value: unknown): { value: unknown; count: number } {\n if (typeof value === 'string') {\n const trimmed = value.trimStart()\n if (trimmed.startsWith('{') || trimmed.startsWith('[')) {\n try {\n const parsed = JSON.parse(value) as unknown\n const result = redactJson(parsed, 0)\n return result.count ? { value: JSON.stringify(result.value), count: result.count } : { value, count: 0 }\n } catch {\n // Not JSON; scan it as text.\n }\n }\n const masked = maskText(value)\n return { value: masked.text, count: masked.count }\n }\n if (value instanceof Uint8Array || value instanceof ArrayBuffer) return { value, count: 0 }\n return redactJson(value, 0)\n }\n\n function maskBytes(onMask: (count: number) => void): TransformStream<Uint8Array, Uint8Array> {\n // Keep a tail so a credential split across two chunks is seen whole.\n const window = 8192\n const maxCarry = 65536\n let carry = new Uint8Array(0)\n\n function scan(buffer: Uint8Array, final: boolean): number {\n const text = decodeBytes(buffer)\n const regex = pattern()\n let emitEnd = final ? buffer.length : Math.max(0, buffer.length - window)\n let masked = 0\n for (let match = regex.exec(text); match; match = regex.exec(text)) {\n const start = match.index\n const end = start + match[0].length\n if (match[0].length === 0) {\n regex.lastIndex += 1\n continue\n }\n if (!final && end === buffer.length) {\n // Possibly truncated; leave it for the next chunk to see whole.\n emitEnd = Math.min(emitEnd, start)\n break\n }\n buffer.fill(MASK_BYTE, start, end)\n masked += 1\n }\n if (masked) onMask(masked)\n if (!final && buffer.length - emitEnd > maxCarry) emitEnd = buffer.length - window\n return emitEnd\n }\n\n // Decompressors emit small chunks. Scanning each one re-reads the carry\n // window, which cost 4x on 4 KiB chunks, so input is gathered into blocks.\n const block = 256 * 1024\n let pending: Uint8Array[] = []\n let pendingLength = 0\n\n function drain(controller: TransformStreamDefaultController<Uint8Array>, final: boolean) {\n const buffer = new Uint8Array(carry.length + pendingLength)\n buffer.set(carry, 0)\n let offset = carry.length\n for (const part of pending) {\n buffer.set(part, offset)\n offset += part.length\n }\n pending = []\n pendingLength = 0\n const emitEnd = scan(buffer, final)\n if (emitEnd > 0) controller.enqueue(buffer.slice(0, emitEnd))\n carry = buffer.slice(emitEnd)\n }\n\n return new TransformStream<Uint8Array, Uint8Array>({\n transform(chunk, controller) {\n pending.push(chunk)\n pendingLength += chunk.length\n if (pendingLength >= block) drain(controller, false)\n },\n flush(controller) {\n if (carry.length || pendingLength) drain(controller, true)\n },\n })\n }\n\n return { maskText, redactValue, maskBytes }\n}\n\n/**\n * One UTF-16 code unit per byte, so string indexes are byte offsets. A native\n * windows-1252 decoder keeps that property and is several times faster; the\n * manual decode covers runtimes whose TextDecoder lacks it.\n */\nconst nativeLatin1 = (() => {\n try {\n const decoder = new TextDecoder('latin1')\n return decoder.decode(new Uint8Array([0x41, 0x80, 0xff])).length === 3 ? decoder : null\n } catch {\n return null\n }\n})()\n\nfunction decodeBytes(buffer: Uint8Array): string {\n if (nativeLatin1) return nativeLatin1.decode(buffer)\n let text = ''\n for (let i = 0; i < buffer.length; i += 8192) text += String.fromCharCode(...buffer.subarray(i, i + 8192))\n return text\n}\n\n/** Credential stores that are blanked wholesale inside a sandbox archive. */\nconst CREDENTIAL_FILES = [\n /(^|\\/)\\.git-credentials$/,\n /(^|\\/)\\.netrc$/,\n /(^|\\/)\\.pgpass$/,\n /(^|\\/)\\.npmrc$/,\n /(^|\\/)\\.pypirc$/,\n /(^|\\/)\\.docker\\/config\\.json$/,\n /(^|\\/)\\.aws\\/credentials$/,\n /(^|\\/)\\.kube\\/config$/,\n /(^|\\/)\\.config\\/gh\\/hosts\\.ya?ml$/,\n /(^|\\/)\\.codex\\/auth\\.json$/,\n /(^|\\/)\\.claude\\/\\.credentials\\.json$/,\n /(^|\\/)opencode\\/auth\\.json$/,\n /(^|\\/)\\.ssh\\/id_[^/]*$/,\n]\n\nexport function isCredentialFile(path: string): boolean {\n const normalized = path.replace(/^\\.\\//, '')\n if (normalized.endsWith('.pub')) return false\n return CREDENTIAL_FILES.some((pattern) => pattern.test(normalized))\n}\n","/**\n * Reads an uncompressed tar stream in flight without changing its length.\n *\n * It counts members for the manifest and overwrites the contents of known\n * credential files (see `isCredentialFile`) with `*`, so the archive stays a\n * valid tar that still shows the file existed. Handles ustar prefixes, GNU long\n * names (`L`) and pax `path=` records.\n */\n\nimport { isCredentialFile } from './secrets'\n\nexport interface TarStats {\n files: number\n bytes: number\n blanked: string[]\n}\n\nconst BLOCK = 512\nconst MAX_NAME_RECORD = 1 << 20\n\nfunction readString(block: Uint8Array, start: number, length: number): string {\n let end = start\n while (end < start + length && block[end] !== 0) end += 1\n return new TextDecoder().decode(block.subarray(start, end))\n}\n\nfunction readSize(block: Uint8Array): number {\n // GNU base-256 for sizes over 8 GiB.\n if (block[124]! & 0x80) {\n let size = 0\n for (let i = 125; i < 136; i += 1) size = size * 256 + block[i]!\n return size\n }\n const octal = readString(block, 124, 12).trim()\n return octal ? Number.parseInt(octal, 8) : 0\n}\n\nfunction paxPath(record: string): string | undefined {\n for (const line of record.split('\\n')) {\n const space = line.indexOf(' ')\n if (space < 0) continue\n const field = line.slice(space + 1)\n if (field.startsWith('path=')) return field.slice(5)\n }\n return undefined\n}\n\nexport function createTarInspector(stats: TarStats): TransformStream<Uint8Array, Uint8Array> {\n const header = new Uint8Array(BLOCK)\n let headerFill = 0\n // Bytes of member data (plus padding) still to pass before the next header.\n let dataRemaining = 0\n let paddingRemaining = 0\n let blanking = false\n let capture: { kind: 'L' | 'x'; parts: Uint8Array[]; length: number } | null = null\n let pendingName: string | undefined\n let ended = false\n\n function onHeader(): void {\n if (header.every((b) => b === 0)) {\n ended = true\n return\n }\n const type = String.fromCharCode(header[156]!)\n const size = readSize(header)\n dataRemaining = size\n paddingRemaining = (BLOCK - (size % BLOCK)) % BLOCK\n blanking = false\n capture = null\n if ((type === 'L' || type === 'x') && size <= MAX_NAME_RECORD) {\n capture = { kind: type, parts: [], length: 0 }\n return\n }\n const prefix = header[257] === 0x75 ? readString(header, 345, 155) : ''\n const base = readString(header, 0, 100)\n const name = pendingName ?? (prefix ? `${prefix}/${base}` : base)\n pendingName = undefined\n if (type === '0' || type === '\\0' || type === '7') {\n stats.files += 1\n stats.bytes += size\n if (isCredentialFile(name)) {\n blanking = true\n stats.blanked.push(name)\n }\n }\n }\n\n return new TransformStream<Uint8Array, Uint8Array>({\n transform(chunk, controller) {\n const out = chunk.slice()\n let at = 0\n while (at < out.length && !ended) {\n if (dataRemaining > 0) {\n const take = Math.min(dataRemaining, out.length - at)\n if (blanking) out.fill(0x2a, at, at + take)\n if (capture) {\n capture.parts.push(out.slice(at, at + take))\n capture.length += take\n }\n dataRemaining -= take\n at += take\n if (dataRemaining === 0 && capture) {\n const joined = new Uint8Array(capture.length)\n let offset = 0\n for (const part of capture.parts) {\n joined.set(part, offset)\n offset += part.length\n }\n const text = new TextDecoder().decode(joined)\n pendingName = capture.kind === 'L' ? text.replace(/\\0+$/, '') : (paxPath(text) ?? pendingName)\n capture = null\n }\n continue\n }\n if (paddingRemaining > 0) {\n const take = Math.min(paddingRemaining, out.length - at)\n paddingRemaining -= take\n at += take\n continue\n }\n const take = Math.min(BLOCK - headerFill, out.length - at)\n header.set(out.subarray(at, at + take), headerFill)\n headerFill += take\n at += take\n if (headerFill === BLOCK) {\n headerFill = 0\n onHeader()\n }\n }\n controller.enqueue(out)\n },\n })\n}\n","/**\n * Streams a zip whose every entry was already written and measured.\n *\n * Because each entry's CRC-32 and sizes are known before the first byte goes\n * out, local headers carry real values (no data descriptors) and the total\n * length is exact, so the download response can send `Content-Length`. Zip64\n * records are added only when a size, offset or entry count needs them, which\n * keeps small archives readable by every unzip tool.\n */\n\nexport interface ZipEntrySpec {\n /** Path inside the archive, `/`-separated, no leading slash. */\n name: string\n /** 0 = stored, 8 = deflate. */\n method: 0 | 8\n crc32: number\n /** Bytes `open()` yields (after compression for method 8). */\n compressedSize: number\n uncompressedSize: number\n modifiedAt: Date\n open(): Promise<ReadableStream<Uint8Array>>\n}\n\nconst U32_MAX = 0xffffffff\nconst U16_MAX = 0xffff\n\ninterface Layout {\n name: Uint8Array\n localHeader: Uint8Array\n offset: number\n}\n\nfunction dosDateTime(date: Date): { time: number; date: number } {\n const year = Math.max(1980, date.getUTCFullYear())\n return {\n time: (date.getUTCHours() << 11) | (date.getUTCMinutes() << 5) | Math.floor(date.getUTCSeconds() / 2),\n date: ((year - 1980) << 9) | ((date.getUTCMonth() + 1) << 5) | date.getUTCDate(),\n }\n}\n\nfunction setU64(view: DataView, offset: number, value: number): void {\n view.setUint32(offset, value % 0x100000000, true)\n view.setUint32(offset + 4, Math.floor(value / 0x100000000), true)\n}\n\nfunction localHeader(entry: ZipEntrySpec, name: Uint8Array): Uint8Array {\n const zip64 = entry.compressedSize >= U32_MAX || entry.uncompressedSize >= U32_MAX\n const extraLength = zip64 ? 20 : 0\n const out = new Uint8Array(30 + name.length + extraLength)\n const view = new DataView(out.buffer)\n const { time, date } = dosDateTime(entry.modifiedAt)\n view.setUint32(0, 0x04034b50, true)\n view.setUint16(4, zip64 ? 45 : 20, true)\n view.setUint16(6, 0x0800, true)\n view.setUint16(8, entry.method, true)\n view.setUint16(10, time, true)\n view.setUint16(12, date, true)\n view.setUint32(14, entry.crc32, true)\n view.setUint32(18, zip64 ? U32_MAX : entry.compressedSize, true)\n view.setUint32(22, zip64 ? U32_MAX : entry.uncompressedSize, true)\n view.setUint16(26, name.length, true)\n view.setUint16(28, extraLength, true)\n out.set(name, 30)\n if (zip64) {\n const at = 30 + name.length\n view.setUint16(at, 0x0001, true)\n view.setUint16(at + 2, 16, true)\n setU64(view, at + 4, entry.uncompressedSize)\n setU64(view, at + 12, entry.compressedSize)\n }\n return out\n}\n\nfunction centralHeader(entry: ZipEntrySpec, layout: Layout): Uint8Array {\n const bigU = entry.uncompressedSize >= U32_MAX\n const bigC = entry.compressedSize >= U32_MAX\n const bigO = layout.offset >= U32_MAX\n const extraFields = (bigU ? 1 : 0) + (bigC ? 1 : 0) + (bigO ? 1 : 0)\n const extraLength = extraFields ? 4 + extraFields * 8 : 0\n const name = layout.name\n const out = new Uint8Array(46 + name.length + extraLength)\n const view = new DataView(out.buffer)\n const { time, date } = dosDateTime(entry.modifiedAt)\n const version = extraFields ? 45 : 20\n view.setUint32(0, 0x02014b50, true)\n view.setUint16(4, (3 << 8) | version, true)\n view.setUint16(6, version, true)\n view.setUint16(8, 0x0800, true)\n view.setUint16(10, entry.method, true)\n view.setUint16(12, time, true)\n view.setUint16(14, date, true)\n view.setUint32(16, entry.crc32, true)\n view.setUint32(20, bigC ? U32_MAX : entry.compressedSize, true)\n view.setUint32(24, bigU ? U32_MAX : entry.uncompressedSize, true)\n view.setUint16(28, name.length, true)\n view.setUint16(30, extraLength, true)\n view.setUint32(38, (0o100644 << 16) >>> 0, true)\n view.setUint32(42, bigO ? U32_MAX : layout.offset, true)\n out.set(name, 46)\n if (extraFields) {\n let at = 46 + name.length\n view.setUint16(at, 0x0001, true)\n view.setUint16(at + 2, extraFields * 8, true)\n at += 4\n if (bigU) {\n setU64(view, at, entry.uncompressedSize)\n at += 8\n }\n if (bigC) {\n setU64(view, at, entry.compressedSize)\n at += 8\n }\n if (bigO) setU64(view, at, layout.offset)\n }\n return out\n}\n\nfunction endRecords(count: number, cdOffset: number, cdSize: number): Uint8Array {\n const zip64 = count >= U16_MAX || cdOffset >= U32_MAX || cdSize >= U32_MAX\n const out = new Uint8Array((zip64 ? 56 + 20 : 0) + 22)\n const view = new DataView(out.buffer)\n let at = 0\n if (zip64) {\n view.setUint32(0, 0x06064b50, true)\n setU64(view, 4, 44)\n view.setUint16(12, (3 << 8) | 45, true)\n view.setUint16(14, 45, true)\n setU64(view, 24, count)\n setU64(view, 32, count)\n setU64(view, 40, cdSize)\n setU64(view, 48, cdOffset)\n view.setUint32(56, 0x07064b50, true)\n setU64(view, 64, cdOffset + cdSize)\n view.setUint32(72, 1, true)\n at = 76\n }\n view.setUint32(at, 0x06054b50, true)\n view.setUint16(at + 8, zip64 ? U16_MAX : count, true)\n view.setUint16(at + 10, zip64 ? U16_MAX : count, true)\n view.setUint32(at + 12, zip64 ? U32_MAX : cdSize, true)\n view.setUint32(at + 16, zip64 ? U32_MAX : cdOffset, true)\n return out\n}\n\n/** Lay out the archive and return its exact byte length and body stream. */\nexport function createZipStream(entries: ZipEntrySpec[]): { length: number; stream: ReadableStream<Uint8Array> } {\n const encoder = new TextEncoder()\n const layouts: Layout[] = []\n let offset = 0\n for (const entry of entries) {\n const name = encoder.encode(entry.name)\n const header = localHeader(entry, name)\n layouts.push({ name, localHeader: header, offset })\n offset += header.length + entry.compressedSize\n }\n const central = entries.map((entry, i) => centralHeader(entry, layouts[i]!))\n const cdSize = central.reduce((sum, part) => sum + part.length, 0)\n const end = endRecords(entries.length, offset, cdSize)\n const length = offset + cdSize + end.length\n\n let index = 0\n let phase: 'entries' | 'tail' | 'done' = 'entries'\n let reader: ReadableStreamDefaultReader<Uint8Array> | null = null\n let written = 0\n\n const stream = new ReadableStream<Uint8Array>({\n async pull(controller) {\n if (phase === 'entries') {\n if (reader) {\n const { done, value } = await reader.read()\n if (!done) {\n written += value.length\n controller.enqueue(value)\n return\n }\n reader = null\n const expected = entries[index]!.compressedSize\n if (written !== expected) {\n controller.error(new Error(`zip entry ${entries[index]!.name} produced ${written} bytes, expected ${expected}`))\n return\n }\n index += 1\n }\n if (index < entries.length) {\n controller.enqueue(layouts[index]!.localHeader)\n written = 0\n reader = (await entries[index]!.open()).getReader()\n return\n }\n phase = 'tail'\n }\n if (phase === 'tail') {\n for (const part of central) controller.enqueue(part)\n controller.enqueue(end)\n phase = 'done'\n controller.close()\n }\n },\n async cancel(reason) {\n await reader?.cancel(reason)\n },\n })\n return { length, stream }\n}\n","/**\n * Builds a workspace export one source at a time and serves it as a zip.\n *\n * Each source becomes a unit. A unit streams its data through the credential\n * masks, records CRC-32, SHA-256 and sizes, and stores the bytes as bounded\n * segments. The job record (`job.json`) tracks which units are done, so an\n * export resumes after a closed tab or a dropped request instead of starting\n * over. When every unit is done, the manifest is written, and the download\n * route stitches the stored segments into one zip with an exact length.\n */\n\nimport { assertSafeKeySegment } from '../object-store'\nimport { crc32Update, createSha256 } from './checksum'\nimport { createSecretScanner, isSecretName, REDACTED, type SecretScanner } from './secrets'\nimport type { ExportStorage } from './storage'\nimport { createTarInspector } from './tar'\nimport type {\n ExportJob,\n ExportPlan,\n ExportProgress,\n ExportRow,\n ExportSource,\n ExportUnit,\n StoredEntry,\n} from './types'\nimport { createZipStream, type ZipEntrySpec } from './zip'\n\nexport const MANIFEST_SCHEMA = 'tangle.workspace-export/v1'\nconst SEGMENT_BYTES = 8 * 1024 * 1024\n// A short lease, renewed while a request works, so a request that dies (closed\n// tab, cancelled fetch) stalls the export for at most a minute.\nconst LEASE_MS = 60_000\nconst HEARTBEAT_MS = 20_000\nconst MAX_ATTEMPTS = 3\n/** Files written per request. Each read and segment write is a subrequest, and\n * Workers cap subrequests per request, so a large files source spans requests. */\nconst FILES_PER_REQUEST = 200\nconst SOURCE_NAME = /^[a-z0-9][a-z0-9_.-]{0,95}$/\n\nexport interface ExportEngineOptions {\n /** Product name for the manifest and the download filename, e.g. `hospitality`. */\n app: string\n storage: ExportStorage\n plan(args: { workspaceId: string }): ExportPlan | Promise<ExportPlan>\n /** Exact credential values held by the product that must never appear. */\n knownSecrets?(args: { workspaceId: string }): readonly string[] | Promise<readonly string[]>\n /** Storage key prefix. Default `workspace-exports`. */\n prefix?: string\n /** Sandbox archives read at once in one request. Default 4. */\n archiveConcurrency?: number\n now?: () => number\n}\n\nclass LeaseLost extends Error {}\n\nfunction iso(ms: number): string {\n return new Date(ms).toISOString()\n}\n\nfunction errorText(scanner: SecretScanner, err: unknown): string {\n const raw = err instanceof Error ? err.message : String(err)\n return scanner.maskText(raw).text.slice(0, 300)\n}\n\nfunction toStream(body: ReadableStream<Uint8Array> | Uint8Array | string): ReadableStream<Uint8Array> {\n if (body instanceof ReadableStream) return body\n const bytes = typeof body === 'string' ? new TextEncoder().encode(body) : body\n return new ReadableStream({\n start(controller) {\n if (bytes.length) controller.enqueue(bytes)\n controller.close()\n },\n })\n}\n\nfunction concatenate(parts: Uint8Array[], length: number): Uint8Array {\n const out = new Uint8Array(length)\n let offset = 0\n for (const part of parts) {\n out.set(part, offset)\n offset += part.length\n }\n return out\n}\n\n/** Make a file path safe and unique inside the archive. */\nfunction safePath(path: string, used: Set<string>): string {\n const parts = path\n .replace(/\\\\/g, '/')\n .split('/')\n .filter((p) => p && p !== '.' && p !== '..')\n .map((p) => p.replace(/[\\0-\\x1f]/g, '_'))\n let candidate = parts.join('/') || 'file'\n let n = 1\n while (used.has(candidate)) {\n n += 1\n candidate = `${parts.join('/') || 'file'}~${n}`\n }\n used.add(candidate)\n return candidate\n}\n\nfunction jsonCell(value: unknown): unknown {\n if (typeof value === 'bigint') return value.toString()\n if (value instanceof ArrayBuffer) value = new Uint8Array(value)\n if (value instanceof Uint8Array) {\n let bin = ''\n for (const b of value) bin += String.fromCharCode(b)\n return { $base64: btoa(bin) }\n }\n return value\n}\n\nexport function createExportEngine(options: ExportEngineOptions) {\n const { storage } = options\n const prefix = options.prefix ?? 'workspace-exports'\n const now = options.now ?? (() => Date.now())\n const archiveConcurrency = Math.max(1, Math.floor(options.archiveConcurrency ?? 4))\n\n /**\n * The units the next step runs, starting at `pending[from]`. Consecutive\n * archive units run together: each mostly waits on its box to resume and\n * stream its tar, so a workspace with dozens of sandboxes would otherwise\n * spend one box's wait per unit. A unit already attempted runs alone, so a\n * batch that died at a Worker limit cannot keep taking its neighbours with it.\n */\n function archiveBatch<T extends { unit: ExportUnit }>(pending: T[], from: number): T[] {\n const first = pending[from]!\n if (first.unit.kind !== 'archive' || first.unit.attempts > 0) return [first]\n const batch = [first]\n for (let i = from + 1; i < pending.length && batch.length < archiveConcurrency; i += 1) {\n const candidate = pending[i]!\n if (candidate.unit.kind !== 'archive' || candidate.unit.attempts > 0) break\n batch.push(candidate)\n }\n return batch\n }\n\n const base =(workspaceId: string, id: string) =>\n `${prefix}/${assertSafeKeySegment(workspaceId)}/${assertSafeKeySegment(id)}`\n const jobKey = (workspaceId: string, id: string) => `${base(workspaceId, id)}/job.json`\n /** The key a download signature covers. No object lives there; the zip is assembled per request. */\n const archiveKey = (workspaceId: string, id: string) => `${base(workspaceId, id)}/archive.zip`\n\n async function loadJob(workspaceId: string, id: string): Promise<{ job: ExportJob; etag: string } | null> {\n if (!/^[a-z0-9-]{8,64}$/.test(id)) return null\n const object = await storage.get(jobKey(workspaceId, id))\n if (!object) return null\n const job = JSON.parse(await new Response(object.body).text()) as ExportJob\n if (job.workspaceId !== workspaceId) return null\n return { job, etag: object.etag }\n }\n\n async function saveJob(job: ExportJob, etag?: string): Promise<string> {\n job.updatedAt = iso(now())\n const result = await storage.put(jobKey(job.workspaceId, job.id), new TextEncoder().encode(JSON.stringify(job)), {\n ifMatch: etag,\n })\n if (!result) throw new LeaseLost('export job changed underneath this request')\n return result.etag\n }\n\n async function writeEntry(\n keyBase: string,\n path: string,\n input: ReadableStream<Uint8Array>,\n compress: boolean,\n ): Promise<StoredEntry> {\n let crc = 0\n let size = 0\n const sha = createSha256()\n let stream = input.pipeThrough(\n new TransformStream<Uint8Array, Uint8Array>({\n async transform(chunk, controller) {\n crc = crc32Update(crc, chunk)\n size += chunk.length\n await sha.update(chunk)\n controller.enqueue(chunk)\n },\n }),\n )\n if (compress) stream = stream.pipeThrough(new CompressionStream('deflate-raw') as unknown as TransformStream<Uint8Array, Uint8Array>)\n\n const segments: StoredEntry['segments'] = []\n let pending: Uint8Array[] = []\n let pendingLength = 0\n let compressedSize = 0\n const flush = async () => {\n if (!pendingLength) return\n const key = `${keyBase}/${segments.length}`\n await storage.put(key, concatenate(pending, pendingLength))\n segments.push({ key, size: pendingLength })\n compressedSize += pendingLength\n pending = []\n pendingLength = 0\n }\n const reader = stream.getReader()\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n pending.push(value)\n pendingLength += value.length\n if (pendingLength >= SEGMENT_BYTES) await flush()\n }\n await flush()\n return {\n path,\n method: compress ? 8 : 0,\n crc32: crc,\n sha256: await sha.digestHex(),\n size,\n compressedSize,\n segments,\n }\n }\n\n function redactRow(row: ExportRow, omit: ReadonlySet<string>, scanner: SecretScanner): { row: ExportRow; count: number } {\n const out: ExportRow = {}\n let count = 0\n for (const [column, raw] of Object.entries(row)) {\n if (omit.has(column)) continue\n if (isSecretName(column)) {\n if (raw === null || raw === undefined || raw === '') out[column] = raw ?? null\n else {\n out[column] = REDACTED\n count += 1\n }\n continue\n }\n const result = scanner.redactValue(jsonCell(raw))\n out[column] = result.value\n count += result.count\n }\n return { row: out, count }\n }\n\n async function runUnit(\n job: ExportJob,\n unit: ExportUnit,\n index: number,\n source: ExportSource,\n scanner: SecretScanner,\n deadline: number,\n ) {\n const keyBase = `${base(job.workspaceId, job.id)}/u/${index}`\n if (unit.cursor === undefined) {\n unit.entries = []\n unit.redactions = 0\n }\n const encoder = new TextEncoder()\n\n if (source.kind === 'rows') {\n const omit = new Set(source.omitColumns ?? [])\n unit.expectedRows = source.expectedCount ? await source.expectedCount() : undefined\n let rows = 0\n const iterator = source.rows()[Symbol.asyncIterator]()\n const body = new ReadableStream<Uint8Array>({\n async pull(controller) {\n const { done, value } = await iterator.next()\n if (done) {\n controller.close()\n return\n }\n const page = Array.isArray(value) ? value : [value]\n let text = ''\n for (const row of page) {\n const redacted = redactRow(row, omit, scanner)\n unit.redactions += redacted.count\n text += `${JSON.stringify(redacted.row)}\\n`\n rows += 1\n }\n if (text) controller.enqueue(encoder.encode(text))\n },\n async cancel() {\n await iterator.return?.()\n },\n })\n unit.entries.push(await writeEntry(`${keyBase}/0`, `data/${source.name}.ndjson`, body, true))\n unit.rows = rows\n unit.status = 'done'\n return\n }\n\n if (source.kind === 'json') {\n const result = scanner.redactValue(await source.value())\n unit.redactions += result.count\n const text = `${JSON.stringify(result.value, null, 2)}\\n`\n unit.entries.push(await writeEntry(`${keyBase}/0`, `data/${source.name}.json`, toStream(text), true))\n unit.status = 'done'\n return\n }\n\n if (source.kind === 'files') {\n // Resumable: `cursor` counts files already listed, so a later request\n // skips them and keeps the entries they produced.\n const folder = `files/${source.name}/`\n const used = new Set(unit.entries.map((e) => e.path.slice(folder.length)))\n const start = unit.cursor ?? 0\n let seen = 0\n let written = 0\n for await (const file of source.files()) {\n if (seen < start) {\n seen += 1\n continue\n }\n if (written >= FILES_PER_REQUEST || now() > deadline) {\n unit.cursor = seen\n return\n }\n const body = await file.open()\n seen += 1\n if (body !== null) {\n const path = folder + safePath(file.path, used)\n const masked = toStream(body).pipeThrough(scanner.maskBytes((n) => (unit.redactions += n)))\n unit.entries.push(await writeEntry(`${keyBase}/${unit.entries.length}`, path, masked, false))\n written += 1\n }\n unit.cursor = seen\n }\n unit.cursor = undefined\n unit.files = unit.entries.length\n unit.status = unit.entries.length ? 'done' : 'empty'\n return\n }\n\n const archive = await source.open()\n if (!archive) {\n unit.status = 'empty'\n return\n }\n const stats = { files: 0, bytes: 0, blanked: [] as string[] }\n const tarGz = archive\n .pipeThrough(new DecompressionStream('gzip') as unknown as TransformStream<Uint8Array, Uint8Array>)\n .pipeThrough(createTarInspector(stats))\n .pipeThrough(scanner.maskBytes((n) => (unit.redactions += n)))\n .pipeThrough(new CompressionStream('gzip') as unknown as TransformStream<Uint8Array, Uint8Array>)\n unit.entries.push(await writeEntry(`${keyBase}/0`, `sandbox/${source.name}.tar.gz`, tarGz, false))\n unit.archive = stats\n unit.files = stats.files\n unit.status = 'done'\n }\n\n function manifest(job: ExportJob, notes: Record<string, unknown> | undefined) {\n const classes: Record<string, string[]> = {}\n for (const unit of job.units) {\n for (const entry of unit.entries) (classes[unit.dataClass] ??= []).push(entry.path)\n }\n return {\n schema: MANIFEST_SCHEMA,\n app: options.app,\n workspaceId: job.workspaceId,\n exportId: job.id,\n requestedBy: job.requestedBy,\n createdAt: job.createdAt,\n completedAt: job.completedAt,\n secretPolicy:\n 'Credential columns and JSON keys are replaced with \"[redacted]\". Credential-shaped values and the product\\'s own keys are masked in rows and files. Credential files inside sandbox archives are overwritten with \"*\". Connections are exported as metadata only.',\n totals: {\n units: job.units.length,\n files: job.units.reduce((n, u) => n + u.entries.length, 0),\n rows: job.units.reduce((n, u) => n + (u.rows ?? 0), 0),\n bytes: job.units.reduce((n, u) => n + u.entries.reduce((m, e) => m + e.size, 0), 0),\n redactions: job.units.reduce((n, u) => n + u.redactions, 0),\n },\n classes,\n sources: job.units.map((u) => ({\n name: u.name,\n kind: u.kind,\n dataClass: u.dataClass,\n description: u.description,\n status: u.status,\n rows: u.rows,\n expectedRows: u.expectedRows,\n files: u.files,\n archive: u.archive,\n redactions: u.redactions,\n })),\n files: job.units.flatMap((u) =>\n u.entries.map((e) => ({ path: e.path, size: e.size, sha256: e.sha256, crc32: e.crc32.toString(16).padStart(8, '0') })),\n ),\n notes,\n }\n }\n\n function readme(job: ExportJob): string {\n return [\n `${options.app} workspace export`,\n '',\n `Workspace: ${job.workspaceId}`,\n `Export: ${job.id}`,\n `Created: ${job.createdAt}`,\n '',\n 'manifest.json what this archive contains: every file with its size and SHA-256, row counts per source, and the redaction policy',\n 'data/*.ndjson one JSON object per line, one file per table or record type',\n 'data/*.json single documents',\n 'files/<source>/ uploaded and generated files, at their original paths',\n 'sandbox/*.tar.gz the agent workspace filesystem; extract with `tar -xzf`',\n '',\n 'Verify a file: `shasum -a 256 <path>` and compare with manifest.json.',\n 'Secrets are never exported. Credential fields read \"[redacted]\".',\n '',\n ].join('\\n')\n }\n\n async function finalize(job: ExportJob, plan: ExportPlan, scanner: SecretScanner) {\n job.completedAt = iso(now())\n const notes = plan.notes ? (scanner.redactValue(plan.notes).value as Record<string, unknown>) : undefined\n const keyBase = `${base(job.workspaceId, job.id)}/meta`\n const manifestText = `${JSON.stringify(manifest(job, notes), null, 2)}\\n`\n job.meta = [\n await writeEntry(`${keyBase}/0`, 'manifest.json', toStream(manifestText), true),\n await writeEntry(`${keyBase}/1`, 'README.txt', toStream(readme(job)), true),\n ]\n job.status = 'complete'\n }\n\n return {\n archiveKey,\n\n async list(workspaceId: string): Promise<ExportJob[]> {\n const ids = new Set<string>()\n let cursor: string | undefined\n do {\n const page = await storage.list(`${prefix}/${assertSafeKeySegment(workspaceId)}/`, cursor)\n for (const key of page.keys) if (key.endsWith('/job.json')) ids.add(key.split('/').at(-2)!)\n cursor = page.cursor\n } while (cursor)\n const jobs: ExportJob[] = []\n for (const id of [...ids].sort().reverse().slice(0, 10)) {\n const loaded = await loadJob(workspaceId, id)\n if (loaded) jobs.push(loaded.job)\n }\n return jobs\n },\n\n async get(workspaceId: string, id: string): Promise<ExportJob | null> {\n return (await loadJob(workspaceId, id))?.job ?? null\n },\n\n /** Start an export, or return the one already running for this workspace. */\n async start(workspaceId: string, requestedBy: string): Promise<ExportJob> {\n const existing = (await this.list(workspaceId)).find(\n (job) => job.status === 'running' && now() - Date.parse(job.updatedAt) < 15 * 60_000,\n )\n if (existing) return existing\n const plan = await options.plan({ workspaceId })\n const names = new Set<string>()\n for (const source of plan.sources) {\n if (!SOURCE_NAME.test(source.name)) throw new Error(`workspace-export: invalid source name \"${source.name}\"`)\n if (names.has(source.name)) throw new Error(`workspace-export: duplicate source name \"${source.name}\"`)\n names.add(source.name)\n }\n const created = now()\n const job: ExportJob = {\n v: 1,\n id: `${created.toString(36)}-${crypto.randomUUID().slice(0, 8)}`,\n workspaceId,\n requestedBy,\n createdAt: iso(created),\n updatedAt: iso(created),\n status: 'running',\n units: plan.sources.map((s) => ({\n name: s.name,\n kind: s.kind,\n dataClass: s.dataClass,\n description: s.description,\n status: 'pending',\n attempts: 0,\n entries: [],\n redactions: 0,\n })),\n }\n await saveJob(job)\n return job\n },\n\n /**\n * Run pending units until `budgetMs` passes. A unit that starts always\n * finishes, so one call can run longer than the budget. Returns the job as\n * stored; another request holding the lease leaves it unchanged.\n */\n async advance(workspaceId: string, id: string, budgetMs = 20_000): Promise<ExportJob | null> {\n const loaded = await loadJob(workspaceId, id)\n if (!loaded) return null\n const { job } = loaded\n if (job.status !== 'running') return job\n if (job.lease && job.lease.until > now()) return job\n const deadline = now() + budgetMs\n let etag = loaded.etag\n // Saves are serialized: the heartbeat and the unit loop share one etag.\n let saving: Promise<void> = Promise.resolve()\n const save = () => {\n saving = saving.then(async () => {\n if (job.lease) job.lease.until = now() + LEASE_MS\n etag = await saveJob(job, etag)\n })\n return saving\n }\n let heartbeat: ReturnType<typeof setInterval> | undefined\n try {\n job.lease = { id: crypto.randomUUID(), until: now() + LEASE_MS }\n await save()\n heartbeat = setInterval(() => {\n save().catch(() => {})\n }, HEARTBEAT_MS)\n const plan = await options.plan({ workspaceId })\n const scanner = createSecretScanner({ knownSecrets: (await options.knownSecrets?.({ workspaceId })) ?? [] })\n const sources = new Map(plan.sources.map((s) => [s.name, s]))\n const pending = job.units.flatMap((unit, index) => (unit.status === 'pending' ? [{ unit, index }] : []))\n let next = 0\n while (next < pending.length) {\n if (now() > deadline) break\n const batch = archiveBatch(pending, next)\n next += batch.length\n const exhausted = batch.find(({ unit }) => unit.attempts >= MAX_ATTEMPTS)\n if (exhausted) {\n // Earlier requests died inside this unit without recording an outcome,\n // most often at the Worker CPU limit.\n const { unit } = exhausted\n unit.status = 'failed'\n unit.error ??= 'the request exporting this source ended before it finished'\n job.status = 'failed'\n job.error = `${unit.name}: ${unit.error}`\n await save()\n break\n }\n // Recorded before running, so a request that dies mid-unit still counts.\n for (const { unit } of batch) unit.attempts += 1\n await save()\n const failed = await Promise.all(\n batch.map(async ({ unit, index }) => {\n const source = sources.get(unit.name)\n try {\n if (!source || source.kind !== unit.kind) throw new Error('source is no longer available')\n await runUnit(job, unit, index, source, scanner, deadline)\n unit.error = undefined\n return false\n } catch (err) {\n unit.error = errorText(scanner, err)\n // A files unit keeps what it already wrote and resumes at its cursor.\n if (unit.cursor === undefined) unit.entries = []\n if (unit.attempts >= MAX_ATTEMPTS) unit.status = 'failed'\n return true\n }\n }),\n )\n const dead = batch.find(({ unit }) => unit.status === 'failed')\n if (dead) {\n job.status = 'failed'\n job.error = `${dead.unit.name}: ${dead.unit.error}`\n }\n if (failed.includes(true)) {\n await save()\n break\n }\n const { unit } = batch[0]!\n if (unit.status === 'pending') {\n // Progress was made; continue this unit in the next request.\n unit.attempts = 0\n await save()\n break\n }\n await save()\n }\n if (job.status === 'running' && job.units.every((u) => u.status === 'done' || u.status === 'empty')) {\n await finalize(job, plan, scanner)\n }\n clearInterval(heartbeat)\n await saving.catch(() => {})\n job.lease = undefined\n await saveJob(job, etag)\n return job\n } catch (err) {\n if (err instanceof LeaseLost) return (await loadJob(workspaceId, id))?.job ?? null\n throw err\n } finally {\n clearInterval(heartbeat)\n }\n },\n\n progress(job: ExportJob): Omit<ExportProgress, 'downloadUrl' | 'downloadExpiresAt'> {\n const bytesOf = (u: ExportUnit) => u.entries.reduce((n, e) => n + e.size, 0)\n return {\n id: job.id,\n status: job.status,\n createdAt: job.createdAt,\n completedAt: job.completedAt,\n error: job.error,\n unitsTotal: job.units.length,\n unitsDone: job.units.filter((u) => u.status !== 'pending').length,\n current: job.status === 'running' ? job.units.find((u) => u.status === 'pending')?.name : undefined,\n bytes: job.units.reduce((n, u) => n + bytesOf(u), 0),\n units: job.units.map((u) => ({\n name: u.name,\n dataClass: u.dataClass,\n status: u.status,\n rows: u.rows,\n files: u.files,\n bytes: bytesOf(u),\n error: u.error,\n })),\n }\n },\n\n /** The finished archive as one stream with an exact length. */\n zip(job: ExportJob): { length: number; stream: ReadableStream<Uint8Array>; filename: string } {\n if (job.status !== 'complete' || !job.meta) throw new Error('workspace-export: export is not complete')\n const modifiedAt = new Date(job.completedAt ?? job.createdAt)\n const entries: ZipEntrySpec[] = [...job.meta, ...job.units.flatMap((u) => u.entries)].map((entry) => ({\n name: entry.path,\n method: entry.method,\n crc32: entry.crc32,\n compressedSize: entry.compressedSize,\n uncompressedSize: entry.size,\n modifiedAt,\n open: async () => {\n let index = 0\n let reader: ReadableStreamDefaultReader<Uint8Array> | null = null\n return new ReadableStream<Uint8Array>({\n async pull(controller) {\n for (;;) {\n if (!reader) {\n const segment = entry.segments[index]\n if (!segment) {\n controller.close()\n return\n }\n index += 1\n const object = await storage.get(segment.key)\n if (!object || object.size !== segment.size) {\n controller.error(new Error(`workspace-export: segment ${segment.key} is missing or changed`))\n return\n }\n reader = object.body.getReader()\n }\n const { done, value } = await reader.read()\n if (!done) {\n controller.enqueue(value)\n return\n }\n reader = null\n }\n },\n async cancel(reason) {\n await reader?.cancel(reason)\n },\n })\n },\n }))\n const { length, stream } = createZipStream(entries)\n const date = (job.completedAt ?? job.createdAt).slice(0, 10)\n return { length, stream, filename: `${options.app}-workspace-export-${date}.zip` }\n },\n\n /** Delete exports older than `retentionMs`, and any export by id when given. */\n async prune(workspaceId: string, retentionMs: number, onlyId?: string): Promise<number> {\n const cutoff = now() - retentionMs\n const doomed: string[] = []\n let cursor: string | undefined\n const root = `${prefix}/${assertSafeKeySegment(workspaceId)}/`\n do {\n const page = await storage.list(root, cursor)\n for (const key of page.keys) {\n const id = key.slice(root.length).split('/')[0] ?? ''\n const created = Number.parseInt(id.split('-')[0] ?? '', 36)\n if (onlyId ? id === onlyId : Number.isFinite(created) && created < cutoff) doomed.push(key)\n }\n cursor = page.cursor\n } while (cursor)\n await storage.delete(doomed)\n return doomed.length\n },\n }\n}\n\nexport type ExportEngine = ReturnType<typeof createExportEngine>\n","/**\n * HTTP surface for workspace exports, mounted by a product under one path such\n * as `/api/workspaces/:id/exports`.\n *\n * GET {mount} list recent exports owner\n * POST {mount} start (or resume) an export owner\n * GET {mount}/:id progress + signed link owner\n * POST {mount}/:id/advance do the next ~20 s of work owner\n * DELETE {mount}/:id delete a finished export owner\n * GET {mount}/:id/download the zip signed link\n *\n * Authorization fails closed: no principal, a non-owner role, or an authorizer\n * that throws all refuse. Writes also require a same-origin request. The\n * download link is an HMAC-signed, short-lived URL bound to one workspace and\n * one export, so a browser can fetch it without a session header.\n */\n\nimport { signObjectUrl, verifyObjectUrl } from '../object-store'\nimport { createExportEngine, type ExportEngineOptions } from './engine'\nimport type { ExportJob, ExportPrincipal, ExportProgress } from './types'\n\nexport interface WorkspaceExportOptions extends ExportEngineOptions {\n /** Resolve the caller from the authenticated session. Return `null` when unauthenticated or not a member. */\n authorize(args: { request: Request; workspaceId: string }): Promise<ExportPrincipal | null>\n /** HMAC secret for download links. An empty secret refuses every download. */\n signingSecret: string\n /** Download link lifetime. Default 15 minutes. */\n linkTtlMs?: number\n /** Exports are deleted after this long. They hold decrypted data, so keep it short. Default 24 hours. */\n retentionMs?: number\n /** Work per advance request. Default 20 seconds. */\n advanceBudgetMs?: number\n}\n\nconst NO_STORE = { 'Cache-Control': 'private, no-store' }\n\nfunction json(body: unknown, status = 200): Response {\n return Response.json(body, { status, headers: NO_STORE })\n}\n\nfunction refuse(status: number, code: string, message: string): Response {\n return json({ error: { code, message } }, status)\n}\n\nfunction sameOrigin(request: Request): boolean {\n const site = request.headers.get('Sec-Fetch-Site')\n if (site && site !== 'same-origin' && site !== 'none') return false\n const origin = request.headers.get('Origin')\n if (origin && origin !== new URL(request.url).origin) return false\n return true\n}\n\nexport function createWorkspaceExport(options: WorkspaceExportOptions) {\n const engine = createExportEngine(options)\n const linkTtlMs = options.linkTtlMs ?? 15 * 60_000\n const retentionMs = options.retentionMs ?? 24 * 60 * 60_000\n const now = options.now ?? (() => Date.now())\n\n async function withProgress(job: ExportJob, mount: string): Promise<ExportProgress> {\n const progress: ExportProgress = engine.progress(job)\n if (job.status === 'complete' && options.signingSecret) {\n const exp = now() + linkTtlMs\n const query = await signObjectUrl({ key: engine.archiveKey(job.workspaceId, job.id), exp, secret: options.signingSecret })\n progress.downloadUrl = `${mount}/${job.id}/download${query}`\n progress.downloadExpiresAt = new Date(exp).toISOString()\n }\n return progress\n }\n\n async function owner(request: Request, workspaceId: string): Promise<ExportPrincipal | Response> {\n let principal: ExportPrincipal | null\n try {\n principal = await options.authorize({ request, workspaceId })\n } catch {\n return refuse(503, 'authorization_unavailable', 'Could not check workspace access')\n }\n if (!principal) return refuse(403, 'forbidden', 'Workspace owner access is required')\n if (principal.role !== 'owner') return refuse(403, 'owner_required', 'Only the workspace owner can export its data')\n return principal\n }\n\n async function download(request: Request, workspaceId: string, id: string): Promise<Response> {\n const verified = await verifyObjectUrl(request, { secret: options.signingSecret })\n if (!verified.ok || verified.key !== engine.archiveKey(workspaceId, id)) {\n return refuse(403, 'link_invalid', 'This download link is invalid or has expired')\n }\n const job = await engine.get(workspaceId, id)\n if (!job || job.status !== 'complete') return refuse(404, 'not_found', 'Export not found')\n const { length, stream, filename } = engine.zip(job)\n return new Response(stream, {\n headers: {\n ...NO_STORE,\n 'Content-Type': 'application/zip',\n 'Content-Length': String(length),\n 'Content-Disposition': `attachment; filename=\"${filename}\"`,\n 'X-Content-Type-Options': 'nosniff',\n },\n })\n }\n\n /**\n * Handle one request. `path` is the part after the mount, without a leading\n * slash: `''`, `'<id>'`, `'<id>/advance'` or `'<id>/download'`.\n */\n async function route(request: Request, args: { workspaceId: string; path: string }): Promise<Response> {\n const { workspaceId } = args\n const path = args.path.replace(/^\\/+|\\/+$/g, '')\n const url = new URL(request.url)\n const mount = path ? url.pathname.slice(0, url.pathname.length - path.length).replace(/\\/+$/, '') : url.pathname.replace(/\\/+$/, '')\n const [id, action, extra] = path ? path.split('/') : []\n const method = request.method.toUpperCase()\n if (extra !== undefined) return refuse(404, 'not_found', 'Not found')\n\n try {\n if (id && action === 'download') {\n if (method !== 'GET') return refuse(405, 'method_not_allowed', 'Use GET')\n return await download(request, workspaceId, id)\n }\n\n if (method !== 'GET' && !sameOrigin(request)) return refuse(403, 'cross_origin', 'Cross-origin request refused')\n const principal = await owner(request, workspaceId)\n if (principal instanceof Response) return principal\n\n if (!id) {\n if (method === 'GET') {\n const jobs = await engine.list(workspaceId)\n return json({ exports: await Promise.all(jobs.map((job) => withProgress(job, mount))) })\n }\n if (method === 'POST') {\n await engine.prune(workspaceId, retentionMs)\n const job = await engine.start(workspaceId, principal.userId)\n return json(await withProgress(job, mount), 202)\n }\n return refuse(405, 'method_not_allowed', 'Use GET or POST')\n }\n\n if (!action) {\n if (method === 'GET') {\n const job = await engine.get(workspaceId, id)\n return job ? json(await withProgress(job, mount)) : refuse(404, 'not_found', 'Export not found')\n }\n if (method === 'DELETE') {\n const job = await engine.get(workspaceId, id)\n if (!job) return refuse(404, 'not_found', 'Export not found')\n if (job.status === 'running') return refuse(409, 'running', 'Wait for the export to finish before deleting it')\n await engine.prune(workspaceId, 0, id)\n return json({ deleted: id })\n }\n return refuse(405, 'method_not_allowed', 'Use GET or DELETE')\n }\n\n if (action === 'advance') {\n if (method !== 'POST') return refuse(405, 'method_not_allowed', 'Use POST')\n const job = await engine.advance(workspaceId, id, options.advanceBudgetMs)\n return job ? json(await withProgress(job, mount)) : refuse(404, 'not_found', 'Export not found')\n }\n return refuse(404, 'not_found', 'Not found')\n } catch {\n // Error text can carry data from a source; it is recorded, masked, on the job instead.\n return refuse(500, 'export_error', 'The export request failed')\n }\n }\n\n return { route, engine }\n}\n","/**\n * Where an export keeps its pieces until download. Each entry is written as\n * bounded segments so nothing larger than one segment is ever held in memory,\n * and the job record is updated with a compare-and-swap so two tabs advancing\n * the same export cannot both run it.\n */\n\nexport interface ExportStorage {\n /** `ifMatch` makes the write conditional; a lost race returns `null`. */\n put(key: string, body: Uint8Array, options?: { ifMatch?: string }): Promise<{ etag: string } | null>\n get(key: string): Promise<{ body: ReadableStream<Uint8Array>; size: number; etag: string } | null>\n list(prefix: string, cursor?: string): Promise<{ keys: string[]; cursor?: string }>\n delete(keys: string[]): Promise<void>\n}\n\n/** The slice of Cloudflare's `R2Bucket` used here; a real binding satisfies it. */\nexport interface R2ExportBucket {\n put(\n key: string,\n value: Uint8Array,\n options?: { onlyIf?: { etagMatches?: string }; httpMetadata?: { contentType?: string } },\n ): Promise<{ etag: string } | null>\n get(key: string): Promise<{ body: ReadableStream<Uint8Array>; size: number; etag: string } | null>\n list(options: { prefix: string; cursor?: string; limit?: number }): Promise<{\n objects: { key: string }[]\n truncated: boolean\n cursor?: string\n }>\n delete(keys: string | string[]): Promise<void>\n}\n\nexport function createR2ExportStorage(bucket: R2ExportBucket): ExportStorage {\n return {\n async put(key, body, options) {\n const result = await bucket.put(key, body, options?.ifMatch ? { onlyIf: { etagMatches: options.ifMatch } } : undefined)\n return result ? { etag: result.etag } : null\n },\n async get(key) {\n const object = await bucket.get(key)\n return object ? { body: object.body, size: object.size, etag: object.etag } : null\n },\n async list(prefix, cursor) {\n const page = await bucket.list({ prefix, cursor, limit: 1000 })\n return { keys: page.objects.map((o) => o.key), cursor: page.truncated ? page.cursor : undefined }\n },\n async delete(keys) {\n for (let i = 0; i < keys.length; i += 1000) await bucket.delete(keys.slice(i, i + 1000))\n },\n }\n}\n\n/** An in-memory store for tests and local runs. */\nexport function createMemoryExportStorage(): ExportStorage & { objects: Map<string, Uint8Array> } {\n const objects = new Map<string, Uint8Array>()\n const etags = new Map<string, string>()\n let version = 0\n return {\n objects,\n async put(key, body, options) {\n if (options?.ifMatch && etags.get(key) !== options.ifMatch) return null\n version += 1\n objects.set(key, body.slice())\n etags.set(key, String(version))\n return { etag: String(version) }\n },\n async get(key) {\n const bytes = objects.get(key)\n if (!bytes) return null\n return { body: new Blob([bytes as BlobPart]).stream() as ReadableStream<Uint8Array>, size: bytes.length, etag: etags.get(key)! }\n },\n async list(prefix) {\n return { keys: [...objects.keys()].filter((k) => k.startsWith(prefix)).sort() }\n },\n async delete(keys) {\n for (const key of keys) {\n objects.delete(key)\n etags.delete(key)\n }\n },\n }\n}\n","/**\n * Export every D1 (SQLite) table that belongs to a workspace, without a\n * hand-kept list that silently falls behind new migrations.\n *\n * Tables are discovered from the schema. A table with one of the workspace\n * columns is exported by that column; a table reached through a parent is\n * exported by the `scoped` SQL the product supplies. Every other table is\n * listed in the coverage report as `excluded` (with the product's reason) or\n * `unscoped`, so a reviewer sees exactly what the export leaves out.\n */\n\nimport type { ExportDataClass, ExportRow, ExportRowsSource } from './types'\n\n/** The slice of Cloudflare's `D1Database` used here. */\nexport interface D1ExportDatabase {\n prepare(sql: string): {\n bind(...values: unknown[]): {\n all<T = Record<string, unknown>>(): Promise<{ results: T[] }>\n }\n all<T = Record<string, unknown>>(): Promise<{ results: T[] }>\n }\n}\n\nexport interface D1TableCoverage {\n table: string\n status: 'exported' | 'excluded' | 'unscoped'\n /** The column or SQL used, or why the table is left out. */\n detail?: string\n}\n\nexport interface D1WorkspaceTablesOptions {\n db: D1ExportDatabase\n workspaceId: string\n /** Columns that hold the workspace id, checked in order, e.g. `['workspace_id']`. */\n workspaceColumns: readonly string[]\n /**\n * Tables keyed through a parent. The value is a WHERE clause; every `?` binds\n * the workspace id. Example: `{ message: 'thread_id IN (SELECT id FROM thread WHERE workspace_id = ?)' }`.\n */\n scoped?: Readonly<Record<string, string>>\n /** Tables left out on purpose, with the reason recorded in coverage. */\n exclude?: Readonly<Record<string, string>>\n /** Per-table columns to drop beyond the automatic credential policy. */\n omitColumns?: Readonly<Record<string, readonly string[]>>\n /** Per-table row rewrite, e.g. to decrypt a product-encrypted column. */\n transform?: Readonly<Record<string, (row: ExportRow) => ExportRow | Promise<ExportRow>>>\n /** Data class per table. Defaults to `records`. */\n classify?: (table: string) => ExportDataClass\n /** Rows per query. Default 500. */\n pageSize?: number\n}\n\nconst INTERNAL = /^(sqlite_|_cf_|d1_|__drizzle|_litestream)/\n\nfunction quote(identifier: string): string {\n return `\"${identifier.replace(/\"/g, '\"\"')}\"`\n}\n\nfunction sourceName(table: string): string {\n return table.toLowerCase().replace(/[^a-z0-9_.-]/g, '_').replace(/^[^a-z0-9]+/, '') || 'table'\n}\n\n/** Discover workspace tables. Returns row sources and a coverage report for the manifest. */\nexport async function d1WorkspaceTables(\n options: D1WorkspaceTablesOptions,\n): Promise<{ sources: ExportRowsSource[]; coverage: D1TableCoverage[] }> {\n const { db, workspaceId } = options\n const pageSize = options.pageSize ?? 500\n const tables = (\n await db.prepare(`SELECT name, sql FROM sqlite_master WHERE type = 'table' ORDER BY name`).all<{ name: string; sql: string | null }>()\n ).results.filter((t) => !INTERNAL.test(t.name))\n\n const sources: ExportRowsSource[] = []\n const coverage: D1TableCoverage[] = []\n for (const { name: table, sql } of tables) {\n const excluded = options.exclude?.[table]\n if (excluded !== undefined) {\n coverage.push({ table, status: 'excluded', detail: excluded })\n continue\n }\n let where = options.scoped?.[table]\n let detail = where\n if (!where) {\n const columns = (await db.prepare(`PRAGMA table_info(${quote(table)})`).all<{ name: string }>()).results.map((c) => c.name)\n const column = options.workspaceColumns.find((c) => columns.includes(c))\n if (!column) {\n coverage.push({ table, status: 'unscoped' })\n continue\n }\n where = `${quote(column)} = ?`\n detail = column\n }\n coverage.push({ table, status: 'exported', detail })\n\n const binds = Array.from({ length: (where.match(/\\?/g) ?? []).length }, () => workspaceId)\n const hasRowid = !/WITHOUT\\s+ROWID/i.test(sql ?? '')\n const transform = options.transform?.[table]\n sources.push({\n kind: 'rows',\n name: `db.${sourceName(table)}`,\n dataClass: options.classify?.(table) ?? 'records',\n description: `D1 table ${table} where ${detail}`,\n omitColumns: options.omitColumns?.[table],\n async expectedCount() {\n const result = await db.prepare(`SELECT COUNT(*) AS n FROM ${quote(table)} WHERE ${where}`).bind(...binds).all<{ n: number }>()\n return Number(result.results[0]?.n ?? 0)\n },\n async *rows() {\n // Keyset pagination on rowid keeps each page an index seek; tables\n // without a rowid fall back to OFFSET.\n let after = Number.MIN_SAFE_INTEGER\n let offset = 0\n for (;;) {\n const page = hasRowid\n ? await db\n .prepare(`SELECT rowid AS \"__export_rowid\", * FROM ${quote(table)} WHERE (${where}) AND rowid > ? ORDER BY rowid LIMIT ?`)\n .bind(...binds, after, pageSize)\n .all<ExportRow>()\n : await db\n .prepare(`SELECT * FROM ${quote(table)} WHERE ${where} LIMIT ? OFFSET ?`)\n .bind(...binds, pageSize, offset)\n .all<ExportRow>()\n const rows = page.results\n if (!rows.length) return\n const out: ExportRow[] = []\n for (const row of rows) {\n if (hasRowid) {\n after = Number(row.__export_rowid)\n delete row.__export_rowid\n }\n out.push(transform ? await transform(row) : row)\n }\n offset += rows.length\n yield out\n if (rows.length < pageSize) return\n }\n },\n })\n }\n return { sources, coverage }\n}\n","/** Ready-made sources for the stores agent apps use: R2 prefixes and KV prefixes. */\n\nimport type { ExportDataClass, ExportFile, ExportFilesSource } from './types'\n\n/** The slice of `R2Bucket` used to export objects. */\nexport interface R2FilesBucket {\n list(options: { prefix: string; cursor?: string; limit?: number }): Promise<{\n objects: { key: string; size: number }[]\n truncated: boolean\n cursor?: string\n }>\n get(key: string): Promise<{ body: ReadableStream<Uint8Array> } | null>\n}\n\n/**\n * Every object under the given prefixes. The archive path is the key with its\n * prefix removed, so `ws-1/guest/a.jpg` under prefix `ws-1/` lands at\n * `files/<name>/guest/a.jpg`. Prefixes must end at a workspace boundary\n * (`ws-1/`, not `ws-1`) or another workspace's objects would match.\n */\nexport function r2Files(args: {\n name: string\n dataClass: ExportDataClass\n bucket: R2FilesBucket\n prefixes: readonly string[]\n /** Optionally rewrite bytes, e.g. to decrypt objects the product encrypted. */\n read?: (key: string, body: ReadableStream<Uint8Array>) => Promise<ReadableStream<Uint8Array> | Uint8Array | string | null>\n description?: string\n}): ExportFilesSource {\n for (const prefix of args.prefixes) {\n if (!prefix.endsWith('/')) throw new Error(`workspace-export: R2 prefix \"${prefix}\" must end with \"/\"`)\n }\n return {\n kind: 'files',\n name: args.name,\n dataClass: args.dataClass,\n description: args.description ?? `R2 objects under ${args.prefixes.join(', ')}`,\n async *files(): AsyncIterable<ExportFile> {\n for (const prefix of args.prefixes) {\n let cursor: string | undefined\n do {\n const page = await args.bucket.list({ prefix, cursor, limit: 1000 })\n for (const object of page.objects) {\n yield {\n path: args.prefixes.length > 1 ? object.key : object.key.slice(prefix.length),\n async open() {\n const found = await args.bucket.get(object.key)\n if (!found) return null\n return args.read ? args.read(object.key, found.body) : found.body\n },\n }\n }\n cursor = page.truncated ? page.cursor : undefined\n } while (cursor)\n }\n },\n }\n}\n\n/** The slice of `KVNamespace` used to export values. */\nexport interface KVFilesNamespace {\n list(options: { prefix: string; cursor?: string; limit?: number }): Promise<{\n keys: { name: string }[]\n list_complete: boolean\n cursor?: string\n }>\n get(key: string, type: 'stream'): Promise<ReadableStream<Uint8Array> | null>\n}\n\n/** Every KV value under a prefix, written as a file at the key minus the prefix. */\nexport function kvFiles(args: {\n name: string\n dataClass: ExportDataClass\n kv: KVFilesNamespace\n prefix: string\n read?: (key: string, body: ReadableStream<Uint8Array>) => Promise<ReadableStream<Uint8Array> | Uint8Array | string | null>\n description?: string\n}): ExportFilesSource {\n return {\n kind: 'files',\n name: args.name,\n dataClass: args.dataClass,\n description: args.description ?? `KV values under ${args.prefix}`,\n async *files(): AsyncIterable<ExportFile> {\n let cursor: string | undefined\n do {\n const page = await args.kv.list({ prefix: args.prefix, cursor, limit: 1000 })\n for (const key of page.keys) {\n yield {\n path: key.name.slice(args.prefix.length),\n async open() {\n const body = await args.kv.get(key.name, 'stream')\n if (!body) return null\n return args.read ? args.read(key.name, body) : body\n },\n }\n }\n cursor = page.list_complete ? undefined : page.cursor\n } while (cursor)\n },\n }\n}\n","/**\n * The sandbox-archive source every app needs, so no product hand-rolls box\n * lifecycle around `fs.openArchive`.\n *\n * `openArchive` refuses a box that is not running. A stopped box is resumed for\n * the export and stopped again once its archive has been read, so exporting\n * neither fails on an idle workspace nor leaves the owner paying for a box they\n * had stopped. A box that no longer exists exports nothing.\n */\n\nimport type { ExportArchiveSource, ExportDataClass } from './types'\n\n/** The slice of the Sandbox SDK's `SandboxInstance` this source uses. */\nexport interface ArchivableBox {\n readonly status: string\n resume(): Promise<void>\n stop?(): Promise<void>\n waitFor(status: 'running', options?: { timeoutMs?: number }): Promise<void>\n fs: { openArchive(dir: string, options?: { signal?: AbortSignal }): Promise<ReadableStream<Uint8Array>> }\n}\n\nconst GONE = new Set(['deleted', 'expired', 'failed'])\n\n/**\n * One sandbox's filesystem as `sandbox/<name>.tar.gz`. `getBox` returns the\n * SDK instance (`client.get(id)`), or `null` when the box is gone.\n */\nexport function sandboxArchive(args: {\n name: string\n getBox(): Promise<ArchivableBox | null>\n /** Directory to archive, relative to the box workspace. Default `.`. */\n dir?: string\n dataClass?: ExportDataClass\n description?: string\n /** How long to wait for a resumed box. Default 120 s. */\n resumeTimeoutMs?: number\n}): ExportArchiveSource {\n return {\n kind: 'archive',\n name: args.name,\n dataClass: args.dataClass ?? 'sandbox',\n description: args.description,\n async open() {\n const box = await args.getBox()\n if (!box || GONE.has(box.status)) return null\n const wasStopped = box.status === 'stopped'\n if (wasStopped) await box.resume()\n if (box.status !== 'running' || wasStopped) await box.waitFor('running', { timeoutMs: args.resumeTimeoutMs ?? 120_000 })\n const archive = await box.fs.openArchive(args.dir ?? '.')\n if (!wasStopped || !box.stop) return archive\n // Put the box back the way the owner left it once the archive is read.\n const restore = () => box.stop!().catch(() => {})\n return archive.pipeThrough(\n new TransformStream<Uint8Array, Uint8Array>({\n flush: () => restore(),\n }),\n )\n },\n }\n}\n"],"mappings":";;;;;;;;AAQA,IAAM,aAAa,MAAM;AACvB,QAAM,QAAQ,IAAI,YAAY,GAAG;AACjC,WAAS,IAAI,GAAG,IAAI,KAAK,KAAK,GAAG;AAC/B,QAAI,IAAI;AACR,aAAS,IAAI,GAAG,IAAI,GAAG,KAAK,EAAG,KAAI,IAAI,IAAI,aAAc,MAAM,IAAK,MAAM;AAC1E,UAAM,CAAC,IAAI,MAAM;AAAA,EACnB;AAC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C;AAAA,UAC1C,OAAO,MAAM,QAAQ;AAAA,QACvB,CAAC;AAAA,MACH;AAAA,IACF;AAAA,EACF;AACF;","names":["a","b","out","take","job","unit"]}
1
+ {"version":3,"sources":["../../src/workspace-export/checksum.ts","../../src/workspace-export/secrets.ts","../../src/workspace-export/tar.ts","../../src/workspace-export/zip.ts","../../src/workspace-export/engine.ts","../../src/workspace-export/routes.ts","../../src/workspace-export/storage.ts","../../src/workspace-export/d1.ts","../../src/workspace-export/sources.ts","../../src/workspace-export/sandbox.ts"],"sourcesContent":["/**\n * Incremental CRC-32 (the zip checksum) and SHA-256 (the manifest checksum).\n *\n * Both run over a stream one chunk at a time so an export never buffers a whole\n * file. SHA-256 uses the Workers-native `crypto.DigestStream` when present and a\n * small pure implementation otherwise (Node, tests); both produce identical hex.\n */\n\nconst CRC_TABLE = (() => {\n const table = new Uint32Array(256)\n for (let n = 0; n < 256; n += 1) {\n let c = n\n for (let k = 0; k < 8; k += 1) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1\n table[n] = c >>> 0\n }\n return table\n})()\n\n/** Continue a CRC-32 over `bytes`. Start with `0`; the result is the finished CRC. */\nexport function crc32Update(crc: number, bytes: Uint8Array): number {\n let c = (crc ^ 0xffffffff) >>> 0\n for (let i = 0; i < bytes.length; i += 1) c = (CRC_TABLE[(c ^ bytes[i]!) & 0xff]! ^ (c >>> 8)) >>> 0\n return (c ^ 0xffffffff) >>> 0\n}\n\nexport interface Sha256Hasher {\n update(bytes: Uint8Array): Promise<void>\n digestHex(): Promise<string>\n}\n\ninterface DigestStreamLike extends WritableStream<Uint8Array> {\n digest: Promise<ArrayBuffer>\n}\n\nfunction toHex(bytes: Uint8Array): string {\n let out = ''\n for (const b of bytes) out += b.toString(16).padStart(2, '0')\n return out\n}\n\n/** A streaming SHA-256. Prefers the runtime's native digest stream. */\nexport function createSha256(): Sha256Hasher {\n const DigestStream = (globalThis.crypto as unknown as {\n DigestStream?: new (algorithm: string) => DigestStreamLike\n }).DigestStream\n if (DigestStream) {\n const stream = new DigestStream('SHA-256')\n const writer = stream.getWriter()\n return {\n update: (bytes) => writer.write(bytes),\n async digestHex() {\n await writer.close()\n return toHex(new Uint8Array(await stream.digest))\n },\n }\n }\n const pure = new PureSha256()\n return {\n async update(bytes) {\n pure.update(bytes)\n },\n async digestHex() {\n return toHex(pure.digest())\n },\n }\n}\n\nconst K = new Uint32Array([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,\n])\n\nclass PureSha256 {\n private h = new Uint32Array([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n ])\n private block = new Uint8Array(64)\n private blockLength = 0\n private totalLength = 0\n private w = new Uint32Array(64)\n\n update(bytes: Uint8Array): void {\n this.totalLength += bytes.length\n let offset = 0\n while (offset < bytes.length) {\n const take = Math.min(64 - this.blockLength, bytes.length - offset)\n this.block.set(bytes.subarray(offset, offset + take), this.blockLength)\n this.blockLength += take\n offset += take\n if (this.blockLength === 64) {\n this.compress(this.block)\n this.blockLength = 0\n }\n }\n }\n\n digest(): Uint8Array {\n const bitLength = this.totalLength * 8\n const padLength = this.blockLength < 56 ? 56 - this.blockLength : 120 - this.blockLength\n const pad = new Uint8Array(padLength + 8)\n pad[0] = 0x80\n const view = new DataView(pad.buffer)\n view.setUint32(padLength, Math.floor(bitLength / 0x100000000))\n view.setUint32(padLength + 4, bitLength >>> 0)\n const total = this.totalLength\n this.update(pad)\n this.totalLength = total\n const out = new Uint8Array(32)\n const outView = new DataView(out.buffer)\n for (let i = 0; i < 8; i += 1) outView.setUint32(i * 4, this.h[i]!)\n return out\n }\n\n private compress(chunk: Uint8Array): void {\n const w = this.w\n const view = new DataView(chunk.buffer, chunk.byteOffset, 64)\n for (let i = 0; i < 16; i += 1) w[i] = view.getUint32(i * 4)\n for (let i = 16; i < 64; i += 1) {\n const a = w[i - 15]!\n const b = w[i - 2]!\n const s0 = ((a >>> 7) | (a << 25)) ^ ((a >>> 18) | (a << 14)) ^ (a >>> 3)\n const s1 = ((b >>> 17) | (b << 15)) ^ ((b >>> 19) | (b << 13)) ^ (b >>> 10)\n w[i] = (w[i - 16]! + s0 + w[i - 7]! + s1) >>> 0\n }\n let [a, b, c, d, e, f, g, h] = this.h as unknown as number[]\n for (let i = 0; i < 64; i += 1) {\n const S1 = ((e! >>> 6) | (e! << 26)) ^ ((e! >>> 11) | (e! << 21)) ^ ((e! >>> 25) | (e! << 7))\n const ch = (e! & f!) ^ (~e! & g!)\n const t1 = (h! + S1 + ch + K[i]! + w[i]!) >>> 0\n const S0 = ((a! >>> 2) | (a! << 30)) ^ ((a! >>> 13) | (a! << 19)) ^ ((a! >>> 22) | (a! << 10))\n const maj = (a! & b!) ^ (a! & c!) ^ (b! & c!)\n const t2 = (S0 + maj) >>> 0\n h = g\n g = f\n f = e\n e = (d! + t1) >>> 0\n d = c\n c = b\n b = a\n a = (t1 + t2) >>> 0\n }\n this.h[0] = (this.h[0]! + a!) >>> 0\n this.h[1] = (this.h[1]! + b!) >>> 0\n this.h[2] = (this.h[2]! + c!) >>> 0\n this.h[3] = (this.h[3]! + d!) >>> 0\n this.h[4] = (this.h[4]! + e!) >>> 0\n this.h[5] = (this.h[5]! + f!) >>> 0\n this.h[6] = (this.h[6]! + g!) >>> 0\n this.h[7] = (this.h[7]! + h!) >>> 0\n }\n}\n","/**\n * Keeps credentials out of workspace exports.\n *\n * Three layers, applied to every byte an export writes:\n * 1. Column and JSON-key names that hold credentials are replaced with\n * `[redacted]` (`password`, `*_token`, `*_api_key`, `*_ciphertext`, ...).\n * 2. Values that look like credentials (provider key prefixes, JWTs, private\n * keys) and the exact values the product passes as `knownSecrets` are masked\n * wherever they appear: in row values, in nested JSON, and in file bytes.\n * 3. Well-known credential files inside a sandbox tar are blanked.\n *\n * Byte masking is same-length (`*`), so tar headers and offsets stay valid.\n * Everything here fails toward redaction: a false positive costs the owner one\n * masked value; a false negative would publish a credential.\n */\n\nexport const REDACTED = '[redacted]'\nconst MASK_BYTE = 0x2a\n\nconst CREDENTIAL_PATTERNS: readonly string[] = [\n String.raw`sk-ant-[A-Za-z0-9_-]{16,}`,\n String.raw`sk-(?:proj-|tan-|or-v1-|svcacct-)?[A-Za-z0-9_-]{20,}`,\n String.raw`(?:sk|rk)_(?:live|test|sb)_[A-Za-z0-9_]{12,}`,\n String.raw`whsec_[A-Za-z0-9+/=]{16,}`,\n String.raw`gh[pousr]_[A-Za-z0-9]{30,}`,\n String.raw`github_pat_[A-Za-z0-9_]{40,}`,\n String.raw`xox[abposr]-[A-Za-z0-9-]{10,}`,\n String.raw`AKIA[0-9A-Z]{16}`,\n String.raw`AIza[0-9A-Za-z_-]{35}`,\n String.raw`ya29\\.[0-9A-Za-z_-]{20,}`,\n String.raw`glpat-[A-Za-z0-9_-]{20,}`,\n String.raw`npm_[A-Za-z0-9]{36}`,\n String.raw`hf_[A-Za-z0-9]{30,}`,\n String.raw`r8_[A-Za-z0-9]{30,}`,\n String.raw`gsk_[A-Za-z0-9]{40,}`,\n String.raw`xai-[A-Za-z0-9]{40,}`,\n String.raw`lak_[A-Za-z0-9_-]{16,}`,\n String.raw`eyJ[A-Za-z0-9_-]{10,}\\.eyJ[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{10,}`,\n String.raw`-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[A-Za-z0-9+/=\\r\\n\\t ]*(?:-----END [A-Z0-9 ]*PRIVATE KEY-----)?`,\n]\n\n/** Names whose value is a credential, after camelCase is folded to snake_case. */\nconst SECRET_NAME =\n /(^|_)(secret|secrets|password|passwd|passphrase|token|credential|credentials|ciphertext|encrypted|bearer|apikey|privatekey|cookie)(_|$)|api_?key|private_?key|(key|secret|token|password|challenge|state|nonce|credential)_(hash|digest)$/\n/** Usage counters that merely mention tokens. */\nconst TOKEN_METRIC = /token_(count|counts|usage|budget|limit|cost)$|^(input|output|total|max|prompt|completion|reasoning|cached)_tokens?$/\n\nfunction snake(name: string): string {\n return name\n .replace(/([a-z0-9])([A-Z])/g, '$1_$2')\n .replace(/[-\\s.]+/g, '_')\n .toLowerCase()\n}\n\n/** True when a column or JSON key named `name` holds a credential. */\nexport function isSecretName(name: string): boolean {\n const folded = snake(name)\n if (TOKEN_METRIC.test(folded)) return false\n return SECRET_NAME.test(folded)\n}\n\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n}\n\nexport interface SecretScanner {\n /** Replace credential-shaped substrings. Returns the count replaced. */\n maskText(text: string): { text: string; count: number }\n /** Redact a row or any JSON value: credential names and credential values. */\n redactValue(value: unknown): { value: unknown; count: number }\n /** A same-length byte masker for file contents. `onMask` receives each count. */\n maskBytes(onMask: (count: number) => void): TransformStream<Uint8Array, Uint8Array>\n}\n\n/**\n * Build the scanner for one export. `knownSecrets` are exact values the product\n * holds (its own API keys, the workspace's sandbox key) that must never appear,\n * whatever their shape. Values shorter than 8 characters are ignored.\n */\nexport function createSecretScanner(options: { knownSecrets?: readonly string[] } = {}): SecretScanner {\n const known = [...new Set(options.knownSecrets ?? [])]\n .filter((s) => typeof s === 'string' && s.length >= 8)\n .sort((a, b) => b.length - a.length)\n .map(escapeRegExp)\n const source = [...known, ...CREDENTIAL_PATTERNS].join('|')\n const pattern = () => new RegExp(source, 'g')\n\n function maskText(text: string): { text: string; count: number } {\n let count = 0\n const out = text.replace(pattern(), () => {\n count += 1\n return REDACTED\n })\n return { text: out, count }\n }\n\n function redactJson(value: unknown, depth: number): { value: unknown; count: number } {\n if (typeof value === 'string') {\n const masked = maskText(value)\n return { value: masked.text, count: masked.count }\n }\n if (depth > 64 || value === null || typeof value !== 'object') return { value, count: 0 }\n let count = 0\n if (Array.isArray(value)) {\n const out = value.map((item) => {\n const result = redactJson(item, depth + 1)\n count += result.count\n return result.value\n })\n return { value: out, count }\n }\n const out: Record<string, unknown> = {}\n for (const [key, item] of Object.entries(value)) {\n if (isSecretName(key) && item !== null && item !== '' && typeof item !== 'boolean') {\n out[key] = REDACTED\n count += 1\n continue\n }\n const result = redactJson(item, depth + 1)\n out[key] = result.value\n count += result.count\n }\n return { value: out, count }\n }\n\n function redactValue(value: unknown): { value: unknown; count: number } {\n if (typeof value === 'string') {\n const trimmed = value.trimStart()\n if (trimmed.startsWith('{') || trimmed.startsWith('[')) {\n try {\n const parsed = JSON.parse(value) as unknown\n const result = redactJson(parsed, 0)\n return result.count ? { value: JSON.stringify(result.value), count: result.count } : { value, count: 0 }\n } catch {\n // Not JSON; scan it as text.\n }\n }\n const masked = maskText(value)\n return { value: masked.text, count: masked.count }\n }\n if (value instanceof Uint8Array || value instanceof ArrayBuffer) return { value, count: 0 }\n return redactJson(value, 0)\n }\n\n function maskBytes(onMask: (count: number) => void): TransformStream<Uint8Array, Uint8Array> {\n // Keep a tail so a credential split across two chunks is seen whole.\n const window = 8192\n const maxCarry = 65536\n let carry = new Uint8Array(0)\n\n function scan(buffer: Uint8Array, final: boolean): number {\n const text = decodeBytes(buffer)\n const regex = pattern()\n let emitEnd = final ? buffer.length : Math.max(0, buffer.length - window)\n let masked = 0\n for (let match = regex.exec(text); match; match = regex.exec(text)) {\n const start = match.index\n const end = start + match[0].length\n if (match[0].length === 0) {\n regex.lastIndex += 1\n continue\n }\n if (!final && end === buffer.length) {\n // Possibly truncated; leave it for the next chunk to see whole.\n emitEnd = Math.min(emitEnd, start)\n break\n }\n buffer.fill(MASK_BYTE, start, end)\n masked += 1\n }\n if (masked) onMask(masked)\n if (!final && buffer.length - emitEnd > maxCarry) emitEnd = buffer.length - window\n return emitEnd\n }\n\n // Decompressors emit small chunks. Scanning each one re-reads the carry\n // window, which cost 4x on 4 KiB chunks, so input is gathered into blocks.\n const block = 256 * 1024\n let pending: Uint8Array[] = []\n let pendingLength = 0\n\n function drain(controller: TransformStreamDefaultController<Uint8Array>, final: boolean) {\n const buffer = new Uint8Array(carry.length + pendingLength)\n buffer.set(carry, 0)\n let offset = carry.length\n for (const part of pending) {\n buffer.set(part, offset)\n offset += part.length\n }\n pending = []\n pendingLength = 0\n const emitEnd = scan(buffer, final)\n if (emitEnd > 0) controller.enqueue(buffer.slice(0, emitEnd))\n carry = buffer.slice(emitEnd)\n }\n\n return new TransformStream<Uint8Array, Uint8Array>({\n transform(chunk, controller) {\n pending.push(chunk)\n pendingLength += chunk.length\n if (pendingLength >= block) drain(controller, false)\n },\n flush(controller) {\n if (carry.length || pendingLength) drain(controller, true)\n },\n })\n }\n\n return { maskText, redactValue, maskBytes }\n}\n\n/**\n * One UTF-16 code unit per byte, so string indexes are byte offsets. A native\n * windows-1252 decoder keeps that property and is several times faster; the\n * manual decode covers runtimes whose TextDecoder lacks it.\n */\nconst nativeLatin1 = (() => {\n try {\n const decoder = new TextDecoder('latin1')\n return decoder.decode(new Uint8Array([0x41, 0x80, 0xff])).length === 3 ? decoder : null\n } catch {\n return null\n }\n})()\n\nfunction decodeBytes(buffer: Uint8Array): string {\n if (nativeLatin1) return nativeLatin1.decode(buffer)\n let text = ''\n for (let i = 0; i < buffer.length; i += 8192) text += String.fromCharCode(...buffer.subarray(i, i + 8192))\n return text\n}\n\n/** Credential stores that are blanked wholesale inside a sandbox archive. */\nconst CREDENTIAL_FILES = [\n /(^|\\/)\\.git-credentials$/,\n /(^|\\/)\\.netrc$/,\n /(^|\\/)\\.pgpass$/,\n /(^|\\/)\\.npmrc$/,\n /(^|\\/)\\.pypirc$/,\n /(^|\\/)\\.docker\\/config\\.json$/,\n /(^|\\/)\\.aws\\/credentials$/,\n /(^|\\/)\\.kube\\/config$/,\n /(^|\\/)\\.config\\/gh\\/hosts\\.ya?ml$/,\n /(^|\\/)\\.codex\\/auth\\.json$/,\n /(^|\\/)\\.claude\\/\\.credentials\\.json$/,\n /(^|\\/)opencode\\/auth\\.json$/,\n /(^|\\/)\\.ssh\\/id_[^/]*$/,\n]\n\nexport function isCredentialFile(path: string): boolean {\n const normalized = path.replace(/^\\.\\//, '')\n if (normalized.endsWith('.pub')) return false\n return CREDENTIAL_FILES.some((pattern) => pattern.test(normalized))\n}\n","/**\n * Reads an uncompressed tar stream in flight without changing its length.\n *\n * It counts members for the manifest and overwrites the contents of known\n * credential files (see `isCredentialFile`) with `*`, so the archive stays a\n * valid tar that still shows the file existed. Handles ustar prefixes, GNU long\n * names (`L`) and pax `path=` records.\n */\n\nimport { isCredentialFile } from './secrets'\n\nexport interface TarStats {\n files: number\n bytes: number\n blanked: string[]\n}\n\nconst BLOCK = 512\nconst MAX_NAME_RECORD = 1 << 20\n\nfunction readString(block: Uint8Array, start: number, length: number): string {\n let end = start\n while (end < start + length && block[end] !== 0) end += 1\n return new TextDecoder().decode(block.subarray(start, end))\n}\n\nfunction readSize(block: Uint8Array): number {\n // GNU base-256 for sizes over 8 GiB.\n if (block[124]! & 0x80) {\n let size = 0\n for (let i = 125; i < 136; i += 1) size = size * 256 + block[i]!\n return size\n }\n const octal = readString(block, 124, 12).trim()\n return octal ? Number.parseInt(octal, 8) : 0\n}\n\nfunction paxPath(record: string): string | undefined {\n for (const line of record.split('\\n')) {\n const space = line.indexOf(' ')\n if (space < 0) continue\n const field = line.slice(space + 1)\n if (field.startsWith('path=')) return field.slice(5)\n }\n return undefined\n}\n\nexport function createTarInspector(stats: TarStats): TransformStream<Uint8Array, Uint8Array> {\n const header = new Uint8Array(BLOCK)\n let headerFill = 0\n // Bytes of member data (plus padding) still to pass before the next header.\n let dataRemaining = 0\n let paddingRemaining = 0\n let blanking = false\n let capture: { kind: 'L' | 'x'; parts: Uint8Array[]; length: number } | null = null\n let pendingName: string | undefined\n let ended = false\n\n function onHeader(): void {\n if (header.every((b) => b === 0)) {\n ended = true\n return\n }\n const type = String.fromCharCode(header[156]!)\n const size = readSize(header)\n dataRemaining = size\n paddingRemaining = (BLOCK - (size % BLOCK)) % BLOCK\n blanking = false\n capture = null\n if ((type === 'L' || type === 'x') && size <= MAX_NAME_RECORD) {\n capture = { kind: type, parts: [], length: 0 }\n return\n }\n const prefix = header[257] === 0x75 ? readString(header, 345, 155) : ''\n const base = readString(header, 0, 100)\n const name = pendingName ?? (prefix ? `${prefix}/${base}` : base)\n pendingName = undefined\n if (type === '0' || type === '\\0' || type === '7') {\n stats.files += 1\n stats.bytes += size\n if (isCredentialFile(name)) {\n blanking = true\n stats.blanked.push(name)\n }\n }\n }\n\n return new TransformStream<Uint8Array, Uint8Array>({\n transform(chunk, controller) {\n const out = chunk.slice()\n let at = 0\n while (at < out.length && !ended) {\n if (dataRemaining > 0) {\n const take = Math.min(dataRemaining, out.length - at)\n if (blanking) out.fill(0x2a, at, at + take)\n if (capture) {\n capture.parts.push(out.slice(at, at + take))\n capture.length += take\n }\n dataRemaining -= take\n at += take\n if (dataRemaining === 0 && capture) {\n const joined = new Uint8Array(capture.length)\n let offset = 0\n for (const part of capture.parts) {\n joined.set(part, offset)\n offset += part.length\n }\n const text = new TextDecoder().decode(joined)\n pendingName = capture.kind === 'L' ? text.replace(/\\0+$/, '') : (paxPath(text) ?? pendingName)\n capture = null\n }\n continue\n }\n if (paddingRemaining > 0) {\n const take = Math.min(paddingRemaining, out.length - at)\n paddingRemaining -= take\n at += take\n continue\n }\n const take = Math.min(BLOCK - headerFill, out.length - at)\n header.set(out.subarray(at, at + take), headerFill)\n headerFill += take\n at += take\n if (headerFill === BLOCK) {\n headerFill = 0\n onHeader()\n }\n }\n controller.enqueue(out)\n },\n })\n}\n","/**\n * Streams a zip whose every entry was already written and measured.\n *\n * Because each entry's CRC-32 and sizes are known before the first byte goes\n * out, local headers carry real values (no data descriptors) and the total\n * length is exact, so the download response can send `Content-Length`. Zip64\n * records are added only when a size, offset or entry count needs them, which\n * keeps small archives readable by every unzip tool.\n */\n\nexport interface ZipEntrySpec {\n /** Path inside the archive, `/`-separated, no leading slash. */\n name: string\n /** 0 = stored, 8 = deflate. */\n method: 0 | 8\n crc32: number\n /** Bytes `open()` yields (after compression for method 8). */\n compressedSize: number\n uncompressedSize: number\n modifiedAt: Date\n open(): Promise<ReadableStream<Uint8Array>>\n}\n\nconst U32_MAX = 0xffffffff\nconst U16_MAX = 0xffff\n\ninterface Layout {\n name: Uint8Array\n localHeader: Uint8Array\n offset: number\n}\n\nfunction dosDateTime(date: Date): { time: number; date: number } {\n const year = Math.max(1980, date.getUTCFullYear())\n return {\n time: (date.getUTCHours() << 11) | (date.getUTCMinutes() << 5) | Math.floor(date.getUTCSeconds() / 2),\n date: ((year - 1980) << 9) | ((date.getUTCMonth() + 1) << 5) | date.getUTCDate(),\n }\n}\n\nfunction setU64(view: DataView, offset: number, value: number): void {\n view.setUint32(offset, value % 0x100000000, true)\n view.setUint32(offset + 4, Math.floor(value / 0x100000000), true)\n}\n\nfunction localHeader(entry: ZipEntrySpec, name: Uint8Array): Uint8Array {\n const zip64 = entry.compressedSize >= U32_MAX || entry.uncompressedSize >= U32_MAX\n const extraLength = zip64 ? 20 : 0\n const out = new Uint8Array(30 + name.length + extraLength)\n const view = new DataView(out.buffer)\n const { time, date } = dosDateTime(entry.modifiedAt)\n view.setUint32(0, 0x04034b50, true)\n view.setUint16(4, zip64 ? 45 : 20, true)\n view.setUint16(6, 0x0800, true)\n view.setUint16(8, entry.method, true)\n view.setUint16(10, time, true)\n view.setUint16(12, date, true)\n view.setUint32(14, entry.crc32, true)\n view.setUint32(18, zip64 ? U32_MAX : entry.compressedSize, true)\n view.setUint32(22, zip64 ? U32_MAX : entry.uncompressedSize, true)\n view.setUint16(26, name.length, true)\n view.setUint16(28, extraLength, true)\n out.set(name, 30)\n if (zip64) {\n const at = 30 + name.length\n view.setUint16(at, 0x0001, true)\n view.setUint16(at + 2, 16, true)\n setU64(view, at + 4, entry.uncompressedSize)\n setU64(view, at + 12, entry.compressedSize)\n }\n return out\n}\n\nfunction centralHeader(entry: ZipEntrySpec, layout: Layout): Uint8Array {\n const bigU = entry.uncompressedSize >= U32_MAX\n const bigC = entry.compressedSize >= U32_MAX\n const bigO = layout.offset >= U32_MAX\n const extraFields = (bigU ? 1 : 0) + (bigC ? 1 : 0) + (bigO ? 1 : 0)\n const extraLength = extraFields ? 4 + extraFields * 8 : 0\n const name = layout.name\n const out = new Uint8Array(46 + name.length + extraLength)\n const view = new DataView(out.buffer)\n const { time, date } = dosDateTime(entry.modifiedAt)\n const version = extraFields ? 45 : 20\n view.setUint32(0, 0x02014b50, true)\n view.setUint16(4, (3 << 8) | version, true)\n view.setUint16(6, version, true)\n view.setUint16(8, 0x0800, true)\n view.setUint16(10, entry.method, true)\n view.setUint16(12, time, true)\n view.setUint16(14, date, true)\n view.setUint32(16, entry.crc32, true)\n view.setUint32(20, bigC ? U32_MAX : entry.compressedSize, true)\n view.setUint32(24, bigU ? U32_MAX : entry.uncompressedSize, true)\n view.setUint16(28, name.length, true)\n view.setUint16(30, extraLength, true)\n view.setUint32(38, (0o100644 << 16) >>> 0, true)\n view.setUint32(42, bigO ? U32_MAX : layout.offset, true)\n out.set(name, 46)\n if (extraFields) {\n let at = 46 + name.length\n view.setUint16(at, 0x0001, true)\n view.setUint16(at + 2, extraFields * 8, true)\n at += 4\n if (bigU) {\n setU64(view, at, entry.uncompressedSize)\n at += 8\n }\n if (bigC) {\n setU64(view, at, entry.compressedSize)\n at += 8\n }\n if (bigO) setU64(view, at, layout.offset)\n }\n return out\n}\n\nfunction endRecords(count: number, cdOffset: number, cdSize: number): Uint8Array {\n const zip64 = count >= U16_MAX || cdOffset >= U32_MAX || cdSize >= U32_MAX\n const out = new Uint8Array((zip64 ? 56 + 20 : 0) + 22)\n const view = new DataView(out.buffer)\n let at = 0\n if (zip64) {\n view.setUint32(0, 0x06064b50, true)\n setU64(view, 4, 44)\n view.setUint16(12, (3 << 8) | 45, true)\n view.setUint16(14, 45, true)\n setU64(view, 24, count)\n setU64(view, 32, count)\n setU64(view, 40, cdSize)\n setU64(view, 48, cdOffset)\n view.setUint32(56, 0x07064b50, true)\n setU64(view, 64, cdOffset + cdSize)\n view.setUint32(72, 1, true)\n at = 76\n }\n view.setUint32(at, 0x06054b50, true)\n view.setUint16(at + 8, zip64 ? U16_MAX : count, true)\n view.setUint16(at + 10, zip64 ? U16_MAX : count, true)\n view.setUint32(at + 12, zip64 ? U32_MAX : cdSize, true)\n view.setUint32(at + 16, zip64 ? U32_MAX : cdOffset, true)\n return out\n}\n\n/** Lay out the archive and return its exact byte length and body stream. */\nexport function createZipStream(entries: ZipEntrySpec[]): { length: number; stream: ReadableStream<Uint8Array> } {\n const encoder = new TextEncoder()\n const layouts: Layout[] = []\n let offset = 0\n for (const entry of entries) {\n const name = encoder.encode(entry.name)\n const header = localHeader(entry, name)\n layouts.push({ name, localHeader: header, offset })\n offset += header.length + entry.compressedSize\n }\n const central = entries.map((entry, i) => centralHeader(entry, layouts[i]!))\n const cdSize = central.reduce((sum, part) => sum + part.length, 0)\n const end = endRecords(entries.length, offset, cdSize)\n const length = offset + cdSize + end.length\n\n let index = 0\n let phase: 'entries' | 'tail' | 'done' = 'entries'\n let reader: ReadableStreamDefaultReader<Uint8Array> | null = null\n let written = 0\n\n const stream = new ReadableStream<Uint8Array>({\n async pull(controller) {\n if (phase === 'entries') {\n if (reader) {\n const { done, value } = await reader.read()\n if (!done) {\n written += value.length\n controller.enqueue(value)\n return\n }\n reader = null\n const expected = entries[index]!.compressedSize\n if (written !== expected) {\n controller.error(new Error(`zip entry ${entries[index]!.name} produced ${written} bytes, expected ${expected}`))\n return\n }\n index += 1\n }\n if (index < entries.length) {\n controller.enqueue(layouts[index]!.localHeader)\n written = 0\n reader = (await entries[index]!.open()).getReader()\n return\n }\n phase = 'tail'\n }\n if (phase === 'tail') {\n for (const part of central) controller.enqueue(part)\n controller.enqueue(end)\n phase = 'done'\n controller.close()\n }\n },\n async cancel(reason) {\n await reader?.cancel(reason)\n },\n })\n return { length, stream }\n}\n","/**\n * Builds a workspace export one source at a time and serves it as a zip.\n *\n * Each source becomes a unit. A unit streams its data through the credential\n * masks, records CRC-32, SHA-256 and sizes, and stores the bytes as bounded\n * segments. The job record (`job.json`) tracks which units are done, so an\n * export resumes after a closed tab or a dropped request instead of starting\n * over. When every unit is done, the manifest is written, and the download\n * route stitches the stored segments into one zip with an exact length.\n */\n\nimport { assertSafeKeySegment } from '../object-store'\nimport { crc32Update, createSha256 } from './checksum'\nimport { createSecretScanner, isSecretName, REDACTED, type SecretScanner } from './secrets'\nimport type { ExportStorage } from './storage'\nimport { createTarInspector } from './tar'\nimport type {\n ExportJob,\n ExportPlan,\n ExportProgress,\n ExportRow,\n ExportSource,\n ExportUnit,\n StoredEntry,\n} from './types'\nimport { createZipStream, type ZipEntrySpec } from './zip'\n\nexport const MANIFEST_SCHEMA = 'tangle.workspace-export/v1'\nconst SEGMENT_BYTES = 8 * 1024 * 1024\n// A short lease, renewed while a request works, so a request that dies (closed\n// tab, cancelled fetch) stalls the export for at most a minute.\nconst LEASE_MS = 60_000\nconst HEARTBEAT_MS = 20_000\nconst MAX_ATTEMPTS = 3\n/** Files written per request. Each read and segment write is a subrequest, and\n * Workers cap subrequests per request, so a large files source spans requests. */\nconst FILES_PER_REQUEST = 200\nconst SOURCE_NAME = /^[a-z0-9][a-z0-9_.-]{0,95}$/\n\nexport interface ExportEngineOptions {\n /** Product name for the manifest and the download filename, e.g. `hospitality`. */\n app: string\n storage: ExportStorage\n plan(args: { workspaceId: string }): ExportPlan | Promise<ExportPlan>\n /** Exact credential values held by the product that must never appear. */\n knownSecrets?(args: { workspaceId: string }): readonly string[] | Promise<readonly string[]>\n /** Storage key prefix. Default `workspace-exports`. */\n prefix?: string\n /** Sandbox archives read at once in one request. Default 4. */\n archiveConcurrency?: number\n now?: () => number\n}\n\nclass LeaseLost extends Error {}\n\nfunction iso(ms: number): string {\n return new Date(ms).toISOString()\n}\n\nfunction errorText(scanner: SecretScanner, err: unknown): string {\n const raw = err instanceof Error ? err.message : String(err)\n return scanner.maskText(raw).text.slice(0, 300)\n}\n\nfunction toStream(body: ReadableStream<Uint8Array> | Uint8Array | string): ReadableStream<Uint8Array> {\n if (body instanceof ReadableStream) return body\n const bytes = typeof body === 'string' ? new TextEncoder().encode(body) : body\n return new ReadableStream({\n start(controller) {\n if (bytes.length) controller.enqueue(bytes)\n controller.close()\n },\n })\n}\n\nfunction concatenate(parts: Uint8Array[], length: number): Uint8Array {\n const out = new Uint8Array(length)\n let offset = 0\n for (const part of parts) {\n out.set(part, offset)\n offset += part.length\n }\n return out\n}\n\n/** Make a file path safe and unique inside the archive. */\nfunction safePath(path: string, used: Set<string>): string {\n const parts = path\n .replace(/\\\\/g, '/')\n .split('/')\n .filter((p) => p && p !== '.' && p !== '..')\n .map((p) => p.replace(/[\\0-\\x1f]/g, '_'))\n let candidate = parts.join('/') || 'file'\n let n = 1\n while (used.has(candidate)) {\n n += 1\n candidate = `${parts.join('/') || 'file'}~${n}`\n }\n used.add(candidate)\n return candidate\n}\n\nfunction jsonCell(value: unknown): unknown {\n if (typeof value === 'bigint') return value.toString()\n if (value instanceof ArrayBuffer) value = new Uint8Array(value)\n if (value instanceof Uint8Array) {\n let bin = ''\n for (const b of value) bin += String.fromCharCode(b)\n return { $base64: btoa(bin) }\n }\n return value\n}\n\nexport function createExportEngine(options: ExportEngineOptions) {\n const { storage } = options\n const prefix = options.prefix ?? 'workspace-exports'\n const now = options.now ?? (() => Date.now())\n const archiveConcurrency = Math.max(1, Math.floor(options.archiveConcurrency ?? 4))\n\n /**\n * The units the next step runs, starting at `pending[from]`. Consecutive\n * archive units run together: each mostly waits on its box to resume and\n * stream its tar, so a workspace with dozens of sandboxes would otherwise\n * spend one box's wait per unit. A unit already attempted runs alone, so a\n * batch that died at a Worker limit cannot keep taking its neighbours with it.\n */\n function archiveBatch<T extends { unit: ExportUnit }>(pending: T[], from: number): T[] {\n const first = pending[from]!\n if (first.unit.kind !== 'archive' || first.unit.attempts > 0) return [first]\n const batch = [first]\n for (let i = from + 1; i < pending.length && batch.length < archiveConcurrency; i += 1) {\n const candidate = pending[i]!\n if (candidate.unit.kind !== 'archive' || candidate.unit.attempts > 0) break\n batch.push(candidate)\n }\n return batch\n }\n\n const base =(workspaceId: string, id: string) =>\n `${prefix}/${assertSafeKeySegment(workspaceId)}/${assertSafeKeySegment(id)}`\n const jobKey = (workspaceId: string, id: string) => `${base(workspaceId, id)}/job.json`\n /** The key a download signature covers. No object lives there; the zip is assembled per request. */\n const archiveKey = (workspaceId: string, id: string) => `${base(workspaceId, id)}/archive.zip`\n\n async function loadJob(workspaceId: string, id: string): Promise<{ job: ExportJob; etag: string } | null> {\n if (!/^[a-z0-9-]{8,64}$/.test(id)) return null\n const object = await storage.get(jobKey(workspaceId, id))\n if (!object) return null\n const job = JSON.parse(await new Response(object.body).text()) as ExportJob\n if (job.workspaceId !== workspaceId) return null\n return { job, etag: object.etag }\n }\n\n async function saveJob(job: ExportJob, etag?: string): Promise<string> {\n job.updatedAt = iso(now())\n const result = await storage.put(jobKey(job.workspaceId, job.id), new TextEncoder().encode(JSON.stringify(job)), {\n ifMatch: etag,\n })\n if (!result) throw new LeaseLost('export job changed underneath this request')\n return result.etag\n }\n\n async function writeEntry(\n keyBase: string,\n path: string,\n input: ReadableStream<Uint8Array>,\n compress: boolean,\n ): Promise<StoredEntry> {\n let crc = 0\n let size = 0\n const sha = createSha256()\n let stream = input.pipeThrough(\n new TransformStream<Uint8Array, Uint8Array>({\n async transform(chunk, controller) {\n crc = crc32Update(crc, chunk)\n size += chunk.length\n await sha.update(chunk)\n controller.enqueue(chunk)\n },\n }),\n )\n if (compress) stream = stream.pipeThrough(new CompressionStream('deflate-raw') as unknown as TransformStream<Uint8Array, Uint8Array>)\n\n const segments: StoredEntry['segments'] = []\n let pending: Uint8Array[] = []\n let pendingLength = 0\n let compressedSize = 0\n const flush = async () => {\n if (!pendingLength) return\n const key = `${keyBase}/${segments.length}`\n await storage.put(key, concatenate(pending, pendingLength))\n segments.push({ key, size: pendingLength })\n compressedSize += pendingLength\n pending = []\n pendingLength = 0\n }\n const reader = stream.getReader()\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n pending.push(value)\n pendingLength += value.length\n if (pendingLength >= SEGMENT_BYTES) await flush()\n }\n await flush()\n return {\n path,\n method: compress ? 8 : 0,\n crc32: crc,\n sha256: await sha.digestHex(),\n size,\n compressedSize,\n segments,\n }\n }\n\n function redactRow(row: ExportRow, omit: ReadonlySet<string>, scanner: SecretScanner): { row: ExportRow; count: number } {\n const out: ExportRow = {}\n let count = 0\n for (const [column, raw] of Object.entries(row)) {\n if (omit.has(column)) continue\n if (isSecretName(column)) {\n if (raw === null || raw === undefined || raw === '') out[column] = raw ?? null\n else {\n out[column] = REDACTED\n count += 1\n }\n continue\n }\n const result = scanner.redactValue(jsonCell(raw))\n out[column] = result.value\n count += result.count\n }\n return { row: out, count }\n }\n\n async function runUnit(\n job: ExportJob,\n unit: ExportUnit,\n index: number,\n source: ExportSource,\n scanner: SecretScanner,\n deadline: number,\n ) {\n const keyBase = `${base(job.workspaceId, job.id)}/u/${index}`\n if (unit.cursor === undefined) {\n unit.entries = []\n unit.redactions = 0\n }\n const encoder = new TextEncoder()\n\n if (source.kind === 'rows') {\n const omit = new Set(source.omitColumns ?? [])\n unit.expectedRows = source.expectedCount ? await source.expectedCount() : undefined\n let rows = 0\n const iterator = source.rows()[Symbol.asyncIterator]()\n const body = new ReadableStream<Uint8Array>({\n async pull(controller) {\n const { done, value } = await iterator.next()\n if (done) {\n controller.close()\n return\n }\n const page = Array.isArray(value) ? value : [value]\n let text = ''\n for (const row of page) {\n const redacted = redactRow(row, omit, scanner)\n unit.redactions += redacted.count\n text += `${JSON.stringify(redacted.row)}\\n`\n rows += 1\n }\n if (text) controller.enqueue(encoder.encode(text))\n },\n async cancel() {\n await iterator.return?.()\n },\n })\n unit.entries.push(await writeEntry(`${keyBase}/0`, `data/${source.name}.ndjson`, body, true))\n unit.rows = rows\n unit.status = 'done'\n return\n }\n\n if (source.kind === 'json') {\n const result = scanner.redactValue(await source.value())\n unit.redactions += result.count\n const text = `${JSON.stringify(result.value, null, 2)}\\n`\n unit.entries.push(await writeEntry(`${keyBase}/0`, `data/${source.name}.json`, toStream(text), true))\n unit.status = 'done'\n return\n }\n\n if (source.kind === 'files') {\n // Resumable: `cursor` counts files already listed, so a later request\n // skips them and keeps the entries they produced.\n const folder = `files/${source.name}/`\n const used = new Set(unit.entries.map((e) => e.path.slice(folder.length)))\n const start = unit.cursor ?? 0\n let seen = 0\n let written = 0\n for await (const file of source.files()) {\n if (seen < start) {\n seen += 1\n continue\n }\n if (written >= FILES_PER_REQUEST || now() > deadline) {\n unit.cursor = seen\n return\n }\n const body = await file.open()\n seen += 1\n if (body !== null) {\n const path = folder + safePath(file.path, used)\n const masked = toStream(body).pipeThrough(scanner.maskBytes((n) => (unit.redactions += n)))\n unit.entries.push(await writeEntry(`${keyBase}/${unit.entries.length}`, path, masked, false))\n written += 1\n }\n unit.cursor = seen\n }\n unit.cursor = undefined\n unit.files = unit.entries.length\n unit.status = unit.entries.length ? 'done' : 'empty'\n return\n }\n\n const archive = await source.open()\n if (!archive) {\n unit.status = 'empty'\n return\n }\n const stats = { files: 0, bytes: 0, blanked: [] as string[] }\n const tarGz = archive\n .pipeThrough(new DecompressionStream('gzip') as unknown as TransformStream<Uint8Array, Uint8Array>)\n .pipeThrough(createTarInspector(stats))\n .pipeThrough(scanner.maskBytes((n) => (unit.redactions += n)))\n .pipeThrough(new CompressionStream('gzip') as unknown as TransformStream<Uint8Array, Uint8Array>)\n unit.entries.push(await writeEntry(`${keyBase}/0`, `sandbox/${source.name}.tar.gz`, tarGz, false))\n unit.archive = stats\n unit.files = stats.files\n unit.status = 'done'\n }\n\n function manifest(job: ExportJob, notes: Record<string, unknown> | undefined) {\n const classes: Record<string, string[]> = {}\n for (const unit of job.units) {\n for (const entry of unit.entries) (classes[unit.dataClass] ??= []).push(entry.path)\n }\n return {\n schema: MANIFEST_SCHEMA,\n app: options.app,\n workspaceId: job.workspaceId,\n exportId: job.id,\n requestedBy: job.requestedBy,\n createdAt: job.createdAt,\n completedAt: job.completedAt,\n secretPolicy:\n 'Credential columns and JSON keys are replaced with \"[redacted]\". Credential-shaped values and the product\\'s own keys are masked in rows and files. Credential files inside sandbox archives are overwritten with \"*\". Connections are exported as metadata only.',\n totals: {\n units: job.units.length,\n files: job.units.reduce((n, u) => n + u.entries.length, 0),\n rows: job.units.reduce((n, u) => n + (u.rows ?? 0), 0),\n bytes: job.units.reduce((n, u) => n + u.entries.reduce((m, e) => m + e.size, 0), 0),\n redactions: job.units.reduce((n, u) => n + u.redactions, 0),\n },\n classes,\n sources: job.units.map((u) => ({\n name: u.name,\n kind: u.kind,\n dataClass: u.dataClass,\n description: u.description,\n status: u.status,\n rows: u.rows,\n expectedRows: u.expectedRows,\n files: u.files,\n archive: u.archive,\n redactions: u.redactions,\n })),\n files: job.units.flatMap((u) =>\n u.entries.map((e) => ({ path: e.path, size: e.size, sha256: e.sha256, crc32: e.crc32.toString(16).padStart(8, '0') })),\n ),\n notes,\n }\n }\n\n function readme(job: ExportJob): string {\n return [\n `${options.app} workspace export`,\n '',\n `Workspace: ${job.workspaceId}`,\n `Export: ${job.id}`,\n `Created: ${job.createdAt}`,\n '',\n 'manifest.json what this archive contains: every file with its size and SHA-256, row counts per source, and the redaction policy',\n 'data/*.ndjson one JSON object per line, one file per table or record type',\n 'data/*.json single documents',\n 'files/<source>/ uploaded and generated files, at their original paths',\n 'sandbox/*.tar.gz the agent workspace filesystem; extract with `tar -xzf`',\n '',\n 'Verify a file: `shasum -a 256 <path>` and compare with manifest.json.',\n 'Secrets are never exported. Credential fields read \"[redacted]\".',\n '',\n ].join('\\n')\n }\n\n async function finalize(job: ExportJob, plan: ExportPlan, scanner: SecretScanner) {\n job.completedAt = iso(now())\n const notes = plan.notes ? (scanner.redactValue(plan.notes).value as Record<string, unknown>) : undefined\n const keyBase = `${base(job.workspaceId, job.id)}/meta`\n const manifestText = `${JSON.stringify(manifest(job, notes), null, 2)}\\n`\n job.meta = [\n await writeEntry(`${keyBase}/0`, 'manifest.json', toStream(manifestText), true),\n await writeEntry(`${keyBase}/1`, 'README.txt', toStream(readme(job)), true),\n ]\n job.status = 'complete'\n }\n\n return {\n archiveKey,\n\n async list(workspaceId: string): Promise<ExportJob[]> {\n const ids = new Set<string>()\n let cursor: string | undefined\n do {\n const page = await storage.list(`${prefix}/${assertSafeKeySegment(workspaceId)}/`, cursor)\n for (const key of page.keys) if (key.endsWith('/job.json')) ids.add(key.split('/').at(-2)!)\n cursor = page.cursor\n } while (cursor)\n const jobs: ExportJob[] = []\n for (const id of [...ids].sort().reverse().slice(0, 10)) {\n const loaded = await loadJob(workspaceId, id)\n if (loaded) jobs.push(loaded.job)\n }\n return jobs\n },\n\n async get(workspaceId: string, id: string): Promise<ExportJob | null> {\n return (await loadJob(workspaceId, id))?.job ?? null\n },\n\n /** Start an export, or return the one already running for this workspace. */\n async start(workspaceId: string, requestedBy: string): Promise<ExportJob> {\n const existing = (await this.list(workspaceId)).find(\n (job) => job.status === 'running' && now() - Date.parse(job.updatedAt) < 15 * 60_000,\n )\n if (existing) return existing\n const plan = await options.plan({ workspaceId })\n const names = new Set<string>()\n for (const source of plan.sources) {\n if (!SOURCE_NAME.test(source.name)) throw new Error(`workspace-export: invalid source name \"${source.name}\"`)\n if (names.has(source.name)) throw new Error(`workspace-export: duplicate source name \"${source.name}\"`)\n names.add(source.name)\n }\n const created = now()\n const job: ExportJob = {\n v: 1,\n id: `${created.toString(36)}-${crypto.randomUUID().slice(0, 8)}`,\n workspaceId,\n requestedBy,\n createdAt: iso(created),\n updatedAt: iso(created),\n status: 'running',\n units: plan.sources.map((s) => ({\n name: s.name,\n kind: s.kind,\n dataClass: s.dataClass,\n description: s.description,\n status: 'pending',\n attempts: 0,\n entries: [],\n redactions: 0,\n })),\n }\n await saveJob(job)\n return job\n },\n\n /**\n * Run pending units until `budgetMs` passes. A unit that starts always\n * finishes, so one call can run longer than the budget. Returns the job as\n * stored; another request holding the lease leaves it unchanged.\n */\n async advance(workspaceId: string, id: string, budgetMs = 20_000): Promise<ExportJob | null> {\n const loaded = await loadJob(workspaceId, id)\n if (!loaded) return null\n const { job } = loaded\n if (job.status !== 'running') return job\n if (job.lease && job.lease.until > now()) return job\n const deadline = now() + budgetMs\n let etag = loaded.etag\n // Saves are serialized: the heartbeat and the unit loop share one etag.\n let saving: Promise<void> = Promise.resolve()\n const save = () => {\n saving = saving.then(async () => {\n if (job.lease) job.lease.until = now() + LEASE_MS\n etag = await saveJob(job, etag)\n })\n return saving\n }\n let heartbeat: ReturnType<typeof setInterval> | undefined\n try {\n job.lease = { id: crypto.randomUUID(), until: now() + LEASE_MS }\n await save()\n heartbeat = setInterval(() => {\n save().catch(() => {})\n }, HEARTBEAT_MS)\n const plan = await options.plan({ workspaceId })\n const scanner = createSecretScanner({ knownSecrets: (await options.knownSecrets?.({ workspaceId })) ?? [] })\n const sources = new Map(plan.sources.map((s) => [s.name, s]))\n const pending = job.units.flatMap((unit, index) => (unit.status === 'pending' ? [{ unit, index }] : []))\n let next = 0\n while (next < pending.length) {\n if (now() > deadline) break\n const batch = archiveBatch(pending, next)\n next += batch.length\n const exhausted = batch.find(({ unit }) => unit.attempts >= MAX_ATTEMPTS)\n if (exhausted) {\n // Earlier requests died inside this unit without recording an outcome,\n // most often at the Worker CPU limit.\n const { unit } = exhausted\n unit.status = 'failed'\n unit.error ??= 'the request exporting this source ended before it finished'\n job.status = 'failed'\n job.error = `${unit.name}: ${unit.error}`\n await save()\n break\n }\n // Recorded before running, so a request that dies mid-unit still counts.\n for (const { unit } of batch) unit.attempts += 1\n await save()\n const failed = await Promise.all(\n batch.map(async ({ unit, index }) => {\n const source = sources.get(unit.name)\n try {\n if (!source || source.kind !== unit.kind) throw new Error('source is no longer available')\n await runUnit(job, unit, index, source, scanner, deadline)\n unit.error = undefined\n return false\n } catch (err) {\n unit.error = errorText(scanner, err)\n // A files unit keeps what it already wrote and resumes at its cursor.\n if (unit.cursor === undefined) unit.entries = []\n if (unit.attempts >= MAX_ATTEMPTS) unit.status = 'failed'\n return true\n }\n }),\n )\n const dead = batch.find(({ unit }) => unit.status === 'failed')\n if (dead) {\n job.status = 'failed'\n job.error = `${dead.unit.name}: ${dead.unit.error}`\n }\n if (failed.includes(true)) {\n await save()\n break\n }\n const { unit } = batch[0]!\n if (unit.status === 'pending') {\n // Progress was made; continue this unit in the next request.\n unit.attempts = 0\n await save()\n break\n }\n await save()\n }\n if (job.status === 'running' && job.units.every((u) => u.status === 'done' || u.status === 'empty')) {\n await finalize(job, plan, scanner)\n }\n clearInterval(heartbeat)\n await saving.catch(() => {})\n job.lease = undefined\n await saveJob(job, etag)\n return job\n } catch (err) {\n if (err instanceof LeaseLost) return (await loadJob(workspaceId, id))?.job ?? null\n // A request that failed outside a unit (a storage or planning error) hands\n // the lease back, so the panel's retry continues now instead of waiting it out.\n // Only the stored job is touched, never this request's half-applied copy.\n clearInterval(heartbeat)\n await saving.catch(() => {})\n const leaseId = job.lease?.id\n const stored = leaseId ? await loadJob(workspaceId, id).catch(() => null) : null\n if (stored && stored.job.lease?.id === leaseId) {\n stored.job.lease = undefined\n await saveJob(stored.job, stored.etag).catch(() => {})\n }\n throw err\n } finally {\n clearInterval(heartbeat)\n }\n },\n\n progress(job: ExportJob): Omit<ExportProgress, 'downloadUrl' | 'downloadExpiresAt'> {\n const bytesOf = (u: ExportUnit) => u.entries.reduce((n, e) => n + e.size, 0)\n return {\n id: job.id,\n status: job.status,\n createdAt: job.createdAt,\n completedAt: job.completedAt,\n error: job.error,\n unitsTotal: job.units.length,\n unitsDone: job.units.filter((u) => u.status !== 'pending').length,\n current: job.status === 'running' ? job.units.find((u) => u.status === 'pending')?.name : undefined,\n bytes: job.units.reduce((n, u) => n + bytesOf(u), 0),\n units: job.units.map((u) => ({\n name: u.name,\n dataClass: u.dataClass,\n status: u.status,\n rows: u.rows,\n files: u.files,\n bytes: bytesOf(u),\n error: u.error,\n })),\n }\n },\n\n /** The finished archive as one stream with an exact length. */\n zip(job: ExportJob): { length: number; stream: ReadableStream<Uint8Array>; filename: string } {\n if (job.status !== 'complete' || !job.meta) throw new Error('workspace-export: export is not complete')\n const modifiedAt = new Date(job.completedAt ?? job.createdAt)\n const entries: ZipEntrySpec[] = [...job.meta, ...job.units.flatMap((u) => u.entries)].map((entry) => ({\n name: entry.path,\n method: entry.method,\n crc32: entry.crc32,\n compressedSize: entry.compressedSize,\n uncompressedSize: entry.size,\n modifiedAt,\n open: async () => {\n let index = 0\n let reader: ReadableStreamDefaultReader<Uint8Array> | null = null\n return new ReadableStream<Uint8Array>({\n async pull(controller) {\n for (;;) {\n if (!reader) {\n const segment = entry.segments[index]\n if (!segment) {\n controller.close()\n return\n }\n index += 1\n const object = await storage.get(segment.key)\n if (!object || object.size !== segment.size) {\n controller.error(new Error(`workspace-export: segment ${segment.key} is missing or changed`))\n return\n }\n reader = object.body.getReader()\n }\n const { done, value } = await reader.read()\n if (!done) {\n controller.enqueue(value)\n return\n }\n reader = null\n }\n },\n async cancel(reason) {\n await reader?.cancel(reason)\n },\n })\n },\n }))\n const { length, stream } = createZipStream(entries)\n const date = (job.completedAt ?? job.createdAt).slice(0, 10)\n return { length, stream, filename: `${options.app}-workspace-export-${date}.zip` }\n },\n\n /** Delete exports older than `retentionMs`, and any export by id when given. */\n async prune(workspaceId: string, retentionMs: number, onlyId?: string): Promise<number> {\n const cutoff = now() - retentionMs\n const doomed: string[] = []\n let cursor: string | undefined\n const root = `${prefix}/${assertSafeKeySegment(workspaceId)}/`\n do {\n const page = await storage.list(root, cursor)\n for (const key of page.keys) {\n const id = key.slice(root.length).split('/')[0] ?? ''\n const created = Number.parseInt(id.split('-')[0] ?? '', 36)\n if (onlyId ? id === onlyId : Number.isFinite(created) && created < cutoff) doomed.push(key)\n }\n cursor = page.cursor\n } while (cursor)\n await storage.delete(doomed)\n return doomed.length\n },\n }\n}\n\nexport type ExportEngine = ReturnType<typeof createExportEngine>\n","/**\n * HTTP surface for workspace exports, mounted by a product under one path such\n * as `/api/workspaces/:id/exports`.\n *\n * GET {mount} list recent exports owner\n * POST {mount} start (or resume) an export owner\n * GET {mount}/:id progress + signed link owner\n * POST {mount}/:id/advance do the next ~20 s of work owner\n * DELETE {mount}/:id delete a finished export owner\n * GET {mount}/:id/download the zip signed link\n *\n * Authorization fails closed: no principal, a non-owner role, or an authorizer\n * that throws all refuse. Writes also require a same-origin request. The\n * download link is an HMAC-signed, short-lived URL bound to one workspace and\n * one export, so a browser can fetch it without a session header.\n */\n\nimport { signObjectUrl, verifyObjectUrl } from '../object-store'\nimport { createExportEngine, type ExportEngineOptions } from './engine'\nimport { createSecretScanner } from './secrets'\nimport type { ExportJob, ExportPrincipal, ExportProgress } from './types'\n\nexport interface WorkspaceExportOptions extends ExportEngineOptions {\n /** Resolve the caller from the authenticated session. Return `null` when unauthenticated or not a member. */\n authorize(args: { request: Request; workspaceId: string }): Promise<ExportPrincipal | null>\n /** HMAC secret for download links. An empty secret refuses every download. */\n signingSecret: string\n /** Download link lifetime. Default 15 minutes. */\n linkTtlMs?: number\n /** Exports are deleted after this long. They hold decrypted data, so keep it short. Default 24 hours. */\n retentionMs?: number\n /** Work per advance request. Default 20 seconds. */\n advanceBudgetMs?: number\n}\n\nconst NO_STORE = { 'Cache-Control': 'private, no-store' }\n\nfunction json(body: unknown, status = 200): Response {\n return Response.json(body, { status, headers: NO_STORE })\n}\n\nfunction refuse(status: number, code: string, message: string): Response {\n return json({ error: { code, message } }, status)\n}\n\nfunction sameOrigin(request: Request): boolean {\n const site = request.headers.get('Sec-Fetch-Site')\n if (site && site !== 'same-origin' && site !== 'none') return false\n const origin = request.headers.get('Origin')\n if (origin && origin !== new URL(request.url).origin) return false\n return true\n}\n\nexport function createWorkspaceExport(options: WorkspaceExportOptions) {\n const engine = createExportEngine(options)\n const linkTtlMs = options.linkTtlMs ?? 15 * 60_000\n const retentionMs = options.retentionMs ?? 24 * 60 * 60_000\n const now = options.now ?? (() => Date.now())\n\n async function withProgress(job: ExportJob, mount: string): Promise<ExportProgress> {\n const progress: ExportProgress = engine.progress(job)\n if (job.status === 'complete' && options.signingSecret) {\n const exp = now() + linkTtlMs\n const query = await signObjectUrl({ key: engine.archiveKey(job.workspaceId, job.id), exp, secret: options.signingSecret })\n progress.downloadUrl = `${mount}/${job.id}/download${query}`\n progress.downloadExpiresAt = new Date(exp).toISOString()\n }\n return progress\n }\n\n async function owner(request: Request, workspaceId: string): Promise<ExportPrincipal | Response> {\n let principal: ExportPrincipal | null\n try {\n principal = await options.authorize({ request, workspaceId })\n } catch {\n return refuse(503, 'authorization_unavailable', 'Could not check workspace access')\n }\n if (!principal) return refuse(403, 'forbidden', 'Workspace owner access is required')\n if (principal.role !== 'owner') return refuse(403, 'owner_required', 'Only the workspace owner can export its data')\n return principal\n }\n\n async function download(request: Request, workspaceId: string, id: string): Promise<Response> {\n const verified = await verifyObjectUrl(request, { secret: options.signingSecret })\n if (!verified.ok || verified.key !== engine.archiveKey(workspaceId, id)) {\n return refuse(403, 'link_invalid', 'This download link is invalid or has expired')\n }\n const job = await engine.get(workspaceId, id)\n if (!job || job.status !== 'complete') return refuse(404, 'not_found', 'Export not found')\n const { length, stream, filename } = engine.zip(job)\n return new Response(stream, {\n headers: {\n ...NO_STORE,\n 'Content-Type': 'application/zip',\n 'Content-Length': String(length),\n 'Content-Disposition': `attachment; filename=\"${filename}\"`,\n 'X-Content-Type-Options': 'nosniff',\n },\n })\n }\n\n /**\n * Handle one request. `path` is the part after the mount, without a leading\n * slash: `''`, `'<id>'`, `'<id>/advance'` or `'<id>/download'`.\n */\n async function route(request: Request, args: { workspaceId: string; path: string }): Promise<Response> {\n const { workspaceId } = args\n const path = args.path.replace(/^\\/+|\\/+$/g, '')\n const url = new URL(request.url)\n const mount = path ? url.pathname.slice(0, url.pathname.length - path.length).replace(/\\/+$/, '') : url.pathname.replace(/\\/+$/, '')\n const [id, action, extra] = path ? path.split('/') : []\n const method = request.method.toUpperCase()\n if (extra !== undefined) return refuse(404, 'not_found', 'Not found')\n\n try {\n if (id && action === 'download') {\n if (method !== 'GET') return refuse(405, 'method_not_allowed', 'Use GET')\n return await download(request, workspaceId, id)\n }\n\n if (method !== 'GET' && !sameOrigin(request)) return refuse(403, 'cross_origin', 'Cross-origin request refused')\n const principal = await owner(request, workspaceId)\n if (principal instanceof Response) return principal\n\n if (!id) {\n if (method === 'GET') {\n const jobs = await engine.list(workspaceId)\n return json({ exports: await Promise.all(jobs.map((job) => withProgress(job, mount))) })\n }\n if (method === 'POST') {\n await engine.prune(workspaceId, retentionMs)\n const job = await engine.start(workspaceId, principal.userId)\n return json(await withProgress(job, mount), 202)\n }\n return refuse(405, 'method_not_allowed', 'Use GET or POST')\n }\n\n if (!action) {\n if (method === 'GET') {\n const job = await engine.get(workspaceId, id)\n return job ? json(await withProgress(job, mount)) : refuse(404, 'not_found', 'Export not found')\n }\n if (method === 'DELETE') {\n const job = await engine.get(workspaceId, id)\n if (!job) return refuse(404, 'not_found', 'Export not found')\n if (job.status === 'running') return refuse(409, 'running', 'Wait for the export to finish before deleting it')\n await engine.prune(workspaceId, 0, id)\n return json({ deleted: id })\n }\n return refuse(405, 'method_not_allowed', 'Use GET or DELETE')\n }\n\n if (action === 'advance') {\n if (method !== 'POST') return refuse(405, 'method_not_allowed', 'Use POST')\n const job = await engine.advance(workspaceId, id, options.advanceBudgetMs)\n return job ? json(await withProgress(job, mount)) : refuse(404, 'not_found', 'Export not found')\n }\n return refuse(404, 'not_found', 'Not found')\n } catch (err) {\n // Error text can carry data from a source, so the response stays generic and\n // the operator log gets the text with credentials and known secrets masked.\n const known = await Promise.resolve(options.knownSecrets?.({ workspaceId })).catch(() => undefined)\n const text = err instanceof Error ? err.message : String(err)\n console.error(`workspace-export: ${method} ${path || '/'} failed: ${createSecretScanner({ knownSecrets: known ?? [] }).maskText(text).text.slice(0, 300)}`)\n return refuse(500, 'export_error', 'The export request failed')\n }\n }\n\n return { route, engine }\n}\n","/**\n * Where an export keeps its pieces until download. Each entry is written as\n * bounded segments so nothing larger than one segment is ever held in memory,\n * and the job record is updated with a compare-and-swap so two tabs advancing\n * the same export cannot both run it.\n */\n\nexport interface ExportStorage {\n /** `ifMatch` makes the write conditional; a lost race returns `null`. */\n put(key: string, body: Uint8Array, options?: { ifMatch?: string }): Promise<{ etag: string } | null>\n get(key: string): Promise<{ body: ReadableStream<Uint8Array>; size: number; etag: string } | null>\n list(prefix: string, cursor?: string): Promise<{ keys: string[]; cursor?: string }>\n delete(keys: string[]): Promise<void>\n}\n\n/** The slice of Cloudflare's `R2Bucket` used here; a real binding satisfies it. */\nexport interface R2ExportBucket {\n put(\n key: string,\n value: Uint8Array,\n options?: { onlyIf?: { etagMatches?: string }; httpMetadata?: { contentType?: string } },\n ): Promise<{ etag: string } | null>\n get(key: string): Promise<{ body: ReadableStream<Uint8Array>; size: number; etag: string } | null>\n list(options: { prefix: string; cursor?: string; limit?: number }): Promise<{\n objects: { key: string }[]\n truncated: boolean\n cursor?: string\n }>\n delete(keys: string | string[]): Promise<void>\n}\n\nexport function createR2ExportStorage(bucket: R2ExportBucket): ExportStorage {\n return {\n async put(key, body, options) {\n const result = await bucket.put(key, body, options?.ifMatch ? { onlyIf: { etagMatches: options.ifMatch } } : undefined)\n return result ? { etag: result.etag } : null\n },\n async get(key) {\n const object = await bucket.get(key)\n return object ? { body: object.body, size: object.size, etag: object.etag } : null\n },\n async list(prefix, cursor) {\n const page = await bucket.list({ prefix, cursor, limit: 1000 })\n return { keys: page.objects.map((o) => o.key), cursor: page.truncated ? page.cursor : undefined }\n },\n async delete(keys) {\n for (let i = 0; i < keys.length; i += 1000) await bucket.delete(keys.slice(i, i + 1000))\n },\n }\n}\n\n/** An in-memory store for tests and local runs. */\nexport function createMemoryExportStorage(): ExportStorage & { objects: Map<string, Uint8Array> } {\n const objects = new Map<string, Uint8Array>()\n const etags = new Map<string, string>()\n let version = 0\n return {\n objects,\n async put(key, body, options) {\n if (options?.ifMatch && etags.get(key) !== options.ifMatch) return null\n version += 1\n objects.set(key, body.slice())\n etags.set(key, String(version))\n return { etag: String(version) }\n },\n async get(key) {\n const bytes = objects.get(key)\n if (!bytes) return null\n return { body: new Blob([bytes as BlobPart]).stream() as ReadableStream<Uint8Array>, size: bytes.length, etag: etags.get(key)! }\n },\n async list(prefix) {\n return { keys: [...objects.keys()].filter((k) => k.startsWith(prefix)).sort() }\n },\n async delete(keys) {\n for (const key of keys) {\n objects.delete(key)\n etags.delete(key)\n }\n },\n }\n}\n","/**\n * Export every D1 (SQLite) table that belongs to a workspace, without a\n * hand-kept list that silently falls behind new migrations.\n *\n * Tables are discovered from the schema. A table with one of the workspace\n * columns is exported by that column; a table reached through a parent is\n * exported by the `scoped` SQL the product supplies. Every other table is\n * listed in the coverage report as `excluded` (with the product's reason) or\n * `unscoped`, so a reviewer sees exactly what the export leaves out.\n */\n\nimport type { ExportDataClass, ExportRow, ExportRowsSource } from './types'\n\n/** The slice of Cloudflare's `D1Database` used here. */\nexport interface D1ExportDatabase {\n prepare(sql: string): {\n bind(...values: unknown[]): {\n all<T = Record<string, unknown>>(): Promise<{ results: T[] }>\n }\n all<T = Record<string, unknown>>(): Promise<{ results: T[] }>\n }\n}\n\nexport interface D1TableCoverage {\n table: string\n status: 'exported' | 'excluded' | 'unscoped'\n /** The column or SQL used, or why the table is left out. */\n detail?: string\n}\n\nexport interface D1WorkspaceTablesOptions {\n db: D1ExportDatabase\n workspaceId: string\n /** Columns that hold the workspace id, checked in order, e.g. `['workspace_id']`. */\n workspaceColumns: readonly string[]\n /**\n * Tables keyed through a parent. The value is a WHERE clause; every `?` binds\n * the workspace id. Example: `{ message: 'thread_id IN (SELECT id FROM thread WHERE workspace_id = ?)' }`.\n */\n scoped?: Readonly<Record<string, string>>\n /** Tables left out on purpose, with the reason recorded in coverage. */\n exclude?: Readonly<Record<string, string>>\n /** Per-table columns to drop beyond the automatic credential policy. */\n omitColumns?: Readonly<Record<string, readonly string[]>>\n /** Per-table row rewrite, e.g. to decrypt a product-encrypted column. */\n transform?: Readonly<Record<string, (row: ExportRow) => ExportRow | Promise<ExportRow>>>\n /** Data class per table. Defaults to `records`. */\n classify?: (table: string) => ExportDataClass\n /** Rows per query. Default 500. */\n pageSize?: number\n}\n\nconst INTERNAL = /^(sqlite_|_cf_|d1_|__drizzle|_litestream)/\n\nfunction quote(identifier: string): string {\n return `\"${identifier.replace(/\"/g, '\"\"')}\"`\n}\n\nfunction sourceName(table: string): string {\n return table.toLowerCase().replace(/[^a-z0-9_.-]/g, '_').replace(/^[^a-z0-9]+/, '') || 'table'\n}\n\n/** Discover workspace tables. Returns row sources and a coverage report for the manifest. */\nexport async function d1WorkspaceTables(\n options: D1WorkspaceTablesOptions,\n): Promise<{ sources: ExportRowsSource[]; coverage: D1TableCoverage[] }> {\n const { db, workspaceId } = options\n const pageSize = options.pageSize ?? 500\n const tables = (\n await db.prepare(`SELECT name, sql FROM sqlite_master WHERE type = 'table' ORDER BY name`).all<{ name: string; sql: string | null }>()\n ).results.filter((t) => !INTERNAL.test(t.name))\n\n const sources: ExportRowsSource[] = []\n const coverage: D1TableCoverage[] = []\n for (const { name: table, sql } of tables) {\n const excluded = options.exclude?.[table]\n if (excluded !== undefined) {\n coverage.push({ table, status: 'excluded', detail: excluded })\n continue\n }\n let where = options.scoped?.[table]\n let detail = where\n if (!where) {\n const columns = (await db.prepare(`PRAGMA table_info(${quote(table)})`).all<{ name: string }>()).results.map((c) => c.name)\n const column = options.workspaceColumns.find((c) => columns.includes(c))\n if (!column) {\n coverage.push({ table, status: 'unscoped' })\n continue\n }\n where = `${quote(column)} = ?`\n detail = column\n }\n coverage.push({ table, status: 'exported', detail })\n\n const binds = Array.from({ length: (where.match(/\\?/g) ?? []).length }, () => workspaceId)\n const hasRowid = !/WITHOUT\\s+ROWID/i.test(sql ?? '')\n const transform = options.transform?.[table]\n sources.push({\n kind: 'rows',\n name: `db.${sourceName(table)}`,\n dataClass: options.classify?.(table) ?? 'records',\n description: `D1 table ${table} where ${detail}`,\n omitColumns: options.omitColumns?.[table],\n async expectedCount() {\n const result = await db.prepare(`SELECT COUNT(*) AS n FROM ${quote(table)} WHERE ${where}`).bind(...binds).all<{ n: number }>()\n return Number(result.results[0]?.n ?? 0)\n },\n async *rows() {\n // Keyset pagination on rowid keeps each page an index seek; tables\n // without a rowid fall back to OFFSET.\n let after = Number.MIN_SAFE_INTEGER\n let offset = 0\n for (;;) {\n const page = hasRowid\n ? await db\n .prepare(`SELECT rowid AS \"__export_rowid\", * FROM ${quote(table)} WHERE (${where}) AND rowid > ? ORDER BY rowid LIMIT ?`)\n .bind(...binds, after, pageSize)\n .all<ExportRow>()\n : await db\n .prepare(`SELECT * FROM ${quote(table)} WHERE ${where} LIMIT ? OFFSET ?`)\n .bind(...binds, pageSize, offset)\n .all<ExportRow>()\n const rows = page.results\n if (!rows.length) return\n const out: ExportRow[] = []\n for (const row of rows) {\n if (hasRowid) {\n after = Number(row.__export_rowid)\n delete row.__export_rowid\n }\n out.push(transform ? await transform(row) : row)\n }\n offset += rows.length\n yield out\n if (rows.length < pageSize) return\n }\n },\n })\n }\n return { sources, coverage }\n}\n","/** Ready-made sources for the stores agent apps use: R2 prefixes and KV prefixes. */\n\nimport type { ExportDataClass, ExportFile, ExportFilesSource } from './types'\n\n/** The slice of `R2Bucket` used to export objects. */\nexport interface R2FilesBucket {\n list(options: { prefix: string; cursor?: string; limit?: number }): Promise<{\n objects: { key: string; size: number }[]\n truncated: boolean\n cursor?: string\n }>\n get(key: string): Promise<{ body: ReadableStream<Uint8Array> } | null>\n}\n\n/**\n * Every object under the given prefixes. The archive path is the key with its\n * prefix removed, so `ws-1/guest/a.jpg` under prefix `ws-1/` lands at\n * `files/<name>/guest/a.jpg`. Prefixes must end at a workspace boundary\n * (`ws-1/`, not `ws-1`) or another workspace's objects would match.\n */\nexport function r2Files(args: {\n name: string\n dataClass: ExportDataClass\n bucket: R2FilesBucket\n prefixes: readonly string[]\n /** Optionally rewrite bytes, e.g. to decrypt objects the product encrypted. */\n read?: (key: string, body: ReadableStream<Uint8Array>) => Promise<ReadableStream<Uint8Array> | Uint8Array | string | null>\n description?: string\n}): ExportFilesSource {\n for (const prefix of args.prefixes) {\n if (!prefix.endsWith('/')) throw new Error(`workspace-export: R2 prefix \"${prefix}\" must end with \"/\"`)\n }\n return {\n kind: 'files',\n name: args.name,\n dataClass: args.dataClass,\n description: args.description ?? `R2 objects under ${args.prefixes.join(', ')}`,\n async *files(): AsyncIterable<ExportFile> {\n for (const prefix of args.prefixes) {\n let cursor: string | undefined\n do {\n const page = await args.bucket.list({ prefix, cursor, limit: 1000 })\n for (const object of page.objects) {\n yield {\n path: args.prefixes.length > 1 ? object.key : object.key.slice(prefix.length),\n async open() {\n const found = await args.bucket.get(object.key)\n if (!found) return null\n return args.read ? args.read(object.key, found.body) : found.body\n },\n }\n }\n cursor = page.truncated ? page.cursor : undefined\n } while (cursor)\n }\n },\n }\n}\n\n/** The slice of `KVNamespace` used to export values. */\nexport interface KVFilesNamespace {\n list(options: { prefix: string; cursor?: string; limit?: number }): Promise<{\n keys: { name: string }[]\n list_complete: boolean\n cursor?: string\n }>\n get(key: string, type: 'stream'): Promise<ReadableStream<Uint8Array> | null>\n}\n\n/** Every KV value under a prefix, written as a file at the key minus the prefix. */\nexport function kvFiles(args: {\n name: string\n dataClass: ExportDataClass\n kv: KVFilesNamespace\n prefix: string\n read?: (key: string, body: ReadableStream<Uint8Array>) => Promise<ReadableStream<Uint8Array> | Uint8Array | string | null>\n description?: string\n}): ExportFilesSource {\n return {\n kind: 'files',\n name: args.name,\n dataClass: args.dataClass,\n description: args.description ?? `KV values under ${args.prefix}`,\n async *files(): AsyncIterable<ExportFile> {\n let cursor: string | undefined\n do {\n const page = await args.kv.list({ prefix: args.prefix, cursor, limit: 1000 })\n for (const key of page.keys) {\n yield {\n path: key.name.slice(args.prefix.length),\n async open() {\n const body = await args.kv.get(key.name, 'stream')\n if (!body) return null\n return args.read ? args.read(key.name, body) : body\n },\n }\n }\n cursor = page.list_complete ? undefined : page.cursor\n } while (cursor)\n },\n }\n}\n","/**\n * The sandbox-archive source every app needs, so no product hand-rolls box\n * lifecycle around `fs.openArchive`.\n *\n * `openArchive` refuses a box that is not running. A stopped box is resumed for\n * the export and stopped again once its archive has been read, so exporting\n * neither fails on an idle workspace nor leaves the owner paying for a box they\n * had stopped. A box that no longer exists exports nothing.\n */\n\nimport type { ExportArchiveSource, ExportDataClass } from './types'\n\n/** The slice of the Sandbox SDK's `SandboxInstance` this source uses. */\nexport interface ArchivableBox {\n readonly status: string\n resume(): Promise<void>\n stop?(): Promise<void>\n waitFor(status: 'running', options?: { timeoutMs?: number }): Promise<void>\n fs: { openArchive(dir: string, options?: { signal?: AbortSignal }): Promise<ReadableStream<Uint8Array>> }\n}\n\nconst GONE = new Set(['deleted', 'expired', 'failed'])\n\n/**\n * One sandbox's filesystem as `sandbox/<name>.tar.gz`. `getBox` returns the\n * SDK instance (`client.get(id)`), or `null` when the box is gone.\n */\nexport function sandboxArchive(args: {\n name: string\n getBox(): Promise<ArchivableBox | null>\n /** Directory to archive, relative to the box workspace. Default `.`. */\n dir?: string\n dataClass?: ExportDataClass\n description?: string\n /** How long to wait for a resumed box. Default 120 s. */\n resumeTimeoutMs?: number\n}): ExportArchiveSource {\n return {\n kind: 'archive',\n name: args.name,\n dataClass: args.dataClass ?? 'sandbox',\n description: args.description,\n async open() {\n const box = await args.getBox()\n if (!box || GONE.has(box.status)) return null\n const wasStopped = box.status === 'stopped'\n if (wasStopped) await box.resume()\n if (box.status !== 'running' || wasStopped) await box.waitFor('running', { timeoutMs: args.resumeTimeoutMs ?? 120_000 })\n const archive = await box.fs.openArchive(args.dir ?? '.')\n if (!wasStopped || !box.stop) return archive\n // Put the box back the way the owner left it once the archive is read.\n const restore = () => box.stop!().catch(() => {})\n return archive.pipeThrough(\n new TransformStream<Uint8Array, Uint8Array>({\n flush: () => restore(),\n }),\n )\n },\n }\n}\n"],"mappings":";;;;;;;;AAQA,IAAM,aAAa,MAAM;AACvB,QAAM,QAAQ,IAAI,YAAY,GAAG;AACjC,WAAS,IAAI,GAAG,IAAI,KAAK,KAAK,GAAG;AAC/B,QAAI,IAAI;AACR,aAAS,IAAI,GAAG,IAAI,GAAG,KAAK,EAAG,KAAI,IAAI,IAAI,aAAc,MAAM,IAAK,MAAM;AAC1E,UAAM,CAAC,IAAI,MAAM;AAAA,EACnB;AACA,SAAO;AACT,GAAG;AAGI,SAAS,YAAY,KAAa,OAA2B;AAClE,MAAI,KAAK,MAAM,gBAAgB;AAC/B,WAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK,EAAG,MAAK,WAAW,IAAI,MAAM,CAAC,KAAM,GAAI,IAAM,MAAM,OAAQ;AACnG,UAAQ,IAAI,gBAAgB;AAC9B;AAWA,SAAS,MAAM,OAA2B;AACxC,MAAI,MAAM;AACV,aAAW,KAAK,MAAO,QAAO,EAAE,SAAS,EAAE,EAAE,SAAS,GAAG,GAAG;AAC5D,SAAO;AACT;AAGO,SAAS,eAA6B;AAC3C,QAAM,eAAgB,WAAW,OAE9B;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AAW,KAAK,mBAAmB,KAAQ,CAAC;AACvH,YAAM,UAAU,MAAM,IAAI,GAAG,YAAY,KAAK,OAAO,GAAG;AACxD,UAAI,CAAC,cAAc,CAAC,IAAI,KAAM,QAAO;AAErC,YAAM,UAAU,MAAM,IAAI,KAAM,EAAE,MAAM,MAAM;AAAA,MAAC,CAAC;AAChD,aAAO,QAAQ;AAAA,QACb,IAAI,gBAAwC;AAAA,UAC1C,OAAO,MAAM,QAAQ;AAAA,QACvB,CAAC;AAAA,MACH;AAAA,IACF;AAAA,EACF;AACF;","names":["a","b","out","take","job","unit"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/agent-app",
3
- "version": "0.60.84",
3
+ "version": "0.60.86",
4
4
  "packageManager": "pnpm@11.24.0",
5
5
  "description": "Build agent applications with typed chat, tools, sandboxes, integrations, billing, and evaluation.",
6
6
  "keywords": [