@tangle-network/agent-app 0.63.18 → 0.63.19
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent-profiles/d1.js +2 -2
- package/dist/agent-profiles/index.js +2 -2
- package/dist/agent-profiles/switch.d.ts +1 -1
- package/dist/agent-profiles/switch.js +1 -1
- package/dist/app-auth/index.js.map +1 -1
- package/dist/chat-routes/hybrid-producer.d.ts +1 -1
- package/dist/chat-routes/index.js +11 -11
- package/dist/chat-routes/model-failover-stream.d.ts +1 -1
- package/dist/chat-routes/turn-prefetch.d.ts +1 -1
- package/dist/{chunk-Z4RD5UF7.js → chunk-2PCNHHN2.js} +2 -2
- package/dist/{chunk-I6BZVIRH.js → chunk-3CI35I4X.js} +1 -1
- package/dist/chunk-3CI35I4X.js.map +1 -0
- package/dist/{chunk-ISP6ZH3G.js → chunk-3Q3UEWKK.js} +1 -1
- package/dist/chunk-3Q3UEWKK.js.map +1 -0
- package/dist/{chunk-VDYEVCQQ.js → chunk-5WSSH3X5.js} +2 -2
- package/dist/chunk-5WSSH3X5.js.map +1 -0
- package/dist/{chunk-NUWSPR5O.js → chunk-G3LZITCA.js} +2 -2
- package/dist/{chunk-IX6UVHXY.js → chunk-JKECSYDB.js} +2 -2
- package/dist/{chunk-6GX3UHQW.js → chunk-K3A2YAIX.js} +6 -6
- package/dist/chunk-K3A2YAIX.js.map +1 -0
- package/dist/{chunk-5GSZGTPJ.js → chunk-KA6LD4OI.js} +3 -3
- package/dist/{chunk-A3BJDXPX.js → chunk-LMIP4OVR.js} +5 -5
- package/dist/chunk-LMIP4OVR.js.map +1 -0
- package/dist/{chunk-MT6ZTQGD.js → chunk-N5RWYR5N.js} +1 -1
- package/dist/chunk-N5RWYR5N.js.map +1 -0
- package/dist/{chunk-7VTGB4DM.js → chunk-OSMMEMDH.js} +1 -1
- package/dist/chunk-OSMMEMDH.js.map +1 -0
- package/dist/{chunk-5FAKBTCK.js → chunk-OYFA7BAK.js} +1 -1
- package/dist/chunk-OYFA7BAK.js.map +1 -0
- package/dist/{chunk-7EDNPQHW.js → chunk-OZDMIYES.js} +1 -1
- package/dist/chunk-OZDMIYES.js.map +1 -0
- package/dist/{chunk-ZLX4BA27.js → chunk-QUT3T2IN.js} +1 -1
- package/dist/chunk-QUT3T2IN.js.map +1 -0
- package/dist/{chunk-PK65B6HP.js → chunk-UJYEBQMS.js} +1 -1
- package/dist/{chunk-PK65B6HP.js.map → chunk-UJYEBQMS.js.map} +1 -1
- package/dist/{chunk-5UQJ7F3P.js → chunk-UULUBF5J.js} +1 -1
- package/dist/chunk-UULUBF5J.js.map +1 -0
- package/dist/{chunk-LRYY3OX7.js → chunk-VEPII3YP.js} +4 -4
- package/dist/chunk-VEPII3YP.js.map +1 -0
- package/dist/{chunk-AVBNS64P.js → chunk-W6G2HF6M.js} +1 -1
- package/dist/chunk-W6G2HF6M.js.map +1 -0
- package/dist/{chunk-4GINUJPF.js → chunk-WRCMVBUJ.js} +1 -1
- package/dist/{chunk-4GINUJPF.js.map → chunk-WRCMVBUJ.js.map} +1 -1
- package/dist/{chunk-E3AOUTIR.js → chunk-XGFGSZS5.js} +2 -2
- package/dist/chunk-XGFGSZS5.js.map +1 -0
- package/dist/{chunk-EKXG4JSN.js → chunk-YRWUJKW5.js} +2 -2
- package/dist/chunk-YRWUJKW5.js.map +1 -0
- package/dist/journeys/cli.js +1 -1
- package/dist/journeys/index.js +1 -1
- package/dist/journeys/index.js.map +1 -1
- package/dist/journeys/score.d.ts +1 -1
- package/dist/journeys/scoreboard.d.ts +1 -2
- package/dist/journeys/send.d.ts +1 -2
- package/dist/launch-invariants/auth-lookup-cache.d.ts +1 -1
- package/dist/launch-invariants/catalog.d.ts +3 -3
- package/dist/launch-invariants/cli.js +3 -3
- package/dist/launch-invariants/index.d.ts +1 -1
- package/dist/launch-invariants/index.js +3 -3
- package/dist/launch-invariants/index.js.map +1 -1
- package/dist/launch-invariants/limit-alarms.d.ts +1 -1
- package/dist/launch-invariants/pasted-code.d.ts +1 -1
- package/dist/launch-invariants/schedule.d.ts +1 -1
- package/dist/launch-invariants/settlement.d.ts +2 -2
- package/dist/launch-invariants/sized-reads.d.ts +1 -1
- package/dist/launch-invariants/testing.js +3 -3
- package/dist/model-resolution/index.js +1 -1
- package/dist/platform/billable-turn-admission.d.ts +1 -1
- package/dist/platform/delegated-keys.d.ts +2 -2
- package/dist/platform/delegated-turn-keys.d.ts +1 -1
- package/dist/platform/index.js.map +1 -1
- package/dist/preflight/cli.js +1 -1
- package/dist/preflight/index.d.ts +1 -1
- package/dist/preflight/index.js +1 -1
- package/dist/preset-cloudflare/index.js +6 -6
- package/dist/public-consultation/index.js +9 -9
- package/dist/rollout/cli.js +1 -1
- package/dist/rollout/d1.js +1 -1
- package/dist/rollout/index.d.ts +1 -1
- package/dist/rollout/index.js +1 -1
- package/dist/runtime/index.js +3 -3
- package/dist/runtime/router-turn.d.ts +3 -3
- package/dist/runtime/router-turn.js +2 -2
- package/dist/runtime/turn-knowledge.d.ts +1 -1
- package/dist/sandbox/index.js +5 -5
- package/dist/sandbox/model.d.ts +1 -1
- package/dist/sandbox/prewarm-claim-d1.d.ts +1 -1
- package/dist/sandbox/prewarm.d.ts +2 -2
- package/dist/sandbox/reuse-state.d.ts +1 -1
- package/dist/sandbox/terminal-connection.d.ts +4 -4
- package/dist/sandbox/warm-lease.d.ts +2 -2
- package/dist/sandbox/warm-receipts.d.ts +1 -1
- package/dist/signoff/app-defaults.d.ts +1 -1
- package/dist/signoff/cli.js +2 -2
- package/dist/signoff/index.js +2 -2
- package/dist/signoff/surface-ladder.d.ts +2 -2
- package/dist/signoff/workspace-surface.d.ts +1 -1
- package/dist/stream/index.js +2 -2
- package/dist/stream/turn-buffer.d.ts +1 -1
- package/dist/turn-health/index.js +1 -1
- package/dist/turn-health/index.js.map +1 -1
- package/dist/turn-stream/adapters.d.ts +1 -1
- package/dist/turn-stream/core.d.ts +1 -1
- package/dist/turn-stream/index.js +2 -2
- package/dist/turn-trace/index.js +1 -1
- package/dist/turn-trace/otel.d.ts +1 -1
- package/dist/workspace-export/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-5FAKBTCK.js.map +0 -1
- package/dist/chunk-5UQJ7F3P.js.map +0 -1
- package/dist/chunk-6GX3UHQW.js.map +0 -1
- package/dist/chunk-7EDNPQHW.js.map +0 -1
- package/dist/chunk-7VTGB4DM.js.map +0 -1
- package/dist/chunk-A3BJDXPX.js.map +0 -1
- package/dist/chunk-AVBNS64P.js.map +0 -1
- package/dist/chunk-E3AOUTIR.js.map +0 -1
- package/dist/chunk-EKXG4JSN.js.map +0 -1
- package/dist/chunk-I6BZVIRH.js.map +0 -1
- package/dist/chunk-ISP6ZH3G.js.map +0 -1
- package/dist/chunk-LRYY3OX7.js.map +0 -1
- package/dist/chunk-MT6ZTQGD.js.map +0 -1
- package/dist/chunk-VDYEVCQQ.js.map +0 -1
- package/dist/chunk-ZLX4BA27.js.map +0 -1
- /package/dist/{chunk-Z4RD5UF7.js.map → chunk-2PCNHHN2.js.map} +0 -0
- /package/dist/{chunk-NUWSPR5O.js.map → chunk-G3LZITCA.js.map} +0 -0
- /package/dist/{chunk-IX6UVHXY.js.map → chunk-JKECSYDB.js.map} +0 -0
- /package/dist/{chunk-5GSZGTPJ.js.map → chunk-KA6LD4OI.js.map} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/turn-health/lifecycle.ts","../../src/turn-health/sweep.ts"],"sourcesContent":["/**\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 /** The newest of these messages was followed by a row that showed the person\n * something (a failure notice or error prose), so they know it failed. False\n * or absent: nothing came back at all. */\n notified?: boolean\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 /**\n * Which threads that got no reply at all should page (a `critical` alert);\n * the rest are reported as a `warning`. A product passes its own rule, such\n * as only its customers' and operators' threads, so internal and evaluation\n * traffic stops paging. Default: threads silent for 24 hours or more.\n */\n pageSilentThreads?: (threads: UnansweredThread[]) => Promise<UnansweredThread[]> | UnansweredThread[]\n /**\n * Where a product already reports threads that ended on a failure the person\n * saw, such as its reliability report. When set, those threads are counted\n * but not alerted here. Unset, they are a `warning`, so a product whose every\n * reply is an error message still shows up.\n */\n failureNoticesReportedBy?: string\n now?: number\n}\n\nconst defaultPageSilentThreads = (threads: UnansweredThread[]) => threads.filter((thread) => thread.oldestAgeMs >= 24 * HOUR_MS)\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 /** Threads whose user messages have no real answer: {@link silentThreads}\n * plus {@link notifiedThreads}. */\n unansweredThreads: number\n pendingUserMessages: number\n oldestUnansweredMs: number\n /** Threads where nothing came back after the newest message. */\n silentThreads: number\n /** Of {@link silentThreads}, the ones `pageSilentThreads` selected. */\n pagedSilentThreads: number\n /** Threads that ended on a failure the person saw. */\n notifiedThreads: 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 const silent = unanswered.filter((t) => !t.notified)\n const notified = unanswered.filter((t) => t.notified)\n const paged = new Set(\n (await (options.pageSilentThreads ?? defaultPageSilentThreads)(silent)).map((t) => t.threadId),\n )\n const describeThread = (t: UnansweredThread) =>\n `thread ${t.threadId}: ${t.pendingMessages} pending, oldest ${(t.oldestAgeMs / HOUR_MS).toFixed(1)}h`\n\n if (silent.length > 0) {\n const silentMessages = silent.reduce((sum, t) => sum + t.pendingMessages, 0)\n const oldest = silent.reduce((max, t) => Math.max(max, t.oldestAgeMs), 0)\n alerts.push({\n product: options.product,\n severity: paged.size > 0 ? 'critical' : 'warning',\n key: `sweep:${options.product}:unanswered_threads`,\n title: `${options.product}: ${silentMessages} user message(s) unanswered across ${silent.length} thread(s), with no reply at all`,\n details: [\n `oldest unanswered message: ${(oldest / HOUR_MS).toFixed(1)}h; ${paged.size} of these thread(s) page`,\n // The threads that page come first, so the alert names what to open.\n ...[...silent.filter((t) => paged.has(t.threadId)), ...silent.filter((t) => !paged.has(t.threadId))]\n .slice(0, 5)\n .map((t) => `${describeThread(t)}${paged.has(t.threadId) ? ' (pages)' : ''}`),\n ],\n data: { silentThreads: silent.length, pagedSilentThreads: paged.size, pendingUserMessages: silentMessages, oldestUnansweredMs: oldest },\n at: now,\n })\n }\n if (notified.length > 0 && !options.failureNoticesReportedBy) {\n const notifiedMessages = notified.reduce((sum, t) => sum + t.pendingMessages, 0)\n alerts.push({\n product: options.product,\n severity: 'warning',\n key: `sweep:${options.product}:failed_threads`,\n title: `${options.product}: ${notifiedMessages} user message(s) across ${notified.length} thread(s) ended on a failure the person saw`,\n details: notified.slice(0, 5).map(describeThread),\n data: { notifiedThreads: notified.length, pendingUserMessages: notifiedMessages },\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 silentThreads: silent.length,\n pagedSilentThreads: paged.size,\n notifiedThreads: notified.length,\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 // A row after the newest pending message that showed something (error\n // prose, or a notice part) means the person saw the failure. A blank row\n // with no notice showed nothing, so its thread stays silent.\n const { results } = await db\n .prepare(\n `WITH pending AS (\n SELECT m.thread_id AS threadId,\n COUNT(*) AS pendingMessages,\n MIN(m.created_at) AS oldestCreatedAt,\n MAX(m.created_at) AS newestCreatedAt\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 )\n SELECT p.threadId, p.pendingMessages, p.oldestCreatedAt,\n EXISTS (\n SELECT 1 FROM ${message} a\n WHERE a.thread_id = p.threadId AND a.role = 'assistant' AND a.created_at >= p.newestCreatedAt\n AND (length(trim(coalesce(a.content, ''))) > 0 OR EXISTS (\n SELECT 1 FROM json_each(CASE WHEN json_valid(a.parts) THEN CASE WHEN json_type(a.parts) = 'array' THEN a.parts ELSE '[]' END ELSE '[]' END) n\n WHERE CASE WHEN n.type = 'object' THEN json_extract(n.value, '$.type') END = 'notice'))\n ) AS notified\n FROM pending p\n ORDER BY p.oldestCreatedAt ASC`,\n )\n .bind(cutoffSeconds, floorSeconds, ...errorPrefixes)\n .all<{ threadId: string; pendingMessages: number; oldestCreatedAt: number; notified: number }>()\n\n return results.map((row) => ({\n threadId: row.threadId,\n pendingMessages: Number(row.pendingMessages),\n oldestAgeMs: now - Number(row.oldestCreatedAt) * 1000,\n notified: Number(row.notified) === 1,\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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,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"]}
|
|
1
|
+
{"version":3,"sources":["../../src/turn-health/lifecycle.ts","../../src/turn-health/sweep.ts"],"sourcesContent":["/**\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 /** The newest of these messages was followed by a row that showed the person\n * something (a failure notice or error prose), so they know it failed. False\n * or absent: nothing came back at all. */\n notified?: boolean\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 /**\n * Which threads that got no reply at all should page (a `critical` alert);\n * the rest are reported as a `warning`. A product passes its own rule, such\n * as only its customers' and operators' threads, so internal and evaluation\n * traffic stops paging. Default: threads silent for 24 hours or more.\n */\n pageSilentThreads?: (threads: UnansweredThread[]) => Promise<UnansweredThread[]> | UnansweredThread[]\n /**\n * Where a product already reports threads that ended on a failure the person\n * saw, such as its reliability report. When set, those threads are counted\n * but not alerted here. Unset, they are a `warning`, so a product whose every\n * reply is an error message still shows up.\n */\n failureNoticesReportedBy?: string\n now?: number\n}\n\nconst defaultPageSilentThreads = (threads: UnansweredThread[]) => threads.filter((thread) => thread.oldestAgeMs >= 24 * HOUR_MS)\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 /** Threads whose user messages have no real answer: {@link silentThreads}\n * plus {@link notifiedThreads}. */\n unansweredThreads: number\n pendingUserMessages: number\n oldestUnansweredMs: number\n /** Threads where nothing came back after the newest message. */\n silentThreads: number\n /** Of {@link silentThreads}, the ones `pageSilentThreads` selected. */\n pagedSilentThreads: number\n /** Threads that ended on a failure the person saw. */\n notifiedThreads: 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 const silent = unanswered.filter((t) => !t.notified)\n const notified = unanswered.filter((t) => t.notified)\n const paged = new Set(\n (await (options.pageSilentThreads ?? defaultPageSilentThreads)(silent)).map((t) => t.threadId),\n )\n const describeThread = (t: UnansweredThread) =>\n `thread ${t.threadId}: ${t.pendingMessages} pending, oldest ${(t.oldestAgeMs / HOUR_MS).toFixed(1)}h`\n\n if (silent.length > 0) {\n const silentMessages = silent.reduce((sum, t) => sum + t.pendingMessages, 0)\n const oldest = silent.reduce((max, t) => Math.max(max, t.oldestAgeMs), 0)\n alerts.push({\n product: options.product,\n severity: paged.size > 0 ? 'critical' : 'warning',\n key: `sweep:${options.product}:unanswered_threads`,\n title: `${options.product}: ${silentMessages} user message(s) unanswered across ${silent.length} thread(s), with no reply at all`,\n details: [\n `oldest unanswered message: ${(oldest / HOUR_MS).toFixed(1)}h; ${paged.size} of these thread(s) page`,\n // The threads that page come first, so the alert names what to open.\n ...[...silent.filter((t) => paged.has(t.threadId)), ...silent.filter((t) => !paged.has(t.threadId))]\n .slice(0, 5)\n .map((t) => `${describeThread(t)}${paged.has(t.threadId) ? ' (pages)' : ''}`),\n ],\n data: { silentThreads: silent.length, pagedSilentThreads: paged.size, pendingUserMessages: silentMessages, oldestUnansweredMs: oldest },\n at: now,\n })\n }\n if (notified.length > 0 && !options.failureNoticesReportedBy) {\n const notifiedMessages = notified.reduce((sum, t) => sum + t.pendingMessages, 0)\n alerts.push({\n product: options.product,\n severity: 'warning',\n key: `sweep:${options.product}:failed_threads`,\n title: `${options.product}: ${notifiedMessages} user message(s) across ${notified.length} thread(s) ended on a failure the person saw`,\n details: notified.slice(0, 5).map(describeThread),\n data: { notifiedThreads: notified.length, pendingUserMessages: notifiedMessages },\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 silentThreads: silent.length,\n pagedSilentThreads: paged.size,\n notifiedThreads: notified.length,\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 // A row after the newest pending message that showed something (error\n // prose, or a notice part) means the person saw the failure. A blank row\n // with no notice showed nothing, so its thread stays silent.\n const { results } = await db\n .prepare(\n `WITH pending AS (\n SELECT m.thread_id AS threadId,\n COUNT(*) AS pendingMessages,\n MIN(m.created_at) AS oldestCreatedAt,\n MAX(m.created_at) AS newestCreatedAt\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 )\n SELECT p.threadId, p.pendingMessages, p.oldestCreatedAt,\n EXISTS (\n SELECT 1 FROM ${message} a\n WHERE a.thread_id = p.threadId AND a.role = 'assistant' AND a.created_at >= p.newestCreatedAt\n AND (length(trim(coalesce(a.content, ''))) > 0 OR EXISTS (\n SELECT 1 FROM json_each(CASE WHEN json_valid(a.parts) THEN CASE WHEN json_type(a.parts) = 'array' THEN a.parts ELSE '[]' END ELSE '[]' END) n\n WHERE CASE WHEN n.type = 'object' THEN json_extract(n.value, '$.type') END = 'notice'))\n ) AS notified\n FROM pending p\n ORDER BY p.oldestCreatedAt ASC`,\n )\n .bind(cutoffSeconds, floorSeconds, ...errorPrefixes)\n .all<{ threadId: string; pendingMessages: number; oldestCreatedAt: number; notified: number }>()\n\n return results.map((row) => ({\n threadId: row.threadId,\n pendingMessages: Number(row.pendingMessages),\n oldestAgeMs: now - Number(row.oldestCreatedAt) * 1000,\n notified: Number(row.notified) === 1,\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: 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":";;;;;;;;;;;;;;;;;;;AAqEA,SAAS,UAAU,OAAwB;AACzC,MAAI,iBAAiB,MAAO,QAAO,MAAM;AACzC,MAAI,OAAO,UAAU,SAAU,QAAO;AACtC,SAAO,OAAO,KAAK;AACrB;AAYO,SAAS,0BACd,SACqB;AA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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"]}
|
|
@@ -57,7 +57,7 @@ export declare function acquireDurableTurnLock(namespace: TurnStreamNamespaceLik
|
|
|
57
57
|
*
|
|
58
58
|
* The first request to a Durable Object that has never been used creates it,
|
|
59
59
|
* which measured 1.3-2.4 s for a thread's first turn in GTM production
|
|
60
|
-
*
|
|
60
|
+
* against 0.05-0.33 s once it exists; every lock now lives on the
|
|
61
61
|
* workspace channel, which exists after the workspace's first turn. A peek
|
|
62
62
|
* sent as soon as a turn is admitted wakes that object if it was evicted.
|
|
63
63
|
*/
|
|
@@ -46,7 +46,7 @@ export declare function workspaceChannelKey(workspaceId: string): string;
|
|
|
46
46
|
* stay independent because each has its own storage key
|
|
47
47
|
* ({@link turnLockStorageKey}). A thread lock on its own channel created a
|
|
48
48
|
* new Durable Object on every thread's first turn, 0.8-1.9 s inside Creative's
|
|
49
|
-
* admission on staging
|
|
49
|
+
* admission on staging against an object that already exists. */
|
|
50
50
|
export declare function turnLockChannelKey(workspaceId: string, _threadId: string, _scope: TurnLockScope): string;
|
|
51
51
|
/** The storage key a lock lives under inside its channel's instance: the
|
|
52
52
|
* workspace-scope lock under `TURN_STREAM_STORAGE_KEYS.lock`, each thread's
|
|
@@ -35,10 +35,10 @@ import {
|
|
|
35
35
|
turnStorageChannelKey,
|
|
36
36
|
verifyTurnStreamToken,
|
|
37
37
|
workspaceChannelKey
|
|
38
|
-
} from "../chunk-
|
|
38
|
+
} from "../chunk-N5RWYR5N.js";
|
|
39
39
|
import {
|
|
40
40
|
DEFAULT_RUNNING_TURN_LEASE_MS
|
|
41
|
-
} from "../chunk-
|
|
41
|
+
} from "../chunk-3Q3UEWKK.js";
|
|
42
42
|
import "../chunk-S5SRJJQG.js";
|
|
43
43
|
|
|
44
44
|
// src/turn-stream/cancellation-do.ts
|
package/dist/turn-trace/index.js
CHANGED
|
@@ -54,7 +54,7 @@ export interface IntelligenceTurnTraceSinkOptions {
|
|
|
54
54
|
/**
|
|
55
55
|
* The tenant key the ingest requires. Omit it: the sink reads the Sandbox product key from the first of
|
|
56
56
|
* `SANDBOX_PRODUCTION_API_KEY`, `TCLOUD_SANDBOX_API_KEY` and `SANDBOX_API_KEY` that is set, the platform key the
|
|
57
|
-
* ingest verifies. Legal's Worker `TANGLE_API_KEY` got 401 on every export (#468
|
|
57
|
+
* ingest verifies. Legal's Worker `TANGLE_API_KEY` got 401 on every export (#468), so a key is never assumed: a refusal is a console warning.
|
|
58
58
|
*/
|
|
59
59
|
apiKey?: string;
|
|
60
60
|
/** Default `https://intelligence.tangle.tools`; spans go to `<base>/v1/otlp/v1/traces`. */
|