@tangle-network/agent-app 0.44.7 → 0.44.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assistant/index.d.ts +4 -4
- package/dist/assistant/index.js +6 -6
- package/dist/{attachment-validation-DRuLEjAE.d.ts → attachment-validation-yJ6Id4pR.d.ts} +1 -1
- package/dist/chat-routes/index.d.ts +4 -4
- package/dist/chat-routes/index.js +3 -3
- package/dist/chat-store/index.d.ts +3 -3
- package/dist/chat-store/index.js +2 -2
- package/dist/{chunk-V55WJSR4.js → chunk-5GA3MKOC.js} +2 -2
- package/dist/{chunk-UDSY2F6N.js → chunk-72TPRENZ.js} +21 -8
- package/dist/chunk-72TPRENZ.js.map +1 -0
- package/dist/{chunk-AFNTRJQ7.js → chunk-FEUW4G2L.js} +2 -2
- package/dist/{chunk-TKRI463Z.js → chunk-J6TNPRQN.js} +4 -4
- package/dist/{chunk-F2CBC4DY.js → chunk-V3HO43PG.js} +15 -1
- package/dist/chunk-V3HO43PG.js.map +1 -0
- package/dist/{chunk-UP33Z633.js → chunk-ZRSUCTST.js} +2 -2
- package/dist/{parts-Co_lFgLI.d.ts → parts-DIKcC1p6.d.ts} +1 -1
- package/dist/{queue-CD5-_VTX.d.ts → queue-DBkulxW1.d.ts} +1 -1
- package/dist/turn-health/index.d.ts +57 -1
- package/dist/turn-health/index.js +14 -4
- package/dist/turn-health/index.js.map +1 -1
- package/dist/{types-XIZqIdX1.d.ts → types-DeEOhQbv.d.ts} +25 -3
- package/dist/web-react/index.d.ts +6 -6
- package/dist/web-react/index.js +6 -6
- package/dist/work-product/index.d.ts +73 -5
- package/dist/work-product/index.js +131 -17
- package/dist/work-product/index.js.map +1 -1
- package/dist/work-product-react/index.d.ts +1 -1
- package/dist/work-product-react/index.js +3 -3
- package/package.json +1 -1
- package/dist/chunk-F2CBC4DY.js.map +0 -1
- package/dist/chunk-UDSY2F6N.js.map +0 -1
- /package/dist/{chunk-V55WJSR4.js.map → chunk-5GA3MKOC.js.map} +0 -0
- /package/dist/{chunk-AFNTRJQ7.js.map → chunk-FEUW4G2L.js.map} +0 -0
- /package/dist/{chunk-TKRI463Z.js.map → chunk-J6TNPRQN.js.map} +0 -0
- /package/dist/{chunk-UP33Z633.js.map → chunk-ZRSUCTST.js.map} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/turn-health/classify.ts","../../src/turn-health/sink.ts","../../src/turn-health/lifecycle.ts","../../src/turn-health/sweep.ts"],"sourcesContent":["/**\n * The classifier for turns that FAIL BY RETURNING SUCCESS.\n *\n * Every failure this module names shipped to a customer with HTTP 200, no\n * thrown error, and no log line anyone read. Three were measured in production\n * in a single week:\n *\n * - a turn settled `{\"outcome\":{\"type\":\"completed\"},\"finalText\":\"\",\n * \"tokenUsage\":{\"outputTokens\":0}}` — the customer saw a blank bubble;\n * - six `submit_proposal` tool calls collapsed into ONE whose arguments were\n * a 1,652-character non-JSON string, so zero proposals persisted and\n * nothing errored (agent-runtime #626);\n * - a thread took 255 user messages over 17 days and produced 2 replies,\n * both of them error text.\n *\n * A conventional health check cannot see any of these, because it probes\n * DEPENDENCIES (is the sandbox reachable, is the router up) and every one of\n * these failures happens with all dependencies green. This classifier probes\n * the OUTCOME instead.\n *\n * It is deliberately pure and structural: it reads a settled turn's own\n * projection, so the SAME function judges a live turn through the\n * `/chat-routes` lifecycle seam and a historical row read back out of the\n * store during a sweep. One definition of \"silently broken\", two call sites.\n */\n\n/** How loudly a reason should be routed. `critical` means a customer got\n * nothing usable; `warning` means the turn degraded but still produced\n * something a human could read. */\nexport type TurnHealthSeverity = 'critical' | 'warning'\n\n/** One specific way a turn returned success while failing.\n *\n * Each variant carries the evidence that identified it, so an alert can name\n * the offending value instead of asserting a verdict the reader has to take\n * on faith. */\nexport type TurnHealthReason =\n /** Settled without error and produced nothing a user can read: no text, and\n * no artifact part (file/image/work-product/plan/interaction). This is the\n * verbatim blank-completion capture. */\n | {\n kind: 'empty_completion'\n outputTokens: number | null\n partCount: number\n durationMs?: number\n }\n /** A tool call whose arguments never parsed. The engine surfaces unparseable\n * arguments as a RAW STRING rather than throwing, so the call is neither\n * dropped nor errored — it silently does nothing. Detecting a string-typed\n * tool input that fails `JSON.parse` is the exact fingerprint of the\n * index-less parallel-tool-call collapse. */\n | {\n kind: 'malformed_tool_call'\n tool: string\n inputLength: number\n /** Leading characters of the offending input, for the alert body. */\n sample: string\n }\n /** A tool call that never reached a terminal state carrying output. The call\n * was issued and then simply produced no effect. */\n | {\n kind: 'tool_call_no_effect'\n tool: string\n status: string\n }\n /** The turn failed outright. Not silent by itself — but it becomes silent\n * the moment nothing is watching, which is how 16 days of\n * `TANGLE_HUB_URL is required` reached customers unnoticed. */\n | { kind: 'turn_failed'; reason: string }\n\n/** A settled turn, in the narrowest shape both call sites can supply.\n *\n * Structural on purpose: the lifecycle seam supplies `finalText`/`usage`, a\n * store sweep supplies `content`/`parts` read back from a row, and neither\n * has to import the other's types. */\nexport interface TurnOutcomeInput {\n /** The turn's final assistant text. */\n finalText?: string | null\n /** The persisted assistant parts. Untyped by design — a sweep reads these\n * out of a JSON column and must not be forced to validate them first. */\n parts?: readonly unknown[] | null\n /** Output tokens, when the caller has usage. `null`/absent is unknown, which\n * is NOT the same as zero and is never treated as evidence. */\n outputTokens?: number | null\n /** Set when the turn surfaced a terminal error event. */\n failed?: boolean\n failureReason?: string | null\n durationMs?: number\n}\n\n/** The verdict for one turn. `healthy` is exactly `reasons.length === 0`, kept\n * as a field so callers read intent rather than an array length. */\nexport interface TurnHealthVerdict {\n healthy: boolean\n severity: TurnHealthSeverity | null\n reasons: TurnHealthReason[]\n}\n\n/** Part kinds that count as something a user actually receives.\n *\n * A tool part is deliberately NOT here. A turn that ran six tools and said\n * nothing, with no artifact to show for it, is the malformed-tool-call\n * disaster — counting a tool chip as output would suppress the very alert\n * this module exists to raise. */\nconst ARTIFACT_PART_KINDS = new Set(['file', 'image', 'work-product', 'plan', 'interaction'])\n\nconst SAMPLE_CHARS = 120\n\nfunction asRecord(value: unknown): Record<string, unknown> | null {\n return typeof value === 'object' && value !== null ? (value as Record<string, unknown>) : null\n}\n\nfunction nonEmptyString(value: unknown): string | null {\n return typeof value === 'string' && value.trim().length > 0 ? value : null\n}\n\n/** True when a string is not parseable JSON.\n *\n * Only meaningful for tool INPUT, where the engine's contract is that a\n * well-formed call carries an object (or a string that parses into one). A\n * string that fails to parse means the arguments were concatenated or\n * truncated upstream. */\nfunction isUnparseableJson(value: string): boolean {\n const trimmed = value.trim()\n if (trimmed.length === 0) return false\n try {\n JSON.parse(trimmed)\n return false\n } catch {\n return true\n }\n}\n\n/** Tool statuses that mean the call actually landed.\n *\n * Anything else — `pending`, `running`, `error`, an unknown string — left no\n * persisted effect by the time the turn settled. */\nconst SETTLED_TOOL_STATUSES = new Set(['completed', 'complete', 'success', 'done'])\n\n/**\n * Judge one settled turn.\n *\n * Never throws: a malformed `parts` blob is a thing this function REPORTS on,\n * so it must not be a thing it dies on. Telemetry that can crash the turn it\n * measures is worse than no telemetry.\n */\nexport function classifyTurnOutcome(input: TurnOutcomeInput): TurnHealthVerdict {\n const reasons: TurnHealthReason[] = []\n\n if (input.failed) {\n reasons.push({\n kind: 'turn_failed',\n reason: nonEmptyString(input.failureReason) ?? 'unspecified',\n })\n }\n\n const parts = Array.isArray(input.parts) ? input.parts : []\n\n let hasVisibleText = nonEmptyString(input.finalText) !== null\n let artifactCount = 0\n\n for (const raw of parts) {\n const part = asRecord(raw)\n if (!part) continue\n const type = typeof part.type === 'string' ? part.type : ''\n\n if (type === 'text' && nonEmptyString(part.text) !== null) {\n hasVisibleText = true\n continue\n }\n if (ARTIFACT_PART_KINDS.has(type)) {\n artifactCount += 1\n continue\n }\n if (type !== 'tool') continue\n\n const tool = nonEmptyString(part.tool) ?? 'unknown'\n const state = asRecord(part.state)\n const status = typeof state?.status === 'string' ? state.status : 'unknown'\n\n // The #626 fingerprint: arguments surfaced as a raw string because they\n // failed to parse upstream. Checked before the status gate — a malformed\n // call can still be marked completed, which is precisely why it is silent.\n const toolInput = state?.input\n if (typeof toolInput === 'string' && isUnparseableJson(toolInput)) {\n reasons.push({\n kind: 'malformed_tool_call',\n tool,\n inputLength: toolInput.length,\n sample: toolInput.slice(0, SAMPLE_CHARS),\n })\n continue\n }\n\n if (!SETTLED_TOOL_STATUSES.has(status)) {\n reasons.push({ kind: 'tool_call_no_effect', tool, status })\n }\n }\n\n // `outputTokens` is corroborating evidence, never the trigger: a turn can\n // spend tokens on reasoning and still deliver nothing, and a turn with\n // unknown usage can still be perfectly fine.\n if (!input.failed && !hasVisibleText && artifactCount === 0) {\n reasons.push({\n kind: 'empty_completion',\n outputTokens: input.outputTokens ?? null,\n partCount: parts.length,\n ...(input.durationMs !== undefined ? { durationMs: input.durationMs } : {}),\n })\n }\n\n return {\n healthy: reasons.length === 0,\n severity: severityOf(reasons),\n reasons,\n }\n}\n\n/** `critical` when the customer got nothing usable out of the turn. A\n * malformed tool call alongside readable text is a `warning` — degraded, but\n * a human still received an answer. */\nfunction severityOf(reasons: TurnHealthReason[]): TurnHealthSeverity | null {\n if (reasons.length === 0) return null\n const critical = reasons.some((r) => r.kind === 'empty_completion' || r.kind === 'turn_failed')\n return critical ? 'critical' : 'warning'\n}\n\n/** One-line human summary of a reason, for an alert body. */\nexport function describeReason(reason: TurnHealthReason): string {\n switch (reason.kind) {\n case 'empty_completion':\n return `completed with NO output (${reason.partCount} parts, outputTokens=${\n reason.outputTokens ?? 'unknown'\n })`\n case 'malformed_tool_call':\n return `tool \\`${reason.tool}\\` arguments did not parse (${reason.inputLength} chars): ${reason.sample}`\n case 'tool_call_no_effect':\n return `tool \\`${reason.tool}\\` left no effect (status=${reason.status})`\n case 'turn_failed':\n return `turn failed: ${reason.reason}`\n }\n}\n","/**\n * Where a silent-failure verdict GOES.\n *\n * The detection half is worthless without this half. Every failure this module\n * finds was already visible in the database the whole time — 255 unanswered\n * messages sat in a table for 17 days. What was missing was not the data, it\n * was delivery to a human who had not thought to look.\n *\n * So the sink is a seam, not a channel: the product supplies the transport,\n * and agent-app ships the two shapes the fleet already has credentials for\n * (an ops webhook, and stderr). No new channel is invented here.\n */\n\nimport { describeReason, type TurnHealthReason, type TurnHealthSeverity } from './classify.js'\n\n/** One deliverable alert. */\nexport interface TurnHealthAlert {\n /** Which product raised it (`projectId`). Alerts from four products land in\n * one channel, so this is what makes the message actionable. */\n product: string\n severity: TurnHealthSeverity\n /** Stable grouping key. Throttling is keyed on this, so it must NOT contain\n * a turn id or a timestamp or every alert is unique and nothing dedupes. */\n key: string\n title: string\n /** Human-readable lines. */\n details: string[]\n /** Structured payload for a machine consumer. */\n data?: Record<string, unknown>\n at: number\n}\n\n/** Deliver an alert. Implementations MUST NOT throw — see\n * {@link createGuardedAlertSink}. */\nexport interface AlertSink {\n deliver(alert: TurnHealthAlert): Promise<void>\n}\n\n/** Build the alert for a set of reasons found on one turn. */\nexport function turnAlert(input: {\n product: string\n severity: TurnHealthSeverity\n reasons: TurnHealthReason[]\n threadId?: string\n turnId?: string\n model?: string\n at?: number\n}): TurnHealthAlert {\n const kinds = [...new Set(input.reasons.map((r) => r.kind))].sort()\n return {\n product: input.product,\n severity: input.severity,\n // Keyed by product + reason kinds ONLY. A blank-completion storm across\n // 200 turns is one incident, not 200 pages.\n key: `turn:${input.product}:${kinds.join('+')}`,\n title: `${input.product}: turn completed but delivered nothing (${kinds.join(', ')})`,\n details: input.reasons.map(describeReason),\n data: {\n kinds,\n ...(input.threadId ? { threadId: input.threadId } : {}),\n ...(input.turnId ? { turnId: input.turnId } : {}),\n ...(input.model ? { model: input.model } : {}),\n },\n at: input.at ?? Date.now(),\n }\n}\n\n// ── transports ────────────────────────────────────────────────────────────\n\n/** Minimal structural fetch, so this module has no lib-dom dependency and can\n * be driven by a fake in tests. */\nexport type FetchLike = (\n url: string,\n init: { method: string; headers: Record<string, string>; body: string },\n) => Promise<{ ok: boolean; status: number; text?(): Promise<string> }>\n\n/**\n * POST to an incoming webhook in the Slack message format.\n *\n * Chosen because the org already runs one (`SLACK_OPS_WEBHOOK_URL`) and\n * gtm-agent's outbound webhook code already speaks this exact shape — the\n * instruction was to route somewhere humans already look, not to stand up a\n * new channel. Discord and most log drains accept the same `{text}` body.\n */\nexport function createWebhookAlertSink(options: {\n webhookUrl: string\n fetchImpl?: FetchLike\n}): AlertSink {\n const fetchImpl = options.fetchImpl ?? (globalThis.fetch as unknown as FetchLike)\n return {\n async deliver(alert) {\n const icon = alert.severity === 'critical' ? ':rotating_light:' : ':warning:'\n const lines = [\n `${icon} *${alert.title}*`,\n ...alert.details.map((d) => `• ${d}`),\n `_${new Date(alert.at).toISOString()}_`,\n ]\n const response = await fetchImpl(options.webhookUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ text: lines.join('\\n') }),\n })\n if (!response.ok) {\n // A dropped alert is a silent failure of the silent-failure detector.\n // It must be loud in the one place that is still working: the log.\n throw new Error(`alert webhook responded ${response.status}`)\n }\n },\n }\n}\n\n/** stderr sink. The zero-config fallback so a product that has not yet been\n * given a webhook still emits something a log search can find. */\nexport function createConsoleAlertSink(log: (message: string) => void = console.error): AlertSink {\n return {\n async deliver(alert) {\n log(\n `[turn-health] ${alert.severity.toUpperCase()} ${alert.title} :: ${alert.details.join(' | ')}`,\n )\n },\n }\n}\n\n/** Fan out to several sinks. One failing transport must not stop the others. */\nexport function createMultiAlertSink(sinks: readonly AlertSink[]): AlertSink {\n return {\n async deliver(alert) {\n const settled = await Promise.allSettled(sinks.map((s) => s.deliver(alert)))\n const failures = settled.filter((r) => r.status === 'rejected')\n if (failures.length === sinks.length && sinks.length > 0) {\n throw new Error('every alert sink failed')\n }\n },\n }\n}\n\n// ── throttling ────────────────────────────────────────────────────────────\n\n/** Records the last time a key was alerted on. A product backs this with KV,\n * D1, or a Durable Object; the in-memory default is correct for a sweep that\n * runs as a single cron invocation. */\nexport interface AlertThrottleStore {\n lastSentAt(key: string): Promise<number | null>\n markSent(key: string, at: number): Promise<void>\n}\n\n/** Process-local throttle store. */\nexport function createMemoryThrottleStore(): AlertThrottleStore {\n const seen = new Map<string, number>()\n return {\n async lastSentAt(key) {\n return seen.get(key) ?? null\n },\n async markSent(key, at) {\n seen.set(key, at)\n },\n }\n}\n\n/**\n * Collapse repeats of the same `key` inside `windowMs`.\n *\n * Deliberately re-alerts once per window rather than going silent after the\n * first: an incident that is still burning must keep saying so. Going quiet\n * after one message is how a 17-day outage stays invisible after someone\n * dismisses the first notification.\n */\nexport function createThrottledAlertSink(\n inner: AlertSink,\n options: { windowMs: number; store?: AlertThrottleStore },\n): AlertSink {\n const store = options.store ?? createMemoryThrottleStore()\n return {\n async deliver(alert) {\n const last = await store.lastSentAt(alert.key)\n if (last !== null && alert.at - last < options.windowMs) return\n await inner.deliver(alert)\n await store.markSent(alert.key, alert.at)\n },\n }\n}\n\n/**\n * Swallow transport errors so telemetry can never fail the turn it measures.\n *\n * Use this at the LIVE lifecycle call site only. A sweep should let the error\n * surface, because a sweep that cannot deliver has done nothing at all and its\n * cron run should go red.\n */\nexport function createGuardedAlertSink(\n inner: AlertSink,\n onError: (error: unknown) => void = (e) => console.error('[turn-health] alert delivery failed', e),\n): AlertSink {\n return {\n async deliver(alert) {\n try {\n await inner.deliver(alert)\n } catch (error) {\n onError(error)\n }\n },\n }\n}\n","/**\n * The LIVE half: judge each turn the moment it settles.\n *\n * This adds no control flow. `createChatTurnRoutes` already exposes a\n * `lifecycle` seam that fires exactly one of `onTurnComplete`/`onTurnError`\n * after a turn settles, and already swallows hook errors so telemetry cannot\n * fail a turn. That seam was shipped and then wired by nobody, which is a fair\n * description of why the outage lasted 17 days. This function fills it.\n *\n * The shape is declared structurally rather than imported from\n * `/chat-routes`, so `/turn-health` stays free of the server chat vertical and\n * can be used by any turn driver that reports the same three moments.\n */\n\nimport { classifyTurnOutcome } from './classify.js'\nimport { type AlertSink, createGuardedAlertSink, turnAlert } from './sink.js'\n\n/** Structural mirror of `/chat-routes`' `ChatTurnLifecycle` complete payload. */\nexport interface TurnHealthCompleteInfo {\n finalText: string\n usage?: { outputTokens?: number | null } | null\n durationMs: number\n threadId?: string\n turnStreamId?: string\n executionId?: string\n}\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}\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 })\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 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'\n\n/** A thread that has taken user messages with no reply since. */\nexport interface UnansweredThread {\n threadId: string\n /** User messages newer than the newest real assistant reply. */\n pendingMessages: number\n /** Age of the OLDEST unanswered user message, in ms. */\n oldestAgeMs: number\n}\n\n/** A persisted assistant row, as the sweep needs to judge it. */\nexport interface PersistedTurnRow {\n id: string\n threadId: string\n content: string\n /** Raw `parts` column. A JSON string or an already-parsed array; the sweep\n * accepts both because D1 drivers differ. */\n parts: unknown\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: { minAgeMs: number; now: number }): Promise<UnansweredThread[]>\n listRecentAssistantTurns(input: { sinceMs: number; now: number; limit: number }): Promise<\n PersistedTurnRow[]\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 /** 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 now?: number\n}\n\n/** What the sweep found. Returned as well as alerted, so a cron can log it and\n * a test can assert on it. */\nexport interface SweepResult {\n product: string\n unansweredThreads: number\n pendingUserMessages: number\n oldestUnansweredMs: number\n turnsJudged: number\n unhealthyTurns: number\n emptyCompletions: number\n malformedToolCalls: number\n toolCallsWithoutEffect: number\n 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 * 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 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\n const [unanswered, turns] = await Promise.all([\n options.source.findUnansweredThreads({ minAgeMs, now }),\n options.source.listRecentAssistantTurns({ sinceMs: now - lookbackMs, now, limit }),\n ])\n\n const alerts: TurnHealthAlert[] = []\n\n // ── silence: messages in, nothing out ──────────────────────────────────\n const pendingUserMessages = unanswered.reduce((sum, t) => sum + t.pendingMessages, 0)\n const oldestUnansweredMs = unanswered.reduce((max, t) => Math.max(max, t.oldestAgeMs), 0)\n\n if (unanswered.length > 0) {\n const hours = (oldestUnansweredMs / HOUR_MS).toFixed(1)\n alerts.push({\n product: options.product,\n // A day of total silence is not a warning.\n severity: oldestUnansweredMs >= 24 * HOUR_MS ? 'critical' : 'warning',\n key: `sweep:${options.product}:unanswered_threads`,\n title: `${options.product}: ${pendingUserMessages} user message(s) unanswered across ${unanswered.length} thread(s)`,\n details: [\n `oldest unanswered message: ${hours}h`,\n ...unanswered\n .slice(0, 5)\n .map(\n (t) =>\n `thread ${t.threadId}: ${t.pendingMessages} pending, oldest ${(\n t.oldestAgeMs / HOUR_MS\n ).toFixed(1)}h`,\n ),\n ],\n data: {\n unansweredThreads: unanswered.length,\n pendingUserMessages,\n oldestUnansweredMs,\n },\n at: now,\n })\n }\n\n // ── success that delivered nothing ─────────────────────────────────────\n let emptyCompletions = 0\n let malformedToolCalls = 0\n let toolCallsWithoutEffect = 0\n let unhealthyTurns = 0\n const malformedSamples: TurnHealthReason[] = []\n\n for (const row of turns) {\n const verdict = classifyTurnOutcome({\n finalText: row.content,\n parts: parseParts(row.parts),\n outputTokens: row.outputTokens ?? null,\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 }\n }\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 if (turns.length >= minTurnsForRate) {\n const rate = emptyCompletions / turns.length\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 ${turns.length} settled turns delivered nothing`,\n `threshold ${(emptyRateThreshold * 100).toFixed(1)}%`,\n ],\n data: { emptyCompletions, turnsJudged: turns.length, rate },\n at: now,\n })\n }\n }\n\n for (const alert of alerts) await options.sink.deliver(alert)\n\n return {\n product: options.product,\n unansweredThreads: unanswered.length,\n pendingUserMessages,\n oldestUnansweredMs,\n turnsJudged: turns.length,\n unhealthyTurns,\n emptyCompletions,\n malformedToolCalls,\n toolCallsWithoutEffect,\n 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: { messageTable?: string; threadTable?: string } = {},\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\n return {\n async findUnansweredThreads({ minAgeMs, now }) {\n const cutoffSeconds = Math.floor((now - minAgeMs) / 1000)\n const { results } = await db\n .prepare(\n `SELECT m.thread_id AS threadId,\n COUNT(*) AS pendingMessages,\n MIN(m.created_at) AS oldestCreatedAt\n FROM ${message} m\n WHERE m.role = 'user'\n AND m.created_at <= ?1\n AND m.created_at > 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), 0)\n GROUP BY m.thread_id\n ORDER BY oldestCreatedAt ASC`,\n )\n .bind(cutoffSeconds)\n .all<{ threadId: string; pendingMessages: number; oldestCreatedAt: number }>()\n\n return results.map((row) => ({\n threadId: row.threadId,\n pendingMessages: Number(row.pendingMessages),\n oldestAgeMs: now - Number(row.oldestCreatedAt) * 1000,\n }))\n },\n\n async listRecentAssistantTurns({ sinceMs, limit }) {\n const sinceSeconds = Math.floor(sinceMs / 1000)\n const { results } = await db\n .prepare(\n `SELECT id, thread_id AS threadId, content, parts,\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: row.parts,\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\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":";AAwGA,IAAM,sBAAsB,oBAAI,IAAI,CAAC,QAAQ,SAAS,gBAAgB,QAAQ,aAAa,CAAC;AAE5F,IAAM,eAAe;AAErB,SAAS,SAAS,OAAgD;AAChE,SAAO,OAAO,UAAU,YAAY,UAAU,OAAQ,QAAoC;AAC5F;AAEA,SAAS,eAAe,OAA+B;AACrD,SAAO,OAAO,UAAU,YAAY,MAAM,KAAK,EAAE,SAAS,IAAI,QAAQ;AACxE;AAQA,SAAS,kBAAkB,OAAwB;AACjD,QAAM,UAAU,MAAM,KAAK;AAC3B,MAAI,QAAQ,WAAW,EAAG,QAAO;AACjC,MAAI;AACF,SAAK,MAAM,OAAO;AAClB,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAMA,IAAM,wBAAwB,oBAAI,IAAI,CAAC,aAAa,YAAY,WAAW,MAAM,CAAC;AAS3E,SAAS,oBAAoB,OAA4C;AAC9E,QAAM,UAA8B,CAAC;AAErC,MAAI,MAAM,QAAQ;AAChB,YAAQ,KAAK;AAAA,MACX,MAAM;AAAA,MACN,QAAQ,eAAe,MAAM,aAAa,KAAK;AAAA,IACjD,CAAC;AAAA,EACH;AAEA,QAAM,QAAQ,MAAM,QAAQ,MAAM,KAAK,IAAI,MAAM,QAAQ,CAAC;AAE1D,MAAI,iBAAiB,eAAe,MAAM,SAAS,MAAM;AACzD,MAAI,gBAAgB;AAEpB,aAAW,OAAO,OAAO;AACvB,UAAM,OAAO,SAAS,GAAG;AAC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AAAA;AAAA;AAAA;AAAA,MAInB,EACC,KAAK,cAAc,KAAK,EACxB,IAA6B;AAEhC,aAAO,QAAQ,IAAI,CAAC,SAAS;AAAA,QAC3B,IAAI,OAAO,IAAI,EAAE;AAAA,QACjB,UAAU,OAAO,IAAI,QAAQ;AAAA,QAC7B,SAAS,OAAO,IAAI,YAAY,WAAW,IAAI,UAAU;AAAA,QACzD,OAAO,IAAI;AAAA,QACX,cAAc,IAAI,iBAAiB,OAAO,OAAO,OAAO,IAAI,YAAY;AAAA,QACxE,OAAQ,IAAI,SAA2B;AAAA,QACvC,WAAW,OAAO,IAAI,SAAS,IAAI;AAAA,MACrC,EAAE;AAAA,IACJ;AAAA,EACF;AAEA,WAAS,eAAe,MAAsB;AAC5C,QAAI,CAAC,2BAA2B,KAAK,IAAI,GAAG;AAC1C,YAAM,IAAI,MAAM,4BAA4B,IAAI,EAAE;AAAA,IACpD;AACA,WAAO;AAAA,EACT;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/turn-health/classify.ts","../../src/turn-health/sink.ts","../../src/turn-health/lifecycle.ts","../../src/turn-health/sweep.ts"],"sourcesContent":["/**\n * The classifier for turns that FAIL BY RETURNING SUCCESS.\n *\n * Every failure this module names shipped to a customer with HTTP 200, no\n * thrown error, and no log line anyone read. Three were measured in production\n * in a single week:\n *\n * - a turn settled `{\"outcome\":{\"type\":\"completed\"},\"finalText\":\"\",\n * \"tokenUsage\":{\"outputTokens\":0}}` — the customer saw a blank bubble;\n * - six `submit_proposal` tool calls collapsed into ONE whose arguments were\n * a 1,652-character non-JSON string, so zero proposals persisted and\n * nothing errored (agent-runtime #626);\n * - a thread took 255 user messages over 17 days and produced 2 replies,\n * both of them error text.\n *\n * A conventional health check cannot see any of these, because it probes\n * DEPENDENCIES (is the sandbox reachable, is the router up) and every one of\n * these failures happens with all dependencies green. This classifier probes\n * the OUTCOME instead.\n *\n * It is deliberately pure and structural: it reads a settled turn's own\n * projection, so the SAME function judges a live turn through the\n * `/chat-routes` lifecycle seam and a historical row read back out of the\n * store during a sweep. One definition of \"silently broken\", two call sites.\n */\n\n/** How loudly a reason should be routed. `critical` means a customer got\n * nothing usable; `warning` means the turn degraded but still produced\n * something a human could read. */\nexport type TurnHealthSeverity = 'critical' | 'warning'\n\n/** One specific way a turn returned success while failing.\n *\n * Each variant carries the evidence that identified it, so an alert can name\n * the offending value instead of asserting a verdict the reader has to take\n * on faith. */\nexport type TurnHealthReason =\n /** Settled without error and produced nothing a user can read: no text, and\n * no artifact part (file/image/work-product/plan/interaction). This is the\n * verbatim blank-completion capture. */\n | {\n kind: 'empty_completion'\n outputTokens: number | null\n partCount: number\n durationMs?: number\n }\n /** A tool call whose arguments never parsed. The engine surfaces unparseable\n * arguments as a RAW STRING rather than throwing, so the call is neither\n * dropped nor errored — it silently does nothing. Detecting a string-typed\n * tool input that fails `JSON.parse` is the exact fingerprint of the\n * index-less parallel-tool-call collapse. */\n | {\n kind: 'malformed_tool_call'\n tool: string\n inputLength: number\n /** Leading characters of the offending input, for the alert body. */\n sample: string\n }\n /** A tool call that never reached a terminal state carrying output. The call\n * was issued and then simply produced no effect. */\n | {\n kind: 'tool_call_no_effect'\n tool: string\n status: string\n }\n /** The turn failed outright. Not silent by itself — but it becomes silent\n * the moment nothing is watching, which is how 16 days of\n * `TANGLE_HUB_URL is required` reached customers unnoticed. */\n | { kind: 'turn_failed'; reason: string }\n\n/** A settled turn, in the narrowest shape both call sites can supply.\n *\n * Structural on purpose: the lifecycle seam supplies `finalText`/`usage`, a\n * store sweep supplies `content`/`parts` read back from a row, and neither\n * has to import the other's types. */\nexport interface TurnOutcomeInput {\n /** The turn's final assistant text. */\n finalText?: string | null\n /** The persisted assistant parts. Untyped by design — a sweep reads these\n * out of a JSON column and must not be forced to validate them first. */\n parts?: readonly unknown[] | null\n /** Output tokens, when the caller has usage. `null`/absent is unknown, which\n * is NOT the same as zero and is never treated as evidence. */\n outputTokens?: number | null\n /** Set when the turn surfaced a terminal error event. */\n failed?: boolean\n failureReason?: string | null\n durationMs?: number\n}\n\n/** The verdict for one turn. `healthy` is exactly `reasons.length === 0`, kept\n * as a field so callers read intent rather than an array length. */\nexport interface TurnHealthVerdict {\n healthy: boolean\n severity: TurnHealthSeverity | null\n reasons: TurnHealthReason[]\n}\n\n/** Part kinds that count as something a user actually receives.\n *\n * A tool part is deliberately NOT here. A turn that ran six tools and said\n * nothing, with no artifact to show for it, is the malformed-tool-call\n * disaster — counting a tool chip as output would suppress the very alert\n * this module exists to raise. */\nconst ARTIFACT_PART_KINDS = new Set(['file', 'image', 'work-product', 'plan', 'interaction'])\n\nconst SAMPLE_CHARS = 120\n\nfunction asRecord(value: unknown): Record<string, unknown> | null {\n return typeof value === 'object' && value !== null ? (value as Record<string, unknown>) : null\n}\n\nfunction nonEmptyString(value: unknown): string | null {\n return typeof value === 'string' && value.trim().length > 0 ? value : null\n}\n\n/** True when a string is not parseable JSON.\n *\n * Only meaningful for tool INPUT, where the engine's contract is that a\n * well-formed call carries an object (or a string that parses into one). A\n * string that fails to parse means the arguments were concatenated or\n * truncated upstream. */\nfunction isUnparseableJson(value: string): boolean {\n const trimmed = value.trim()\n if (trimmed.length === 0) return false\n try {\n JSON.parse(trimmed)\n return false\n } catch {\n return true\n }\n}\n\n/** Tool statuses that mean the call actually landed.\n *\n * Anything else — `pending`, `running`, `error`, an unknown string — left no\n * persisted effect by the time the turn settled. */\nconst SETTLED_TOOL_STATUSES = new Set(['completed', 'complete', 'success', 'done'])\n\n/**\n * Judge one settled turn.\n *\n * Never throws: a malformed `parts` blob is a thing this function REPORTS on,\n * so it must not be a thing it dies on. Telemetry that can crash the turn it\n * measures is worse than no telemetry.\n */\nexport function classifyTurnOutcome(input: TurnOutcomeInput): TurnHealthVerdict {\n const reasons: TurnHealthReason[] = []\n\n if (input.failed) {\n reasons.push({\n kind: 'turn_failed',\n reason: nonEmptyString(input.failureReason) ?? 'unspecified',\n })\n }\n\n const parts = Array.isArray(input.parts) ? input.parts : []\n\n let hasVisibleText = nonEmptyString(input.finalText) !== null\n let artifactCount = 0\n\n for (const raw of parts) {\n const part = asRecord(raw)\n if (!part) continue\n const type = typeof part.type === 'string' ? part.type : ''\n\n if (type === 'text' && nonEmptyString(part.text) !== null) {\n hasVisibleText = true\n continue\n }\n if (ARTIFACT_PART_KINDS.has(type)) {\n artifactCount += 1\n continue\n }\n if (type !== 'tool') continue\n\n const tool = nonEmptyString(part.tool) ?? 'unknown'\n const state = asRecord(part.state)\n const status = typeof state?.status === 'string' ? state.status : 'unknown'\n\n // The #626 fingerprint: arguments surfaced as a raw string because they\n // failed to parse upstream. Checked before the status gate — a malformed\n // call can still be marked completed, which is precisely why it is silent.\n const toolInput = state?.input\n if (typeof toolInput === 'string' && isUnparseableJson(toolInput)) {\n reasons.push({\n kind: 'malformed_tool_call',\n tool,\n inputLength: toolInput.length,\n sample: toolInput.slice(0, SAMPLE_CHARS),\n })\n continue\n }\n\n if (!SETTLED_TOOL_STATUSES.has(status)) {\n reasons.push({ kind: 'tool_call_no_effect', tool, status })\n }\n }\n\n // `outputTokens` is corroborating evidence, never the trigger: a turn can\n // spend tokens on reasoning and still deliver nothing, and a turn with\n // unknown usage can still be perfectly fine.\n if (!input.failed && !hasVisibleText && artifactCount === 0) {\n reasons.push({\n kind: 'empty_completion',\n outputTokens: input.outputTokens ?? null,\n partCount: parts.length,\n ...(input.durationMs !== undefined ? { durationMs: input.durationMs } : {}),\n })\n }\n\n return {\n healthy: reasons.length === 0,\n severity: severityOf(reasons),\n reasons,\n }\n}\n\n/** `critical` when the customer got nothing usable out of the turn. A\n * malformed tool call alongside readable text is a `warning` — degraded, but\n * a human still received an answer. */\nfunction severityOf(reasons: TurnHealthReason[]): TurnHealthSeverity | null {\n if (reasons.length === 0) return null\n const critical = reasons.some((r) => r.kind === 'empty_completion' || r.kind === 'turn_failed')\n return critical ? 'critical' : 'warning'\n}\n\n/** One-line human summary of a reason, for an alert body. */\nexport function describeReason(reason: TurnHealthReason): string {\n switch (reason.kind) {\n case 'empty_completion':\n return `completed with NO output (${reason.partCount} parts, outputTokens=${\n reason.outputTokens ?? 'unknown'\n })`\n case 'malformed_tool_call':\n return `tool \\`${reason.tool}\\` arguments did not parse (${reason.inputLength} chars): ${reason.sample}`\n case 'tool_call_no_effect':\n return `tool \\`${reason.tool}\\` left no effect (status=${reason.status})`\n case 'turn_failed':\n return `turn failed: ${reason.reason}`\n }\n}\n","/**\n * Where a silent-failure verdict GOES.\n *\n * The detection half is worthless without this half. Every failure this module\n * finds was already visible in the database the whole time — 255 unanswered\n * messages sat in a table for 17 days. What was missing was not the data, it\n * was delivery to a human who had not thought to look.\n *\n * So the sink is a seam, not a channel: the product supplies the transport,\n * and agent-app ships the two shapes the fleet already has credentials for\n * (an ops webhook, and stderr). No new channel is invented here.\n */\n\nimport { describeReason, type TurnHealthReason, type TurnHealthSeverity } from './classify.js'\n\n/** One deliverable alert. */\nexport interface TurnHealthAlert {\n /** Which product raised it (`projectId`). Alerts from four products land in\n * one channel, so this is what makes the message actionable. */\n product: string\n severity: TurnHealthSeverity\n /** Stable grouping key. Throttling is keyed on this, so it must NOT contain\n * a turn id or a timestamp or every alert is unique and nothing dedupes. */\n key: string\n title: string\n /** Human-readable lines. */\n details: string[]\n /** Structured payload for a machine consumer. */\n data?: Record<string, unknown>\n at: number\n}\n\n/** Deliver an alert. Implementations MUST NOT throw — see\n * {@link createGuardedAlertSink}. */\nexport interface AlertSink {\n deliver(alert: TurnHealthAlert): Promise<void>\n}\n\n/** Build the alert for a set of reasons found on one turn. */\nexport function turnAlert(input: {\n product: string\n severity: TurnHealthSeverity\n reasons: TurnHealthReason[]\n threadId?: string\n turnId?: string\n model?: string\n at?: number\n}): TurnHealthAlert {\n const kinds = [...new Set(input.reasons.map((r) => r.kind))].sort()\n return {\n product: input.product,\n severity: input.severity,\n // Keyed by product + reason kinds ONLY. A blank-completion storm across\n // 200 turns is one incident, not 200 pages.\n key: `turn:${input.product}:${kinds.join('+')}`,\n title: `${input.product}: turn completed but delivered nothing (${kinds.join(', ')})`,\n details: input.reasons.map(describeReason),\n data: {\n kinds,\n ...(input.threadId ? { threadId: input.threadId } : {}),\n ...(input.turnId ? { turnId: input.turnId } : {}),\n ...(input.model ? { model: input.model } : {}),\n },\n at: input.at ?? Date.now(),\n }\n}\n\n// ── transports ────────────────────────────────────────────────────────────\n\n/** Minimal structural fetch, so this module has no lib-dom dependency and can\n * be driven by a fake in tests. */\nexport type FetchLike = (\n url: string,\n init: { method: string; headers: Record<string, string>; body: string },\n) => Promise<{ ok: boolean; status: number; text?(): Promise<string> }>\n\n/**\n * POST to an incoming webhook in the Slack message format.\n *\n * Chosen because the org already runs one (`SLACK_OPS_WEBHOOK_URL`) and\n * gtm-agent's outbound webhook code already speaks this exact shape — the\n * instruction was to route somewhere humans already look, not to stand up a\n * new channel. Discord and most log drains accept the same `{text}` body.\n */\nexport function createWebhookAlertSink(options: {\n webhookUrl: string\n fetchImpl?: FetchLike\n}): AlertSink {\n const fetchImpl = options.fetchImpl ?? (globalThis.fetch as unknown as FetchLike)\n return {\n async deliver(alert) {\n const icon = alert.severity === 'critical' ? ':rotating_light:' : ':warning:'\n const lines = [\n `${icon} *${alert.title}*`,\n ...alert.details.map((d) => `• ${d}`),\n `_${new Date(alert.at).toISOString()}_`,\n ]\n const response = await fetchImpl(options.webhookUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ text: lines.join('\\n') }),\n })\n if (!response.ok) {\n // A dropped alert is a silent failure of the silent-failure detector.\n // It must be loud in the one place that is still working: the log.\n throw new Error(`alert webhook responded ${response.status}`)\n }\n },\n }\n}\n\n/** stderr sink. The zero-config fallback so a product that has not yet been\n * given a webhook still emits something a log search can find. */\nexport function createConsoleAlertSink(log: (message: string) => void = console.error): AlertSink {\n return {\n async deliver(alert) {\n log(\n `[turn-health] ${alert.severity.toUpperCase()} ${alert.title} :: ${alert.details.join(' | ')}`,\n )\n },\n }\n}\n\n/** Fan out to several sinks. One failing transport must not stop the others. */\nexport function createMultiAlertSink(sinks: readonly AlertSink[]): AlertSink {\n return {\n async deliver(alert) {\n const settled = await Promise.allSettled(sinks.map((s) => s.deliver(alert)))\n const failures = settled.filter((r) => r.status === 'rejected')\n if (failures.length === sinks.length && sinks.length > 0) {\n throw new Error('every alert sink failed')\n }\n },\n }\n}\n\n// ── throttling ────────────────────────────────────────────────────────────\n\n/** Records the last time a key was alerted on. A product backs this with KV,\n * D1, or a Durable Object; the in-memory default is correct for a sweep that\n * runs as a single cron invocation. */\nexport interface AlertThrottleStore {\n lastSentAt(key: string): Promise<number | null>\n markSent(key: string, at: number): Promise<void>\n}\n\n/** Process-local throttle store. */\nexport function createMemoryThrottleStore(): AlertThrottleStore {\n const seen = new Map<string, number>()\n return {\n async lastSentAt(key) {\n return seen.get(key) ?? null\n },\n async markSent(key, at) {\n seen.set(key, at)\n },\n }\n}\n\n/**\n * Collapse repeats of the same `key` inside `windowMs`.\n *\n * Deliberately re-alerts once per window rather than going silent after the\n * first: an incident that is still burning must keep saying so. Going quiet\n * after one message is how a 17-day outage stays invisible after someone\n * dismisses the first notification.\n */\nexport function createThrottledAlertSink(\n inner: AlertSink,\n options: { windowMs: number; store?: AlertThrottleStore },\n): AlertSink {\n const store = options.store ?? createMemoryThrottleStore()\n return {\n async deliver(alert) {\n const last = await store.lastSentAt(alert.key)\n if (last !== null && alert.at - last < options.windowMs) return\n await inner.deliver(alert)\n await store.markSent(alert.key, alert.at)\n },\n }\n}\n\n/**\n * Swallow transport errors so telemetry can never fail the turn it measures.\n *\n * Use this at the LIVE lifecycle call site only. A sweep should let the error\n * surface, because a sweep that cannot deliver has done nothing at all and its\n * cron run should go red.\n */\nexport function createGuardedAlertSink(\n inner: AlertSink,\n onError: (error: unknown) => void = (e) => console.error('[turn-health] alert delivery failed', e),\n): AlertSink {\n return {\n async deliver(alert) {\n try {\n await inner.deliver(alert)\n } catch (error) {\n onError(error)\n }\n },\n }\n}\n","/**\n * The LIVE half: judge each turn the moment it settles.\n *\n * This adds no control flow. `createChatTurnRoutes` already exposes a\n * `lifecycle` seam that fires exactly one of `onTurnComplete`/`onTurnError`\n * after a turn settles, and already swallows hook errors so telemetry cannot\n * fail a turn. That seam was shipped and then wired by nobody, which is a fair\n * description of why the outage lasted 17 days. This function fills it.\n *\n * The shape is declared structurally rather than imported from\n * `/chat-routes`, so `/turn-health` stays free of the server chat vertical and\n * can be used by any turn driver that reports the same three moments.\n */\n\nimport { classifyTurnOutcome } from './classify.js'\nimport { type AlertSink, createGuardedAlertSink, turnAlert } from './sink.js'\n\n/** Structural mirror of `/chat-routes`' `ChatTurnLifecycle` complete payload. */\nexport interface TurnHealthCompleteInfo {\n finalText: string\n usage?: { outputTokens?: number | null } | null\n durationMs: number\n threadId?: string\n turnStreamId?: string\n executionId?: string\n}\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}\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 })\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 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'\n\n/** A thread that has taken user messages with no reply since. */\nexport interface UnansweredThread {\n threadId: string\n /** User messages newer than the newest real assistant reply. */\n pendingMessages: number\n /** Age of the OLDEST unanswered user message, in ms. */\n oldestAgeMs: number\n}\n\n/** A persisted assistant row, as the sweep needs to judge it. */\nexport interface PersistedTurnRow {\n id: string\n threadId: string\n content: string\n /** Raw `parts` column. A JSON string or an already-parsed array; the sweep\n * accepts both because D1 drivers differ. */\n parts: unknown\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\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 now?: number\n}\n\n/** What the sweep found. Returned as well as alerted, so a cron can log it and\n * a test can assert on it. */\nexport interface SweepResult {\n product: string\n unansweredThreads: number\n pendingUserMessages: number\n oldestUnansweredMs: number\n turnsJudged: number\n unhealthyTurns: number\n emptyCompletions: number\n malformedToolCalls: number\n toolCallsWithoutEffect: number\n 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 */\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\n const [unanswered, turns] = await Promise.all([\n options.source.findUnansweredThreads({ minAgeMs, maxAgeMs, now }),\n options.source.listRecentAssistantTurns({ sinceMs: now - lookbackMs, now, limit }),\n ])\n\n const alerts: TurnHealthAlert[] = []\n\n // ── silence: messages in, nothing out ──────────────────────────────────\n const pendingUserMessages = unanswered.reduce((sum, t) => sum + t.pendingMessages, 0)\n const oldestUnansweredMs = unanswered.reduce((max, t) => Math.max(max, t.oldestAgeMs), 0)\n\n if (unanswered.length > 0) {\n const hours = (oldestUnansweredMs / HOUR_MS).toFixed(1)\n alerts.push({\n product: options.product,\n // A day of total silence is not a warning.\n severity: oldestUnansweredMs >= 24 * HOUR_MS ? 'critical' : 'warning',\n key: `sweep:${options.product}:unanswered_threads`,\n title: `${options.product}: ${pendingUserMessages} user message(s) unanswered across ${unanswered.length} thread(s)`,\n details: [\n `oldest unanswered message: ${hours}h`,\n ...unanswered\n .slice(0, 5)\n .map(\n (t) =>\n `thread ${t.threadId}: ${t.pendingMessages} pending, oldest ${(\n t.oldestAgeMs / HOUR_MS\n ).toFixed(1)}h`,\n ),\n ],\n data: {\n unansweredThreads: unanswered.length,\n pendingUserMessages,\n oldestUnansweredMs,\n },\n at: now,\n })\n }\n\n // ── success that delivered nothing ─────────────────────────────────────\n let emptyCompletions = 0\n let malformedToolCalls = 0\n let toolCallsWithoutEffect = 0\n let unhealthyTurns = 0\n const malformedSamples: TurnHealthReason[] = []\n\n for (const row of turns) {\n const verdict = classifyTurnOutcome({\n finalText: row.content,\n parts: parseParts(row.parts),\n outputTokens: row.outputTokens ?? null,\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 }\n }\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 if (turns.length >= minTurnsForRate) {\n const rate = emptyCompletions / turns.length\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 ${turns.length} settled turns delivered nothing`,\n `threshold ${(emptyRateThreshold * 100).toFixed(1)}%`,\n ],\n data: { emptyCompletions, turnsJudged: turns.length, rate },\n at: now,\n })\n }\n }\n\n for (const alert of alerts) await options.sink.deliver(alert)\n\n return {\n product: options.product,\n unansweredThreads: unanswered.length,\n pendingUserMessages,\n oldestUnansweredMs,\n turnsJudged: turns.length,\n unhealthyTurns,\n emptyCompletions,\n malformedToolCalls,\n toolCallsWithoutEffect,\n alerts,\n }\n}\n\n// ── D1 source for the shared chat-store schema ────────────────────────────\n\n/** Minimal structural D1 contract (Cloudflare's `D1Database` satisfies it). */\nexport interface D1LikeForHealth {\n prepare(sql: string): {\n bind(...values: unknown[]): {\n all<T = Record<string, unknown>>(): Promise<{ results: T[] }>\n }\n }\n}\n\n/**\n * The sweep source for products on the canonical `/chat-store` tables.\n *\n * \"Answered\" deliberately means an assistant row with NON-EMPTY content. A\n * blank assistant row is what a broken turn writes, so counting it as an\n * answer would let the exact failure being hunted mark itself resolved. That\n * single predicate is the difference between this catching the gtm outage and\n * sleeping through it — during those sixteen days the table was NOT empty.\n *\n * The query deliberately does NOT join the thread table. Products do not all\n * keep one: tax-agent's `thread` table holds zero rows because it groups by\n * its own `tax_sessions`, and an inner join against it silently reported \"0\n * unanswered threads, healthy\" while 18 real messages sat unanswered. A\n * detector that reports healthy because its join found nothing is the same\n * bug class it was built to catch.\n */\nexport function createD1TurnHealthSource(\n db: D1LikeForHealth,\n options: {\n messageTable?: string\n threadTable?: string\n /**\n * Content prefixes that mark an assistant row as an ERROR SURFACE rather\n * than an answer. A row matching one of these stops counting as a reply,\n * so the thread keeps reporting as unanswered.\n *\n * This exists because the obvious rule — \"an assistant row with non-empty\n * content is an answer\" — is wrong in the exact case that matters. On\n * 2026-07-27 gtm-agent's newest assistant row read:\n *\n * \"The sandbox model stream stopped before a clean completion.\n * Error: All 2 model(s) failed. gpt-5-mini: TANGLE_HUB_URL is required …\"\n *\n * 246 characters of well-formed prose that answers nothing. Counting it\n * marks a dead product healthy — the same failure-returning-success shape\n * this module exists to catch, recursing into the detector itself.\n *\n * There is no schema-level way to recognise it: `output_tokens IS NULL`\n * looked promising until legal-agent showed 22 of 25 GENUINE replies with\n * null usage — it would have reported a working product broken.\n *\n * Defaults to {@link SHELL_ERROR_REPLY_PREFIXES}, the openers agent-app\n * ITSELF writes in `createSandboxChatProducer`. Those are not domain —\n * this package composed them, so this package is what must recognise\n * them, and every product on the shared producer is correct with no\n * configuration. Pass your own list to ADD product-specific error prose;\n * pass `[]` to disable the rule.\n *\n * Prefixes are bound as query parameters, never interpolated.\n */\n errorReplyPrefixes?: readonly string[]\n } = {},\n): TurnHealthSource {\n // Table names are identifiers and cannot be bound as parameters. They come\n // from deploy-time product config, never from a request, and are validated\n // here so this can never become an injection point.\n const message = safeIdentifier(options.messageTable ?? 'message')\n const thread = safeIdentifier(options.threadTable ?? 'thread')\n const errorPrefixes = [...(options.errorReplyPrefixes ?? SHELL_ERROR_REPLY_PREFIXES)]\n\n return {\n async findUnansweredThreads({ minAgeMs, maxAgeMs, now }) {\n const cutoffSeconds = Math.floor((now - minAgeMs) / 1000)\n const floorSeconds = Math.floor((now - maxAgeMs) / 1000)\n // Each prefix becomes one bound `NOT LIKE ?||'%'` term. Parameters, not\n // interpolation — a product-supplied string never reaches the SQL text.\n const errorClause = errorPrefixes\n .map((_, i) => ` AND a.content NOT LIKE ?${i + 3} || '%'`)\n .join('')\n const { results } = await db\n .prepare(\n `SELECT m.thread_id AS threadId,\n COUNT(*) AS pendingMessages,\n MIN(m.created_at) AS oldestCreatedAt\n FROM ${message} m\n WHERE m.role = 'user'\n AND m.created_at <= ?1\n AND m.created_at >= ?2\n AND m.created_at > COALESCE(\n (SELECT MAX(a.created_at)\n FROM ${message} a\n WHERE a.thread_id = m.thread_id\n AND a.role = 'assistant'\n AND length(trim(a.content)) > 0${errorClause}), 0)\n GROUP BY m.thread_id\n ORDER BY oldestCreatedAt ASC`,\n )\n .bind(cutoffSeconds, floorSeconds, ...errorPrefixes)\n .all<{ threadId: string; pendingMessages: number; oldestCreatedAt: number }>()\n\n return results.map((row) => ({\n threadId: row.threadId,\n pendingMessages: Number(row.pendingMessages),\n oldestAgeMs: now - Number(row.oldestCreatedAt) * 1000,\n }))\n },\n\n async listRecentAssistantTurns({ sinceMs, limit }) {\n const sinceSeconds = Math.floor(sinceMs / 1000)\n const { results } = await db\n .prepare(\n `SELECT id, thread_id AS threadId, content, parts,\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: row.parts,\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\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":";AAwGA,IAAM,sBAAsB,oBAAI,IAAI,CAAC,QAA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;AAAA,MAInB,EACC,KAAK,cAAc,KAAK,EACxB,IAA6B;AAEhC,aAAO,QAAQ,IAAI,CAAC,SAAS;AAAA,QAC3B,IAAI,OAAO,IAAI,EAAE;AAAA,QACjB,UAAU,OAAO,IAAI,QAAQ;AAAA,QAC7B,SAAS,OAAO,IAAI,YAAY,WAAW,IAAI,UAAU;AAAA,QACzD,OAAO,IAAI;AAAA,QACX,cAAc,IAAI,iBAAiB,OAAO,OAAO,OAAO,IAAI,YAAY;AAAA,QACxE,OAAQ,IAAI,SAA2B;AAAA,QACvC,WAAW,OAAO,IAAI,SAAS,IAAI;AAAA,MACrC,EAAE;AAAA,IACJ;AAAA,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":[]}
|
|
@@ -38,13 +38,35 @@ interface WorkProductArtifact {
|
|
|
38
38
|
/** The structured field map lineage targets anchor to (tax: form-line ids). */
|
|
39
39
|
fields?: Record<string, unknown>;
|
|
40
40
|
}
|
|
41
|
-
/**
|
|
41
|
+
/** A half-open `[start, end)` character range into the source document's text.
|
|
42
|
+
* Offsets index exactly the string the product's `readSourceText` seam
|
|
43
|
+
* returns for the same `sourceRef` — which is the string its document-reading
|
|
44
|
+
* tool pages with an `offset`. The PLATFORM slices `locator.quote` out of it,
|
|
45
|
+
* so a span citation cannot name text the document does not contain. */
|
|
46
|
+
interface EvidenceSpan {
|
|
47
|
+
start: number;
|
|
48
|
+
end: number;
|
|
49
|
+
}
|
|
50
|
+
/** How `locator.quote` got there. Server-set on every path — never read from
|
|
51
|
+
* model args, because the whole value of the distinction is that a reviewer
|
|
52
|
+
* can trust it:
|
|
53
|
+
* - `span` the platform sliced it out of the source bytes (unfalsifiable)
|
|
54
|
+
* - `model` the model supplied the text and the platform PROVED it occurs */
|
|
55
|
+
type QuoteBasis = 'span' | 'model';
|
|
56
|
+
/** Point into a source document: page, free-form range, span, verbatim quote */
|
|
42
57
|
interface EvidenceLocator {
|
|
43
58
|
page?: number;
|
|
44
59
|
/** 'L120-L134' | 'B7' | '¶4' — free-form, non-empty when present. */
|
|
45
60
|
range?: string;
|
|
46
|
-
/** Verbatim supporting quote from the source.
|
|
61
|
+
/** Verbatim supporting quote from the source. Model-supplied and verified,
|
|
62
|
+
* or platform-sliced from {@link EvidenceLocator.span} — read `quoteBasis`
|
|
63
|
+
* to tell which. */
|
|
47
64
|
quote?: string;
|
|
65
|
+
/** Character range the quote is sliced from. The preferred citation form:
|
|
66
|
+
* two integers cannot be a fabricated quote. */
|
|
67
|
+
span?: EvidenceSpan;
|
|
68
|
+
/** Server-set provenance for `quote`; a model-supplied value is discarded. */
|
|
69
|
+
quoteBasis?: QuoteBasis;
|
|
48
70
|
}
|
|
49
71
|
/** One lineage row: a source document location supporting one artifact claim */
|
|
50
72
|
interface EvidenceEntry {
|
|
@@ -265,4 +287,4 @@ declare function workProductToPersistedPart(record: WorkProductRecord): WorkProd
|
|
|
265
287
|
/** Re-validate a stored/wire part into the typed anchor; null for junk. */
|
|
266
288
|
declare function persistedPartToWorkProduct(part: Record<string, unknown>): WorkProductPersistedPart | null;
|
|
267
289
|
|
|
268
|
-
export { type AgentCheckInput as A, type EvidenceEntry as E, type ProfileBacktestSummary as P, type QualityCheck as Q, type WorkProductRef as W, type WorkProductProvenance as a, type WorkProductRecord as b, type WorkProductPersistedPart as c, type WorkProductStorePort as d, type WorkProductAuditEvent as e, type WorkProductArtifact as f, type ExceptionEntry as g, type WorkProductStatus as h, type EvidenceLocator as i, type
|
|
290
|
+
export { type AgentCheckInput as A, type EvidenceEntry as E, type ProfileBacktestSummary as P, type QualityCheck as Q, type WorkProductRef as W, type WorkProductProvenance as a, type WorkProductRecord as b, type WorkProductPersistedPart as c, type WorkProductStorePort as d, type WorkProductAuditEvent as e, type WorkProductArtifact as f, type ExceptionEntry as g, type WorkProductStatus as h, type EvidenceLocator as i, type EvidenceSpan as j, type ExceptionSeverity as k, type QuoteBasis as l, type WorkProductParseResult as m, type WorkProductPatch as n, type WorkProductUpdateGuard as o, type WorkProductVersionEntry as p, isWorkProductStatus as q, parseAgentCheckInput as r, parseArtifactInput as s, parseEvidenceInput as t, parseExceptionInput as u, persistedPartToWorkProduct as v, unresolvedBlockingExceptions as w, workProductToPersistedPart as x };
|
|
@@ -5,17 +5,17 @@ export { f as ChatFreeTextField, g as ComposerAnswerDelivery, h as INTERACTION_C
|
|
|
5
5
|
import { ChatPlan } from '../plans/index.js';
|
|
6
6
|
import { InteractionData } from '@tangle-network/agent-interface';
|
|
7
7
|
export { InteractionData, InteractionOutcome, InteractionRequest } from '@tangle-network/agent-interface';
|
|
8
|
-
import { M as FileMention, g as ChatMentionPart, b as ChatAttachmentPart, a as ChatAttachmentKind, Q as ChatAttachmentInput } from '../parts-
|
|
9
|
-
export { f as ChatMentionKind, P as ChatTurnFilePartInput, O as ChatTurnPartInput, N as ChatTurnRequestPayload, U as DISPATCH_MAX_MEDIA_PARTS, V as DISPATCH_MAX_PARTS, W as DISPATCH_REQUEST_MAX_BYTES, X as DISPATCH_STRUCTURAL_RESERVE_BYTES, $ as ProducerErrorEvent, a0 as ProducerNoticeEvent, a1 as ProducerPassthroughEvent, a2 as ProducerPassthroughEventType, a3 as ProducerReasoningEvent, a4 as ProducerTextEvent, a5 as ProducerToolCallEvent, a6 as ProducerToolResultEvent, a7 as ProducerUsageEvent, a8 as ProducerWireEvent, u as attachmentInputToPart, v as attachmentKindForMime, w as attachmentPartsFromMessageParts, ab as base64WireLen, ac as buildMentionPromptBlock, ad as chatTurnRequestInit, ae as fileMentionsToParts, z as isChatAttachmentPart, ag as mediaTypeForMentionPath, J as mentionInputToPart, ah as mentionKindForPath, K as mentionPartsFromMessageParts } from '../parts-
|
|
10
|
-
import { E as EvidenceEntry, g as ExceptionEntry, a as WorkProductProvenance, P as ProfileBacktestSummary, Q as QualityCheck, c as WorkProductPersistedPart, h as WorkProductStatus } from '../types-
|
|
8
|
+
import { M as FileMention, g as ChatMentionPart, b as ChatAttachmentPart, a as ChatAttachmentKind, Q as ChatAttachmentInput } from '../parts-DIKcC1p6.js';
|
|
9
|
+
export { f as ChatMentionKind, P as ChatTurnFilePartInput, O as ChatTurnPartInput, N as ChatTurnRequestPayload, U as DISPATCH_MAX_MEDIA_PARTS, V as DISPATCH_MAX_PARTS, W as DISPATCH_REQUEST_MAX_BYTES, X as DISPATCH_STRUCTURAL_RESERVE_BYTES, $ as ProducerErrorEvent, a0 as ProducerNoticeEvent, a1 as ProducerPassthroughEvent, a2 as ProducerPassthroughEventType, a3 as ProducerReasoningEvent, a4 as ProducerTextEvent, a5 as ProducerToolCallEvent, a6 as ProducerToolResultEvent, a7 as ProducerUsageEvent, a8 as ProducerWireEvent, u as attachmentInputToPart, v as attachmentKindForMime, w as attachmentPartsFromMessageParts, ab as base64WireLen, ac as buildMentionPromptBlock, ad as chatTurnRequestInit, ae as fileMentionsToParts, z as isChatAttachmentPart, ag as mediaTypeForMentionPath, J as mentionInputToPart, ah as mentionKindForPath, K as mentionPartsFromMessageParts } from '../parts-DIKcC1p6.js';
|
|
10
|
+
import { E as EvidenceEntry, g as ExceptionEntry, a as WorkProductProvenance, P as ProfileBacktestSummary, Q as QualityCheck, c as WorkProductPersistedPart, h as WorkProductStatus } from '../types-DeEOhQbv.js';
|
|
11
11
|
import { S as StepAgentActivity } from '../agent-activity-C8ZG0F0M.js';
|
|
12
12
|
import { F as FlowTrace } from '../flow-types-CJxEmaRy.js';
|
|
13
|
-
import { a as ReviewQueueItem, c as ReviewQueueState } from '../queue-
|
|
14
|
-
export { p as parseReviewQueueItem } from '../queue-
|
|
13
|
+
import { a as ReviewQueueItem, c as ReviewQueueState } from '../queue-DBkulxW1.js';
|
|
14
|
+
export { p as parseReviewQueueItem } from '../queue-DBkulxW1.js';
|
|
15
15
|
export { S as SandboxTerminalConnection, a as SandboxTerminalConnectionResponse, U as UseSandboxTerminalConnectionOptions, b as UseSandboxTerminalConnectionResult, t as tabTerminalConnectionId, u as useSandboxTerminalConnection } from '../sandbox-terminal-ChNEdHF8.js';
|
|
16
16
|
import { CatalogModel } from '../catalog/index.js';
|
|
17
17
|
import { Harness } from '../harness/index.js';
|
|
18
|
-
export { a as ATTACHMENT_ACCEPT, e as FileIndexReadyResponse, f as FileIndexResponse, g as FileIndexWarmingResponse } from '../attachment-validation-
|
|
18
|
+
export { a as ATTACHMENT_ACCEPT, e as FileIndexReadyResponse, f as FileIndexResponse, g as FileIndexWarmingResponse } from '../attachment-validation-yJ6Id4pR.js';
|
|
19
19
|
export { a as attachmentPartKey } from '../stream-normalizer-DnuqkZvw.js';
|
|
20
20
|
|
|
21
21
|
/** Represent durable plan decisions as either approved or rejected */
|
package/dist/web-react/index.js
CHANGED
|
@@ -74,7 +74,7 @@ import {
|
|
|
74
74
|
useSmoothText,
|
|
75
75
|
useThinkingSeconds,
|
|
76
76
|
waterfallLayout
|
|
77
|
-
} from "../chunk-
|
|
77
|
+
} from "../chunk-J6TNPRQN.js";
|
|
78
78
|
import "../chunk-FBVLEGEG.js";
|
|
79
79
|
import {
|
|
80
80
|
EvidenceLineageTable,
|
|
@@ -87,17 +87,17 @@ import {
|
|
|
87
87
|
reviewQueueStateLabel,
|
|
88
88
|
workProductPartsFromMessageParts,
|
|
89
89
|
workProductStatusLabel
|
|
90
|
-
} from "../chunk-
|
|
90
|
+
} from "../chunk-72TPRENZ.js";
|
|
91
91
|
import {
|
|
92
92
|
parseReviewQueueItem
|
|
93
|
-
} from "../chunk-
|
|
93
|
+
} from "../chunk-ZRSUCTST.js";
|
|
94
94
|
import {
|
|
95
95
|
tabTerminalConnectionId,
|
|
96
96
|
useSandboxTerminalConnection
|
|
97
97
|
} from "../chunk-HCOROIRT.js";
|
|
98
98
|
import {
|
|
99
99
|
ATTACHMENT_ACCEPT
|
|
100
|
-
} from "../chunk-
|
|
100
|
+
} from "../chunk-5GA3MKOC.js";
|
|
101
101
|
import {
|
|
102
102
|
DISPATCH_MAX_MEDIA_PARTS,
|
|
103
103
|
DISPATCH_MAX_PARTS,
|
|
@@ -115,8 +115,8 @@ import {
|
|
|
115
115
|
mentionInputToPart,
|
|
116
116
|
mentionKindForPath,
|
|
117
117
|
mentionPartsFromMessageParts
|
|
118
|
-
} from "../chunk-
|
|
119
|
-
import "../chunk-
|
|
118
|
+
} from "../chunk-FEUW4G2L.js";
|
|
119
|
+
import "../chunk-V3HO43PG.js";
|
|
120
120
|
import {
|
|
121
121
|
attachmentPartKey
|
|
122
122
|
} from "../chunk-5EPIPT4V.js";
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { a as WorkProductProvenance, d as WorkProductStorePort, e as WorkProductAuditEvent, b as WorkProductRecord, f as WorkProductArtifact, Q as QualityCheck, E as EvidenceEntry, g as ExceptionEntry, h as WorkProductStatus, c as WorkProductPersistedPart } from '../types-
|
|
2
|
-
export { A as AgentCheckInput, i as EvidenceLocator, j as ExceptionSeverity, P as ProfileBacktestSummary,
|
|
1
|
+
import { a as WorkProductProvenance, d as WorkProductStorePort, e as WorkProductAuditEvent, b as WorkProductRecord, f as WorkProductArtifact, Q as QualityCheck, E as EvidenceEntry, g as ExceptionEntry, h as WorkProductStatus, c as WorkProductPersistedPart } from '../types-DeEOhQbv.js';
|
|
2
|
+
export { A as AgentCheckInput, i as EvidenceLocator, j as EvidenceSpan, k as ExceptionSeverity, P as ProfileBacktestSummary, l as QuoteBasis, m as WorkProductParseResult, n as WorkProductPatch, W as WorkProductRef, o as WorkProductUpdateGuard, p as WorkProductVersionEntry, q as isWorkProductStatus, r as parseAgentCheckInput, s as parseArtifactInput, t as parseEvidenceInput, u as parseExceptionInput, v as persistedPartToWorkProduct, w as unresolvedBlockingExceptions, x as workProductToPersistedPart } from '../types-DeEOhQbv.js';
|
|
3
3
|
import { a as AppToolContext, c as AppToolDefinition } from '../types-BCxK0wyS.js';
|
|
4
4
|
import { JudgeVerdict } from '@tangle-network/agent-eval';
|
|
5
5
|
import { T as TrustItem } from '../trust-gate-Dcm5xSva.js';
|
|
6
|
-
export { R as ReviewQueueInputs, a as ReviewQueueItem, b as ReviewQueuePendingAsk, c as ReviewQueueState, d as ReviewQueueThread, p as parseReviewQueueItem, e as projectReviewQueue } from '../queue-
|
|
6
|
+
export { R as ReviewQueueInputs, a as ReviewQueueItem, b as ReviewQueuePendingAsk, c as ReviewQueueState, d as ReviewQueueThread, p as parseReviewQueueItem, e as projectReviewQueue } from '../queue-DBkulxW1.js';
|
|
7
7
|
|
|
8
8
|
/**
|
|
9
9
|
* The guarded work-product status machine — the `/missions` service PATTERN
|
|
@@ -242,8 +242,22 @@ interface WorkProductToolConfig {
|
|
|
242
242
|
* Omit the seam entirely and no quote is checked. */
|
|
243
243
|
readSourceText?: (ref: string, ctx: AppToolContext) => Promise<string | null>;
|
|
244
244
|
/** The material targets the platform coverage check requires evidence for.
|
|
245
|
-
* Product-owned vocabulary; omit to skip the coverage gate.
|
|
245
|
+
* Product-owned vocabulary; omit to skip the coverage gate.
|
|
246
|
+
*
|
|
247
|
+
* Return ONLY targets a source document can actually evidence. A gate that
|
|
248
|
+
* demands document lineage for a value the session COMPUTED is not
|
|
249
|
+
* satisfiable by any honest answer, and an unsatisfiable gate does not stop
|
|
250
|
+
* a submit — it selects for an invented one. Computed values belong to a
|
|
251
|
+
* product's own computation check, where "matches what we already
|
|
252
|
+
* calculated" is satisfiable by construction. */
|
|
246
253
|
materialTargets?: (artifact: WorkProductArtifact) => string[];
|
|
254
|
+
/** Require every material target to carry a SOURCE ANCHOR — a span-sliced or
|
|
255
|
+
* verified quote — not merely an evidence row. Off by default (a bare
|
|
256
|
+
* `claim` is legitimate lineage for products with no readable sources);
|
|
257
|
+
* turn it ON once `readSourceText` is wired and `materialTargets` names only
|
|
258
|
+
* document-derived targets, and coverage stops being satisfiable by
|
|
259
|
+
* assertion. */
|
|
260
|
+
requireAnchoredEvidence?: boolean;
|
|
247
261
|
/** Per-turn provenance closure the ROUTE supplies (profileHash + runId are
|
|
248
262
|
* known at dispatch; trusted, never read from model args). */
|
|
249
263
|
provenance: (ctx: AppToolContext) => WorkProductProvenanceBase;
|
|
@@ -292,6 +306,60 @@ declare function normalizeQuoteText(value: string): string;
|
|
|
292
306
|
* substring of every document and pass the gate vacuously.
|
|
293
307
|
*/
|
|
294
308
|
declare function sourceContainsQuote(sourceText: string, quote: string): boolean;
|
|
309
|
+
/**
|
|
310
|
+
* Slice a citation out of the source text by character offset — the reason
|
|
311
|
+
* this module exists in its stronger form.
|
|
312
|
+
*
|
|
313
|
+
* Verification above is a REJECTION gate: the model retypes a quote and the
|
|
314
|
+
* shell refuses it when the characters do not occur. That gate is correct and
|
|
315
|
+
* it works, but a model that reproduces a line character-for-character only
|
|
316
|
+
* some of the time cannot USE it — every miss is a refusal, and the package
|
|
317
|
+
* ends up with no lineage at all rather than false lineage. A measured 9 of 59
|
|
318
|
+
* on the live tax surface is what "some of the time" meant in practice.
|
|
319
|
+
*
|
|
320
|
+
* A span inverts it. The model names two integers into text it just read; the
|
|
321
|
+
* PLATFORM produces the quote from the bytes it already holds. There is no
|
|
322
|
+
* retyping step to get wrong, so a fabricated quote is not rejected — it is
|
|
323
|
+
* unrepresentable. `sourceContainsQuote(text, sliceSourceSpan(text, span))` is
|
|
324
|
+
* true for every span this function returns, by construction.
|
|
325
|
+
*
|
|
326
|
+
* Offsets index the SAME string the product's document-reading tool pages
|
|
327
|
+
* with an offset, which is the same string its `readSourceText` seam returns.
|
|
328
|
+
* That is the one contract a product must keep; violate it and spans point at
|
|
329
|
+
* the wrong characters (still real characters of that document — never
|
|
330
|
+
* invented text, but the wrong line).
|
|
331
|
+
*
|
|
332
|
+
* Half-open `[start, end)`, matching `String.prototype.slice` and the
|
|
333
|
+
* `offset`/`offset + text.length` window a paged read already reports.
|
|
334
|
+
*/
|
|
335
|
+
type SourceSpanFailure = {
|
|
336
|
+
reason: 'not_integer';
|
|
337
|
+
field: 'start' | 'end';
|
|
338
|
+
} | {
|
|
339
|
+
reason: 'negative';
|
|
340
|
+
field: 'start' | 'end';
|
|
341
|
+
} | {
|
|
342
|
+
reason: 'inverted';
|
|
343
|
+
} | {
|
|
344
|
+
reason: 'out_of_range';
|
|
345
|
+
totalChars: number;
|
|
346
|
+
} | {
|
|
347
|
+
reason: 'blank';
|
|
348
|
+
};
|
|
349
|
+
type SourceSpanResult = {
|
|
350
|
+
ok: true;
|
|
351
|
+
quote: string;
|
|
352
|
+
} | {
|
|
353
|
+
ok: false;
|
|
354
|
+
failure: SourceSpanFailure;
|
|
355
|
+
};
|
|
356
|
+
/** Resolve `[start, end)` against `sourceText`. Every rejection is a caller
|
|
357
|
+
* mistake the model can correct from the paged read it already has, so each
|
|
358
|
+
* carries the discriminator a tool layer turns into a specific message. */
|
|
359
|
+
declare function sliceSourceSpan(sourceText: string, span: {
|
|
360
|
+
start: number;
|
|
361
|
+
end: number;
|
|
362
|
+
}): SourceSpanResult;
|
|
295
363
|
|
|
296
364
|
/**
|
|
297
365
|
* Framework-neutral work-product review endpoints — the
|
|
@@ -382,4 +450,4 @@ interface WorkProductRoutes {
|
|
|
382
450
|
/** Create the work-product review endpoints over the store port and product seams */
|
|
383
451
|
declare function createWorkProductRoutes(options: WorkProductRoutesOptions): WorkProductRoutes;
|
|
384
452
|
|
|
385
|
-
export { type CreateWorkProductInput, EVIDENCE_COVERAGE_CHECK, EvidenceEntry, ExceptionEntry, type FinalizeWorkProductProvenanceInput, type InMemoryWorkProductStore, MAX_WORK_PRODUCT_BATCH, QUOTE_VERIFICATION_CHECK, QualityCheck, type SubmitWorkProductInput, TrustItem, WorkProductArtifact, WorkProductAuditEvent, type WorkProductAuthorizeArgs, type WorkProductOutcome, WorkProductPersistedPart, WorkProductProvenance, type WorkProductProvenanceBase, WorkProductRecord, type WorkProductRouteAuthorization, type WorkProductRoutes, type WorkProductRoutesOptions, type WorkProductService, type WorkProductServiceOptions, WorkProductStatus, WorkProductStorePort, type WorkProductToolConfig, type WorkProductVerdictBody, type WorkProductVerdictInput, buildWorkProductTools, canTransitionWorkProduct, createInMemoryWorkProductStore, createWorkProductRoutes, createWorkProductService, finalizeWorkProductProvenance, isWorkProductTerminal, normalizeQuoteText, sourceContainsQuote, stampProvenance, validateWorkProductVerdictBody, workProductTrustInputs };
|
|
453
|
+
export { type CreateWorkProductInput, EVIDENCE_COVERAGE_CHECK, EvidenceEntry, ExceptionEntry, type FinalizeWorkProductProvenanceInput, type InMemoryWorkProductStore, MAX_WORK_PRODUCT_BATCH, QUOTE_VERIFICATION_CHECK, QualityCheck, type SourceSpanFailure, type SourceSpanResult, type SubmitWorkProductInput, TrustItem, WorkProductArtifact, WorkProductAuditEvent, type WorkProductAuthorizeArgs, type WorkProductOutcome, WorkProductPersistedPart, WorkProductProvenance, type WorkProductProvenanceBase, WorkProductRecord, type WorkProductRouteAuthorization, type WorkProductRoutes, type WorkProductRoutesOptions, type WorkProductService, type WorkProductServiceOptions, WorkProductStatus, WorkProductStorePort, type WorkProductToolConfig, type WorkProductVerdictBody, type WorkProductVerdictInput, buildWorkProductTools, canTransitionWorkProduct, createInMemoryWorkProductStore, createWorkProductRoutes, createWorkProductService, finalizeWorkProductProvenance, isWorkProductTerminal, normalizeQuoteText, sliceSourceSpan, sourceContainsQuote, stampProvenance, validateWorkProductVerdictBody, workProductTrustInputs };
|