@tangle-network/agent-app 4.0.2 → 4.0.4

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.
Files changed (44) hide show
  1. package/dist/assistant/index.js +1 -1
  2. package/dist/chat-routes/draft-persistence.d.ts +7 -4
  3. package/dist/chat-routes/index.js +3 -3
  4. package/dist/{chunk-EI27JMS6.js → chunk-565M7QOK.js} +1 -1
  5. package/dist/chunk-565M7QOK.js.map +1 -0
  6. package/dist/{chunk-LBMFQLBS.js → chunk-DKEIQRKT.js} +4 -2
  7. package/dist/chunk-DKEIQRKT.js.map +1 -0
  8. package/dist/{chunk-XOHE6SKU.js → chunk-EK2Y55K4.js} +2 -137
  9. package/dist/chunk-EK2Y55K4.js.map +1 -0
  10. package/dist/{chunk-QVGDVY5U.js → chunk-I4MPG5T6.js} +2 -2
  11. package/dist/chunk-IJ6B5ZPU.js +141 -0
  12. package/dist/chunk-IJ6B5ZPU.js.map +1 -0
  13. package/dist/{chunk-SJKQUTGU.js → chunk-K4YIDNX5.js} +28 -6
  14. package/dist/chunk-K4YIDNX5.js.map +1 -0
  15. package/dist/{chunk-U2PTQCQ3.js → chunk-NKANJSKB.js} +2 -2
  16. package/dist/{chunk-EYPYU4PZ.js → chunk-QXPOBDPU.js} +7 -9
  17. package/dist/{chunk-EYPYU4PZ.js.map → chunk-QXPOBDPU.js.map} +1 -1
  18. package/dist/{chunk-W5YQZEE4.js → chunk-ROTSZSYZ.js} +2 -2
  19. package/dist/{chunk-JKYCXQFI.js → chunk-W2DIPVHW.js} +2 -2
  20. package/dist/conformance/cli.js +2 -2
  21. package/dist/conformance/index.js +2 -2
  22. package/dist/launch-invariants/cli.js +4 -3
  23. package/dist/launch-invariants/cli.js.map +1 -1
  24. package/dist/launch-invariants/index.js +3 -2
  25. package/dist/launch-invariants/index.js.map +1 -1
  26. package/dist/launch-invariants/testing.js +4 -3
  27. package/dist/operator/contract.d.ts +6 -0
  28. package/dist/operator/index.js +6 -1
  29. package/dist/operator/index.js.map +1 -1
  30. package/dist/preset-cloudflare/index.js +2 -2
  31. package/dist/public-consultation/index.js +2 -2
  32. package/dist/turn-health/index.js +5 -3
  33. package/dist/turn-health/index.js.map +1 -1
  34. package/dist/web-react/chat-message-body.d.ts +2 -2
  35. package/dist/web-react/index.js +1 -1
  36. package/package.json +1 -1
  37. package/dist/chunk-EI27JMS6.js.map +0 -1
  38. package/dist/chunk-LBMFQLBS.js.map +0 -1
  39. package/dist/chunk-SJKQUTGU.js.map +0 -1
  40. package/dist/chunk-XOHE6SKU.js.map +0 -1
  41. /package/dist/{chunk-QVGDVY5U.js.map → chunk-I4MPG5T6.js.map} +0 -0
  42. /package/dist/{chunk-U2PTQCQ3.js.map → chunk-NKANJSKB.js.map} +0 -0
  43. /package/dist/{chunk-W5YQZEE4.js.map → chunk-ROTSZSYZ.js.map} +0 -0
  44. /package/dist/{chunk-JKYCXQFI.js.map → chunk-W2DIPVHW.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 \"The assistant's model refused its access key, so this message was not answered.\",\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;A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AAG,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 \"The assistant's model refused its access key, so this message was not answered.\",\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;AAErB,QAAM,OAAO,uBAAuB,QAAQ,IAAI;AAEhD,SAAO;AAAA,IACL,MAAM,eAAe,MAAM;AACzB,YAAM,UAAU,oBAAoB;AAAA,QAClC,WAAW,KAAK;AAAA,QAChB,cAAc,KAAK,OAAO,gBAAgB;AAAA,QAC1C,YAAY,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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"]}
@@ -9,8 +9,8 @@ export declare function StreamingCaret(): import("react").JSX.Element;
9
9
  * run carries the streaming caret; if the last segment is instead a tool, a
10
10
  * trailing caret keeps the gap before the next run from looking frozen. Any
11
11
  * `toolCalls` not represented in `segments` (a partially-migrated producer that
12
- * set both) still render, so a tool row is never silently dropped. A settled
13
- * run of many tool calls collapses into one disclosure — see below. */
12
+ * set both) still render, so a tool row is never silently dropped. Long tool
13
+ * runs share a disclosure during streaming and after settlement. */
14
14
  export declare function SegmentedBody({ segments, msg, streaming, showCaret, renderBody, approval, onToolCallClick, toolRenderers, messageClassName, }: {
15
15
  segments: ChatMessageSegment[];
16
16
  msg: ChatUiMessage;
@@ -153,7 +153,7 @@ import {
153
153
  withoutRecordGridCreated,
154
154
  withoutRecordGridRemoved,
155
155
  withoutRecordGridUpdate
156
- } from "../chunk-EYPYU4PZ.js";
156
+ } from "../chunk-QXPOBDPU.js";
157
157
  import {
158
158
  useInfiniteScroll
159
159
  } from "../chunk-UHSUY6H6.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/agent-app",
3
- "version": "4.0.2",
3
+ "version": "4.0.4",
4
4
  "packageManager": "pnpm@11.28.8",
5
5
  "description": "Build agent applications with typed chat, tools, sandboxes, integrations, billing, and evaluation.",
6
6
  "keywords": [
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/operator/contract.ts","../src/operator/client.ts"],"sourcesContent":["/**\n * The standard operator API contract every agent app mounts at\n * `/api/operator/v1`. An outside agent (a Claude Code or Codex session, or\n * another app's agent) holds one scoped key per app and drives workspaces\n * through these routes; the app supplies only storage and execution.\n */\n\nimport type { ChatAttachmentInput } from '../chat-routes/wire.js'\n\nexport const OPERATOR_API_VERSION = 'v1'\nexport const OPERATOR_API_BASE_PATH = '/api/operator/v1'\n\n/** Key permissions, with the labels an app's API access page shows. */\nexport const OPERATOR_ACCESS = [\n {\n scope: 'operator:read',\n label: 'Read workspaces',\n description: 'Read workspaces, conversations, files, approvals, scorecards, and run status.',\n },\n {\n scope: 'operator:write',\n label: 'Create and edit',\n description: 'Create workspaces and conversations, and write files.',\n },\n {\n scope: 'operator:run',\n requires: ['operator:read'],\n label: 'Run agents',\n description: 'Requires read access. Start, continue, and interrupt agent turns, and answer their questions and tool-permission requests. Agents can modify workspace files. Uses your plan and budget.',\n },\n] as const\n\nexport type OperatorScope = typeof OPERATOR_ACCESS[number]['scope']\n\nexport const OPERATOR_API_SCOPES: readonly OperatorScope[] = OPERATOR_ACCESS.map(({ scope }) => scope)\n\nexport const OPERATOR_SCOPE_DEPENDENCIES: Readonly<Record<string, readonly string[]>> = Object.fromEntries(\n OPERATOR_ACCESS.flatMap((option) => 'requires' in option ? [[option.scope, option.requires]] : []),\n)\n\n/**\n * A key carrying one or more of these scopes reaches only the named\n * workspaces and cannot create workspaces. Keys without one keep the owner's\n * ordinary workspace access.\n */\nexport const OPERATOR_WORKSPACE_SCOPE_PREFIX = 'operator:workspace:'\n\nconst WORKSPACE_ID = /^[A-Za-z0-9_-]{1,128}$/\n\nexport function operatorWorkspaceScope(workspaceId: string): string {\n if (!WORKSPACE_ID.test(workspaceId)) throw new TypeError('Workspace ids contain only letters, digits, - and _')\n return `${OPERATOR_WORKSPACE_SCOPE_PREFIX}${workspaceId}`\n}\n\n/** The workspaces a key is restricted to, or null when it is unrestricted. A malformed restriction restricts to nothing. */\nexport function operatorKeyWorkspaces(scopes: readonly string[]): readonly string[] | null {\n const restricted = scopes.filter((scope) => scope.startsWith(OPERATOR_WORKSPACE_SCOPE_PREFIX))\n if (restricted.length === 0) return null\n return restricted\n .map((scope) => scope.slice(OPERATOR_WORKSPACE_SCOPE_PREFIX.length))\n .filter((id) => WORKSPACE_ID.test(id))\n}\n\nexport type OperatorRole = 'owner' | 'admin' | 'editor' | 'viewer'\n\nexport interface OperatorAppInfo {\n /** Stable app identifier, such as `gtm` or `tax`. */\n app: string\n name: string\n apiVersion: typeof OPERATOR_API_VERSION\n /** Optional operations this app implements; absent ones answer 501. */\n capabilities: OperatorCapability[]\n}\n\nexport type OperatorCapability =\n | 'turns.attachments'\n | 'turns.cancel'\n | 'workspaces.create'\n | 'threads.read'\n | 'files.read'\n | 'journal.read'\n | 'assets.read'\n | 'scorecard.read'\n\nexport interface OperatorPrincipalInfo {\n keyId: string\n scopes: string[]\n /** Workspaces the key is restricted to, or null for the owner's ordinary access. */\n workspaces: string[] | null\n}\n\nexport interface OperatorWorkspace {\n id: string\n name: string\n role?: OperatorRole\n /** Browser link for a person to open the workspace. */\n url?: string\n createdAt?: string\n}\n\nexport interface OperatorThread {\n id: string\n title: string\n updatedAt?: string\n url?: string\n}\n\n/**\n * `succeeded` and `failed` are settled. `input-required` waits on a person or\n * an operator decision listed in `approvals`. `unknown` means the app cannot\n * establish the state; it is never evidence of success.\n */\nexport type OperatorTurnState = 'queued' | 'working' | 'input-required' | 'succeeded' | 'failed' | 'unknown'\n\nexport const OPERATOR_SETTLED_STATES: readonly OperatorTurnState[] = ['succeeded', 'failed']\n\n/** `failure.code` of a turn that settled because it was cancelled before it finished. */\nexport const OPERATOR_TURN_CANCELLED_CODE = 'turn.cancelled'\n\nexport interface OperatorAssetRef {\n id: string\n /** Root-relative operator route that returns the bytes. */\n path: string\n mediaType?: string\n name?: string\n}\n\nexport interface OperatorFileChange {\n path: string\n action: 'created' | 'updated' | 'deleted' | 'changed'\n}\n\nexport type OperatorApprovalKind = 'question' | 'permission' | 'plan' | 'hub' | 'asset' | 'review'\n\nexport interface OperatorApproval {\n id: string\n kind: OperatorApprovalKind\n title: string\n detail?: string\n threadId?: string\n /** Browser link where an authorized person decides it. */\n url?: string\n createdAt?: string\n expiresAt?: string\n /** Who can decide: an operator key with run access, an editor, or the workspace owner. */\n decidedBy: 'operator' | 'editor' | 'owner'\n}\n\nexport interface OperatorTurn {\n workspaceId: string\n threadId: string\n turnId: string\n state: OperatorTurnState\n url?: string\n executionId?: string\n model?: string\n costUsd?: number\n /** The harness's own reported token cost, kept when the ledger charged nothing (a failed turn). */\n harnessCostUsd?: number\n /** Producer-recorded basis for costUsd; catalog is an estimate, ledger is settlement evidence. */\n costSource?: 'ledger' | 'catalog' | 'reported' | 'unreported' | 'subscription'\n /** Producer-recorded billing path, not the identity of a payer. */\n billingOwner?: 'router' | 'sandbox-router' | 'subscription'\n /** Producer-recorded credential path; never inferred from costUsd or billingOwner. */\n credentialSource?: 'router' | 'subscription'\n /** Opaque producer settlement reference; its presence alone does not prove a charge or zero provider cost. */\n settlementRecord?: string\n /**\n * Token usage the app stored on the turn's reply; `operatorTurnUsage` maps\n * a chat-store row to it.\n * - `inputTokens`: prompt tokens NOT read from the provider's cache. Unlike\n * the turn trace's summary, it never includes cache reads; it is omitted\n * when the row's split is ambiguous, including when the row records no\n * cache count (see `operatorTurnUsage`).\n * - `cachedInputTokens`: prompt tokens read from the provider's cache (the\n * row's `cacheReadTokens`); with both present the whole prompt is\n * `inputTokens + cachedInputTokens`. When absent the cache share is unknown.\n * - `outputTokens`: completion tokens.\n * Each field is present only when known; never a guessed zero.\n */\n usage?: { inputTokens?: number; cachedInputTokens?: number; outputTokens?: number }\n completedAt?: string\n /** The settled answer; null until the turn settles. */\n reply: { content: string; mediaType: string } | null\n failure: { code?: string; message: string } | null\n assets: OperatorAssetRef[]\n files: OperatorFileChange[]\n /** Decisions open on this turn's conversation. */\n approvals: OperatorApproval[]\n}\n\nexport interface OperatorJournalEntry {\n path: string\n /** `YYYY-MM-DD` the entry belongs to. */\n date: string\n title?: string\n updatedAt?: string\n}\n\nexport interface OperatorFileEntry {\n path: string\n updatedAt?: string\n bytes?: number\n}\n\nexport interface OperatorFile {\n path: string\n content: string\n mediaType: string\n revision?: string\n}\n\nexport interface OperatorMetric {\n key: string\n label: string\n /** Null when the app has no measurement; never a guessed zero. */\n value: number | null\n unit: 'count' | 'usd' | 'ratio' | 'ms'\n note?: string\n}\n\nexport interface OperatorScorecard {\n workspaceId: string\n generatedAt: string\n window: { start: string; end: string; days: number }\n /** Work the agent did in the window. */\n metrics: OperatorMetric[]\n /** Business results recorded in the window, such as clicks, signups, or replies. */\n outcomes: OperatorMetric[]\n /** How the numbers are measured and what they exclude. */\n measurement: string\n}\n\nexport interface OperatorErrorBody {\n error: string\n code: string\n retryable?: boolean\n}\n\nexport interface StartTurnInput {\n /** Client-generated UUID. Reuse it to retry the same turn; it never starts twice. */\n turnId: string\n content: string\n /** Continue this conversation; omitted starts a new one. */\n threadId?: string\n /** Title for a new conversation. */\n title?: string\n model?: string\n /**\n * Files uploaded to this workspace ahead of the turn, as the app's\n * attachment upload route returned them in `{ files }`. They reach the\n * agent exactly as browser-composer attachments do; the app re-checks each\n * path against the workspace's own store. At most the app's\n * `maxAttachments` entries, `ATTACHMENT_MAX_COUNT` (`/chat-routes`) unless\n * the app sets one. Apps without the `turns.attachments` capability refuse\n * them.\n */\n attachments?: ChatAttachmentInput[]\n}\n\n/** Route table: method, path pattern under the base path, and required scopes. */\nexport const OPERATOR_ROUTES = [\n { id: 'describe', method: 'GET', path: '', scopes: ['operator:read'] },\n { id: 'workspaces.list', method: 'GET', path: '/workspaces', scopes: ['operator:read'] },\n { id: 'workspaces.create', method: 'POST', path: '/workspaces', scopes: ['operator:write'] },\n { id: 'workspaces.get', method: 'GET', path: '/workspaces/:workspaceId', scopes: ['operator:read'] },\n { id: 'turns.start', method: 'POST', path: '/workspaces/:workspaceId/turns', scopes: ['operator:read', 'operator:run'] },\n { id: 'threads.list', method: 'GET', path: '/workspaces/:workspaceId/threads', scopes: ['operator:read'] },\n { id: 'threads.get', method: 'GET', path: '/workspaces/:workspaceId/threads/:threadId', scopes: ['operator:read'] },\n { id: 'turns.get', method: 'GET', path: '/workspaces/:workspaceId/threads/:threadId/turns/:turnId', scopes: ['operator:read'] },\n { id: 'turns.cancel', method: 'POST', path: '/workspaces/:workspaceId/threads/:threadId/turns/:turnId/cancel', scopes: ['operator:read', 'operator:run'] },\n { id: 'approvals.list', method: 'GET', path: '/workspaces/:workspaceId/approvals', scopes: ['operator:read'] },\n { id: 'journal.list', method: 'GET', path: '/workspaces/:workspaceId/journal', scopes: ['operator:read'] },\n { id: 'files.list', method: 'GET', path: '/workspaces/:workspaceId/files', scopes: ['operator:read'] },\n { id: 'files.read', method: 'GET', path: '/workspaces/:workspaceId/file', scopes: ['operator:read'] },\n { id: 'assets.read', method: 'GET', path: '/workspaces/:workspaceId/assets/:assetId', scopes: ['operator:read'] },\n { id: 'scorecard.get', method: 'GET', path: '/workspaces/:workspaceId/scorecard', scopes: ['operator:read'] },\n] as const satisfies ReadonlyArray<{ id: string; method: 'GET' | 'POST'; path: string; scopes: readonly OperatorScope[] }>\n\nexport type OperatorRouteId = typeof OPERATOR_ROUTES[number]['id']\n\nconst SEGMENT = /^[A-Za-z0-9_:.%-]{1,256}$/\n\n/** Match a pathname under the base path to its route and decoded parameters. */\nexport function matchOperatorRoute(\n method: string,\n pathname: string,\n basePath: string = OPERATOR_API_BASE_PATH,\n): { route: typeof OPERATOR_ROUTES[number]; params: Record<string, string> } | null {\n if (pathname !== basePath && !pathname.startsWith(`${basePath}/`)) return null\n const rest = pathname.slice(basePath.length).replace(/\\/$/, '')\n const actual = rest ? rest.split('/').slice(1) : []\n for (const route of OPERATOR_ROUTES) {\n if (route.method !== method) continue\n const pattern = route.path ? route.path.split('/').slice(1) : []\n if (pattern.length !== actual.length) continue\n const params: Record<string, string> = {}\n let matched = true\n for (let index = 0; index < pattern.length; index++) {\n const expected = pattern[index]!\n const segment = actual[index]!\n if (expected.startsWith(':')) {\n if (!SEGMENT.test(segment)) { matched = false; break }\n let decoded: string\n try { decoded = decodeURIComponent(segment) } catch { matched = false; break }\n if (!decoded || decoded.includes('/')) { matched = false; break }\n params[expected.slice(1)] = decoded\n } else if (expected !== segment) {\n matched = false\n break\n }\n }\n if (matched) return { route, params }\n }\n return null\n}\n","import { createApiKeyFetch } from '../web/api-key-fetch.js'\nimport {\n OPERATOR_API_BASE_PATH,\n type OperatorApproval,\n type OperatorAppInfo,\n type OperatorErrorBody,\n type OperatorFile,\n type OperatorFileEntry,\n type OperatorJournalEntry,\n type OperatorPrincipalInfo,\n type OperatorScorecard,\n type OperatorThread,\n type OperatorTurn,\n type OperatorWorkspace,\n type StartTurnInput,\n} from './contract.js'\n\nexport type OperatorResult<T> =\n | { succeeded: true; value: T }\n | { succeeded: false; status: number; code: string; error: string; retryable: boolean }\n\nexport interface OperatorClientOptions {\n /** The app's origin, such as `https://gtm.tangle.tools`. */\n origin: string\n /** Resolve the key from trusted secret storage on each request; never from model output. */\n getApiKey(): string | Promise<string>\n fetchImpl?: typeof fetch\n allowHttpLoopback?: boolean\n basePath?: string\n}\n\nexport interface WaitForTurnOptions {\n /** Total time to follow the turn. */\n timeoutMs: number\n /** Server hold per request, in seconds; the server caps it. */\n waitSeconds?: number\n signal?: AbortSignal\n}\n\nexport interface OperatorClient {\n describe(): Promise<OperatorResult<{ app: OperatorAppInfo; principal: OperatorPrincipalInfo }>>\n listWorkspaces(): Promise<OperatorResult<OperatorWorkspace[]>>\n createWorkspace(input: { name: string }): Promise<OperatorResult<OperatorWorkspace>>\n getWorkspace(workspaceId: string): Promise<OperatorResult<OperatorWorkspace>>\n /** Omitting turnId generates one; retry with the returned turn's id. */\n startTurn(workspaceId: string, input: Omit<StartTurnInput, 'turnId'> & { turnId?: string }): Promise<OperatorResult<OperatorTurn>>\n getTurn(workspaceId: string, threadId: string, turnId: string, options?: { waitSeconds?: number; signal?: AbortSignal }): Promise<OperatorResult<OperatorTurn>>\n /**\n * Stop a turn. A settled turn comes back as it settled; otherwise the app\n * has been asked to stop it, and the server holds up to `waitSeconds` for\n * the turn to settle `failed` with `OPERATOR_TURN_CANCELLED_CODE`. Read it\n * with `getTurn` or `waitForTurn` until it settles.\n */\n cancelTurn(workspaceId: string, threadId: string, turnId: string, options?: { waitSeconds?: number; signal?: AbortSignal }): Promise<OperatorResult<OperatorTurn>>\n /** Follow until the turn settles, waits on a decision, or the timeout passes; the last read is returned. */\n waitForTurn(workspaceId: string, threadId: string, turnId: string, options: WaitForTurnOptions): Promise<OperatorResult<OperatorTurn>>\n listThreads(workspaceId: string, query?: { cursor?: string; limit?: number }): Promise<OperatorResult<{ threads: OperatorThread[]; nextCursor: string | null }>>\n getThread(workspaceId: string, threadId: string): Promise<OperatorResult<{ thread: OperatorThread; latestTurn: OperatorTurn | null }>>\n listApprovals(workspaceId: string): Promise<OperatorResult<OperatorApproval[]>>\n listJournal(workspaceId: string, query?: { days?: number }): Promise<OperatorResult<OperatorJournalEntry[]>>\n listFiles(workspaceId: string, query?: { prefix?: string }): Promise<OperatorResult<OperatorFileEntry[]>>\n readFile(workspaceId: string, path: string): Promise<OperatorResult<OperatorFile>>\n /** The raw asset response; the caller reads and bounds its body. */\n readAsset(workspaceId: string, assetId: string, init?: { signal?: AbortSignal }): Promise<OperatorResult<Response>>\n getScorecard(workspaceId: string, query?: { days?: number }): Promise<OperatorResult<OperatorScorecard>>\n}\n\nfunction segment(value: string): string {\n return encodeURIComponent(value)\n}\n\nasync function failure(response: Response): Promise<OperatorResult<never>> {\n let body: Partial<OperatorErrorBody> = {}\n try { body = await response.json() as Partial<OperatorErrorBody> } catch { /* A non-JSON refusal keeps its status. */ }\n return {\n succeeded: false,\n status: response.status,\n code: typeof body.code === 'string' ? body.code : `http_${response.status}`,\n error: typeof body.error === 'string' ? body.error : `HTTP ${response.status}`,\n retryable: body.retryable === true || response.status === 429 || response.status >= 500,\n }\n}\n\nfunction transportFailure(error: unknown): OperatorResult<never> {\n const aborted = error instanceof Error && error.name === 'AbortError'\n return {\n succeeded: false,\n status: 0,\n code: aborted ? 'operator.aborted' : 'operator.transport_failed',\n // createApiKeyFetch never forwards transport diagnostics, which could carry the key.\n error: error instanceof Error ? error.message : 'Operator transport failed',\n retryable: !aborted,\n }\n}\n\nconst SETTLED = new Set(['succeeded', 'failed', 'input-required'])\n\n/** A typed client for one app's operator API. */\nexport function createOperatorClient(options: OperatorClientOptions): OperatorClient {\n const basePath = (options.basePath ?? OPERATOR_API_BASE_PATH).replace(/\\/$/, '')\n const request = createApiKeyFetch({\n origin: options.origin,\n getApiKey: options.getApiKey,\n ...(options.fetchImpl ? { fetchImpl: options.fetchImpl } : {}),\n ...(options.allowHttpLoopback ? { allowHttpLoopback: true } : {}),\n })\n\n async function call<T>(\n path: string,\n pick: (body: Record<string, unknown>) => T,\n init: RequestInit = {},\n ): Promise<OperatorResult<T>> {\n let response: Response\n try {\n response = await request(`${basePath}${path}`, {\n ...init,\n headers: { accept: 'application/json', ...(init.body ? { 'content-type': 'application/json' } : {}) },\n })\n } catch (error) {\n return transportFailure(error)\n }\n if (!response.ok) return failure(response)\n try {\n return { succeeded: true, value: pick(await response.json() as Record<string, unknown>) }\n } catch {\n return { succeeded: false, status: response.status, code: 'operator.invalid_response', error: 'The response was not the expected JSON', retryable: true }\n }\n }\n\n const query = (params: Record<string, string | number | undefined>) => {\n const search = new URLSearchParams()\n for (const [name, value] of Object.entries(params)) if (value !== undefined && value !== '') search.set(name, String(value))\n const text = search.toString()\n return text ? `?${text}` : ''\n }\n\n const client: OperatorClient = {\n describe: () => call('', (body) => body as unknown as { app: OperatorAppInfo; principal: OperatorPrincipalInfo }),\n listWorkspaces: () => call('/workspaces', (body) => body.workspaces as OperatorWorkspace[]),\n createWorkspace: (input) => call('/workspaces', (body) => body.workspace as OperatorWorkspace, {\n method: 'POST', body: JSON.stringify({ name: input.name }),\n }),\n getWorkspace: (workspaceId) => call(`/workspaces/${segment(workspaceId)}`, (body) => body.workspace as OperatorWorkspace),\n startTurn: (workspaceId, input) => call(`/workspaces/${segment(workspaceId)}/turns`, (body) => body.turn as OperatorTurn, {\n method: 'POST', body: JSON.stringify({ ...input, turnId: input.turnId ?? crypto.randomUUID() }),\n }),\n getTurn: (workspaceId, threadId, turnId, opts = {}) => call(\n `/workspaces/${segment(workspaceId)}/threads/${segment(threadId)}/turns/${segment(turnId)}${query({ wait: opts.waitSeconds })}`,\n (body) => body.turn as OperatorTurn,\n opts.signal ? { signal: opts.signal } : {},\n ),\n cancelTurn: (workspaceId, threadId, turnId, opts = {}) => call(\n `/workspaces/${segment(workspaceId)}/threads/${segment(threadId)}/turns/${segment(turnId)}/cancel${query({ wait: opts.waitSeconds })}`,\n (body) => body.turn as OperatorTurn,\n { method: 'POST', ...(opts.signal ? { signal: opts.signal } : {}) },\n ),\n async waitForTurn(workspaceId, threadId, turnId, opts) {\n const deadline = Date.now() + opts.timeoutMs\n const waitSeconds = opts.waitSeconds ?? 25\n let last: OperatorResult<OperatorTurn> | null = null\n while (true) {\n const remaining = Math.floor((deadline - Date.now()) / 1000)\n const started = Date.now()\n last = await client.getTurn(workspaceId, threadId, turnId, {\n waitSeconds: Math.max(0, Math.min(waitSeconds, remaining)),\n ...(opts.signal ? { signal: opts.signal } : {}),\n })\n if (!last.succeeded) {\n if (!last.retryable || Date.now() >= deadline || opts.signal?.aborted) return last\n await new Promise((resolve) => setTimeout(resolve, Math.min(5_000, Math.max(0, deadline - Date.now()))))\n continue\n }\n if (SETTLED.has(last.value.state) || last.value.approvals.length > 0) return last\n if (Date.now() >= deadline || opts.signal?.aborted) return last\n // A server that does not hold the read still gets a bounded request rate.\n if (Date.now() - started < 1_000) {\n await new Promise((resolve) => setTimeout(resolve, Math.min(2_000, Math.max(0, deadline - Date.now()))))\n }\n }\n },\n listThreads: (workspaceId, q = {}) => call(\n `/workspaces/${segment(workspaceId)}/threads${query({ cursor: q.cursor, limit: q.limit })}`,\n (body) => ({ threads: body.threads as OperatorThread[], nextCursor: (body.nextCursor as string | null) ?? null }),\n ),\n getThread: (workspaceId, threadId) => call(\n `/workspaces/${segment(workspaceId)}/threads/${segment(threadId)}`,\n (body) => ({ thread: body.thread as OperatorThread, latestTurn: (body.latestTurn as OperatorTurn | null) ?? null }),\n ),\n listApprovals: (workspaceId) => call(`/workspaces/${segment(workspaceId)}/approvals`, (body) => body.approvals as OperatorApproval[]),\n listJournal: (workspaceId, q = {}) => call(\n `/workspaces/${segment(workspaceId)}/journal${query({ days: q.days })}`,\n (body) => body.entries as OperatorJournalEntry[],\n ),\n listFiles: (workspaceId, q = {}) => call(\n `/workspaces/${segment(workspaceId)}/files${query({ prefix: q.prefix })}`,\n (body) => body.files as OperatorFileEntry[],\n ),\n readFile: (workspaceId, path) => call(\n `/workspaces/${segment(workspaceId)}/file${query({ path })}`,\n (body) => body.file as OperatorFile,\n ),\n async readAsset(workspaceId, assetId, init = {}) {\n let response: Response\n try {\n response = await request(`${basePath}/workspaces/${segment(workspaceId)}/assets/${segment(assetId)}`, init.signal ? { signal: init.signal } : {})\n } catch (error) {\n return transportFailure(error)\n }\n if (!response.ok) return failure(response)\n return { succeeded: true, value: response }\n },\n getScorecard: (workspaceId, q = {}) => call(\n `/workspaces/${segment(workspaceId)}/scorecard${query({ days: q.days })}`,\n (body) => body.scorecard as OperatorScorecard,\n ),\n }\n return client\n}\n"],"mappings":";;;;;AASO,IAAM,uBAAuB;AAC7B,IAAM,yBAAyB;AAG/B,IAAM,kBAAkB;AAAA,EAC7B;AAAA,IACE,OAAO;AAAA,IACP,OAAO;AAAA,IACP,aAAa;AAAA,EACf;AAAA,EACA;AAAA,IACE,OAAO;AAAA,IACP,OAAO;AAAA,IACP,aAAa;AAAA,EACf;AAAA,EACA;AAAA,IACE,OAAO;AAAA,IACP,UAAU,CAAC,eAAe;AAAA,IAC1B,OAAO;AAAA,IACP,aAAa;AAAA,EACf;AACF;AAIO,IAAM,sBAAgD,gBAAgB,IAAI,CAAC,EAAE,MAAM,MAAM,KAAK;AAE9F,IAAM,8BAA2E,OAAO;AAAA,EAC7F,gBAAgB,QAAQ,CAAC,WAAW,cAAc,SAAS,CAAC,CAAC,OAAO,OAAO,OAAO,QAAQ,CAAC,IAAI,CAAC,CAA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O,SAAS;AAAA,IAC5C;AAAA,IACA,cAAc,CAAC,aAAa,IAAI,CAAC,MAAM;AAAA,MACrC,eAAe,QAAQ,WAAW,CAAC,aAAa,MAAM,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC;AAAA,MACvE,CAAC,SAAS,KAAK;AAAA,IACjB;AAAA,EACF;AACA,SAAO;AACT;","names":["segment"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/conformance/session.ts","../src/conformance/revision.ts","../src/conformance/turns.ts","../src/conformance/run.ts"],"sourcesContent":["/**\n * Sign-in for the conformance runner: the two ways a member reaches an agent app, and one question both answer,\n * \"does the app accept this session?\". Nothing here is specific to an app; a product whose sign-in differs\n * fails the check with the status it answered.\n */\n\nexport type SignInMode = 'password' | 'sso'\n\n/** A check failed for a reason worth reporting; its message is the cause. */\nexport class Failure extends Error {}\n\nexport interface MemberSession {\n origin: string\n /** A request to the app as the signed-in member; `path` is root-relative. */\n fetch(path: string, init?: RequestInit): Promise<Response>\n}\n\nconst REQUEST_MS = 30_000\n\n/** Cookies by origin: enough of a jar for one sign-in and the calls after it. */\nclass Jar {\n private readonly byOrigin = new Map<string, Map<string, string>>()\n\n header(url: string): string {\n return [...(this.byOrigin.get(new URL(url).origin) ?? [])].map(([name, value]) => `${name}=${value}`).join('; ')\n }\n\n async send(url: string, init: RequestInit = {}): Promise<Response> {\n const headers = new Headers(init.headers)\n const cookie = this.header(url)\n if (cookie) headers.set('cookie', cookie)\n const response = await fetch(url, { ...init, headers, redirect: 'manual', signal: init.signal ?? AbortSignal.timeout(REQUEST_MS) })\n this.absorb(url, response)\n return response\n }\n\n private absorb(url: string, response: Response): void {\n const origin = new URL(url).origin\n const jar = this.byOrigin.get(origin) ?? new Map<string, string>()\n for (const line of response.headers.getSetCookie()) {\n const [pair = '', ...attributes] = line.split(';')\n const eq = pair.indexOf('=')\n if (eq < 1) continue\n const name = pair.slice(0, eq).trim()\n const value = pair.slice(eq + 1).trim()\n const attribute = (key: string) => attributes.map(item => item.trim()).find(item => item.toLowerCase().startsWith(`${key}=`))?.slice(key.length + 1)\n const maxAge = attribute('max-age')\n const expires = attribute('expires')\n const gone = !value || (maxAge !== undefined && Number(maxAge) <= 0)\n || (maxAge === undefined && expires !== undefined && Date.parse(expires) <= Date.now())\n if (gone) jar.delete(name)\n else jar.set(name, value)\n }\n this.byOrigin.set(origin, jar)\n }\n}\n\nconst snippet = async (response: Response) => (await response.text().catch(() => '')).replace(/\\s+/g, ' ').slice(0, 160)\n\n/** A sign-in POST. An auth service that answers 429 is asked again after its Retry-After (at most 20 s), twice at most. */\nasync function postSignIn(jar: Jar, origin: string, email: string, password: string): Promise<Response> {\n for (let attempt = 0; ; attempt += 1) {\n const response = await jar.send(`${origin}/api/auth/sign-in/email`, {\n method: 'POST', headers: { 'content-type': 'application/json', origin }, body: JSON.stringify({ email, password }),\n })\n if (response.status !== 429 || attempt === 2) return response\n const wait = Number(response.headers.get('retry-after'))\n await response.body?.cancel().catch(() => {})\n await new Promise(resolve => setTimeout(resolve, Math.min(20, Number.isFinite(wait) && wait > 0 ? wait : 5) * 1000))\n }\n}\n\nasync function passwordSignIn(jar: Jar, origin: string, email: string, password: string): Promise<void> {\n const response = await postSignIn(jar, origin, email, password)\n if (response.status !== 200) throw new Failure(`password sign-in answered ${response.status}: ${await snippet(response)}`)\n}\n\nconst TANGLE_AUTH_PATH = /(^|\\/)auth\\/tangle\\//\n\n/**\n * The app's \"Log in with Tangle\": its start route sends the browser to Platform, Platform signs the member in and\n * authorizes, and the app's callback sets its own session. Apps mount the start route at `/auth/tangle/start` or\n * under `/api`.\n */\nasync function ssoSignIn(jar: Jar, origin: string, email: string, password: string): Promise<void> {\n const answers: string[] = []\n let location: string | null = null\n for (const path of ['/auth/tangle/start', '/api/auth/tangle/start']) {\n const start = await jar.send(`${origin}${path}`)\n location = start.headers.get('location')\n if (location) break\n answers.push(`${path} answered ${start.status}`)\n }\n if (!location) throw new Failure(`SSO start sent the member nowhere (${answers.join('; ')})`)\n const authorize = new URL(location, origin)\n const platform = authorize.origin\n const member = await postSignIn(jar, platform, email, password)\n if (member.status !== 200) throw new Failure(`Platform sign-in answered ${member.status}: ${await snippet(member)}`)\n let next = authorize.href\n for (let hop = 0; hop < 8; hop += 1) {\n const response = await jar.send(next)\n const redirect = response.headers.get('location')\n if (!redirect) throw new Failure(`SSO stopped at ${new URL(next).pathname} with ${response.status}`)\n const url = new URL(redirect, next)\n if (url.origin === origin && !TANGLE_AUTH_PATH.test(url.pathname)) {\n if (url.pathname.startsWith('/login') || url.searchParams.has('error') || url.searchParams.get('connection') === 'failed') {\n throw new Failure(`the app's SSO callback sent the member to ${url.pathname}${url.search.slice(0, 80)}`)\n }\n return\n }\n next = url.href\n }\n throw new Failure('SSO did not return to the app within 8 redirects')\n}\n\n/** A redirect to sign-in or an error page is an app that did not accept the session. */\nasync function sessionAccepted(session: MemberSession): Promise<string> {\n const who = await session.fetch('/api/auth/get-session')\n if (who.status === 200) {\n const body = await who.json().catch(() => null) as { user?: { id?: unknown } } | null\n if (typeof body?.user?.id === 'string' && body.user.id) return 'GET /api/auth/get-session returned the user'\n }\n const workspaces = await session.fetch('/api/workspaces')\n if (workspaces.status === 200) return 'GET /api/workspaces answered 200 as the member'\n throw new Failure(`signed in, but the app does not accept the session: GET /api/auth/get-session answered ${who.status}, GET /api/workspaces ${workspaces.status}`)\n}\n\n/** Signs in and proves the app accepts the session; the detail names the proof. */\nexport async function signIn(input: { origin: string; mode: SignInMode; email: string; password: string }): Promise<{ session: MemberSession; detail: string }> {\n const jar = new Jar()\n if (input.mode === 'password') await passwordSignIn(jar, input.origin, input.email, input.password)\n else await ssoSignIn(jar, input.origin, input.email, input.password)\n const session: MemberSession = {\n origin: input.origin,\n fetch: (path, init = {}) => {\n const headers = new Headers(init.headers)\n if (!headers.has('origin')) headers.set('origin', input.origin)\n return jar.send(`${input.origin}${path}`, { ...init, headers })\n },\n }\n return { session, detail: `${input.mode}: ${await sessionAccepted(session)}` }\n}\n","/**\n * The served revision, read the way an operator reads it: from the app's own `GET /api/health` body, or from the\n * `x-<app>-revision` / `x-<app>-version` header the app puts on its responses. An app that serves neither cannot\n * say what it is running, so a release cannot be told from the one before it.\n */\n\nimport { Failure } from './session.js'\n\nconst REVISION_HEADER = /^x-[a-z0-9-]+-(revision|version)$/i\nconst REQUEST_MS = 20_000\n\nconst text = (value: unknown): string | null => typeof value === 'string' && value.trim() ? value.trim() : null\n\n/** The revision a health body carries: `revision`, or what `release` carries. */\nfunction fromHealth(body: unknown): string | null {\n if (!body || typeof body !== 'object') return null\n const record = body as Record<string, unknown>\n const release = record.release && typeof record.release === 'object' ? record.release as Record<string, unknown> : {}\n return text(record.revision) ?? text(release.revision) ?? text(release.sha) ?? text(release.tag)\n}\n\nfunction fromHeaders(response: Response): { name: string; value: string } | null {\n for (const [name, value] of response.headers) if (REVISION_HEADER.test(name) && value.trim()) return { name, value: value.trim() }\n return null\n}\n\n/**\n * Reads the revision, or throws a Failure naming every place it looked. `source` says where it was read, e.g.\n * `GET /api/health` or `GET / x-creative-revision`.\n */\nexport async function readRevision(origin: string, expect?: string): Promise<{ revision: string; source: string }> {\n const looked: string[] = []\n const found = await (async (): Promise<{ revision: string; source: string } | null> => {\n for (const path of ['/api/health', '/']) {\n let response: Response\n try {\n response = await fetch(`${origin}${path}`, { headers: { accept: 'application/json' }, redirect: 'manual', signal: AbortSignal.timeout(REQUEST_MS) })\n } catch (error) {\n looked.push(`GET ${path} failed (${error instanceof Error ? error.name : 'error'})`)\n continue\n }\n const header = fromHeaders(response)\n if (path === '/api/health' && response.ok) {\n const revision = fromHealth(await response.json().catch(() => null))\n if (revision) return { revision, source: 'GET /api/health' }\n }\n if (header) return { revision: header.value, source: `GET ${path} ${header.name}` }\n await response.body?.cancel().catch(() => {})\n looked.push(`GET ${path} answered ${response.status} without a revision`)\n }\n return null\n })()\n if (!found) throw new Failure(`the app serves no readable revision (${looked.join('; ')})`)\n if (expect) {\n const [a, b] = [found.revision.toLowerCase(), expect.trim().toLowerCase()]\n if (b.length < 7 || !(a.startsWith(b) || b.startsWith(a))) {\n throw new Failure(`the app serves revision ${found.revision} (${found.source}), not the expected ${expect}`)\n }\n }\n return found\n}\n","/**\n * The conformance turns, run through the operator API every agent app mounts the same way\n * (docs/operator-api.md), so one runner drives every product. The verdict is the settled turn the app stored.\n *\n * plain a reply with text;\n * computer a turn only the workspace computer can answer: either the digest of a fresh nonce, which the model\n * cannot know without running the command, or a file the computer saves that the app then serves back.\n */\n\nimport { createHash, randomBytes, randomUUID } from 'node:crypto'\nimport { createOperatorClient, type OperatorClient } from '../operator/client.js'\nimport type { OperatorTurn, OperatorWorkspace } from '../operator/contract.js'\nimport { Failure, type MemberSession } from './session.js'\n\nexport type ComputerProof = 'digest' | 'file'\n\nconst REQUEST_MS = 30_000\nconst KEY_LIFETIME_MS = 60 * 60_000\n\nexport interface OperatorAccess {\n client: OperatorClient\n workspace: OperatorWorkspace\n /** The app's own account of what the key may do. */\n scopes: readonly string[]\n}\n\n/** An expiring key for the signed-in member, through the route every app's API access page uses. */\nexport async function mintKey(session: MemberSession): Promise<{ id: string; key: string }> {\n const response = await session.fetch('/api/keys', {\n method: 'POST', headers: { 'content-type': 'application/json' }, signal: AbortSignal.timeout(REQUEST_MS),\n body: JSON.stringify({\n name: `conformance ${new Date().toISOString()}`, scopes: ['operator:read', 'operator:run'],\n expiresAt: new Date(Date.now() + KEY_LIFETIME_MS).toISOString(), workspaceIds: [],\n }),\n })\n if (response.status === 404) {\n throw new Failure('the app has no key route (POST /api/keys answered 404), so a conformance turn has no credential; give it an operator key')\n }\n const body = await response.json().catch(() => null) as { id?: unknown; key?: unknown; error?: unknown } | null\n if (!response.ok || typeof body?.id !== 'string' || typeof body.key !== 'string') {\n throw new Failure(`POST /api/keys answered ${response.status}: ${typeof body?.error === 'string' ? body.error.slice(0, 160) : 'no key in the response'}`)\n }\n return { id: body.id, key: body.key }\n}\n\n/** Revokes a key this run created. Apps accept the id in the path, or in the body of the collection route. */\nexport async function revokeKey(session: MemberSession, id: string): Promise<void> {\n const byPath = await session.fetch(`/api/keys/${encodeURIComponent(id)}`, { method: 'DELETE', signal: AbortSignal.timeout(REQUEST_MS) })\n if (byPath.ok) return\n const byBody = await session.fetch('/api/keys', {\n method: 'DELETE', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ id }), signal: AbortSignal.timeout(REQUEST_MS),\n })\n if (byBody.ok) return\n throw new Failure(`the minted key ${id} was not revoked: DELETE /api/keys/:id answered ${byPath.status}, DELETE /api/keys ${byBody.status} (it expires within the hour)`)\n}\n\n/**\n * Opens the operator API with `key` and picks the workspace the turns run in: `workspace` is its id or exact name,\n * and omitted, the key must reach exactly one. `requestMs` bounds any one request, a held turn read included.\n */\nexport async function openOperatorAccess(\n { origin, key, workspace, requestMs }: { origin: string; key: string; workspace: string | undefined; requestMs: number },\n): Promise<OperatorAccess> {\n const client = createOperatorClient({\n origin,\n getApiKey: () => key,\n fetchImpl: (url, init) => fetch(url, { ...init, signal: init?.signal ? AbortSignal.any([init.signal, AbortSignal.timeout(requestMs)]) : AbortSignal.timeout(requestMs) }),\n })\n const described = await client.describe()\n if (!described.succeeded) throw new Failure(`GET /api/operator/v1 answered ${described.status} ${described.code}: ${described.error.slice(0, 160)}`)\n const scopes = described.value.principal.scopes\n const missing = ['operator:read', 'operator:run'].filter(scope => !scopes.includes(scope) && !scopes.includes('*'))\n if (missing.length) throw new Failure(`the operator key lacks ${missing.join(' and ')}`)\n const listed = await client.listWorkspaces()\n if (!listed.succeeded) throw new Failure(`GET /api/operator/v1/workspaces answered ${listed.status} ${listed.code}: ${listed.error.slice(0, 160)}`)\n const chosen = workspace\n ? listed.value.filter(candidate => candidate.id === workspace || candidate.name === workspace)\n : listed.value.length === 1 ? listed.value : []\n if (chosen.length !== 1) {\n const names = listed.value.slice(0, 12).map(candidate => `${candidate.name} (${candidate.id.slice(0, 8)})`).join(', ')\n throw new Failure(workspace\n ? `${chosen.length} of the key's ${listed.value.length} workspaces match \"${workspace}\": ${names}`\n : `the key reaches ${listed.value.length} workspaces; name the canary workspace: ${names}`)\n }\n return { client, workspace: chosen[0]!, scopes }\n}\n\nconst reply = (turn: OperatorTurn) => (turn.reply?.content ?? '').trim()\n\n/** One turn on a new thread, followed until it settles. */\nasync function runTurn(access: OperatorAccess, title: string, content: string, turnMs: number, model?: string): Promise<{ turn: OperatorTurn; where: string }> {\n const turnId = randomUUID()\n const started = await access.client.startTurn(access.workspace.id, { turnId, content, title, ...(model ? { model } : {}) })\n if (!started.succeeded) throw new Failure(`the turn was refused: ${started.status} ${started.code}: ${started.error.slice(0, 200)}`)\n const where = `thread ${started.value.threadId}`\n const settled = await access.client.waitForTurn(access.workspace.id, started.value.threadId, started.value.turnId, { timeoutMs: turnMs })\n if (!settled.succeeded) throw new Failure(`reading the turn answered ${settled.status} ${settled.code}: ${settled.error.slice(0, 160)} (${where})`)\n const turn = settled.value\n if (turn.state === 'failed') throw new Failure(`the turn failed${turn.failure?.code ? ` (${turn.failure.code})` : ''}: ${(turn.failure?.message ?? 'no message').slice(0, 300)} (${where})`)\n if (turn.state === 'input-required' || turn.approvals.length > 0) throw new Failure(`the turn is waiting on a decision, which no one can answer in a conformance run (${where})`)\n if (turn.state !== 'succeeded') throw new Failure(`the turn had not settled after ${Math.round(turnMs / 1000)} s (state ${turn.state}; ${where})`)\n return { turn, where }\n}\n\nexport async function plainTurn(access: OperatorAccess, turnMs: number): Promise<string> {\n const { turn, where } = await runTurn(access, 'Conformance: plain turn',\n 'Conformance check: reply with one short sentence confirming you can answer.', turnMs)\n if (!reply(turn)) throw new Failure(`the turn succeeded with an empty reply (${where})`)\n return `${reply(turn).length} characters from ${turn.model ?? 'an unreported model'} (${where})`\n}\n\nexport async function computerTurn(access: OperatorAccess, turnMs: number, proof: ComputerProof, fileDir: string, model: string): Promise<string> {\n const nonce = `conformance-${randomBytes(12).toString('hex')}`\n if (proof === 'digest') {\n const digest = createHash('sha256').update(nonce).digest('hex')\n const { turn, where } = await runTurn(access, 'Conformance: computer turn',\n 'Conformance check: run this exact shell command on the workspace computer (sandbox_run when you have it), then reply with only '\n + `the 64-character hex digest it prints:\\nprintf %s '${nonce}' | sha256sum`, turnMs, model)\n if (!reply(turn).includes(digest)) {\n throw new Failure(`the reply does not hold the digest of the fresh nonce, so the computer did not run the command: \"${reply(turn).slice(0, 160)}\" (${where})`)\n }\n return `the reply carries the digest ${digest.slice(0, 12)}… (${where})`\n }\n const path = `${fileDir.replace(/\\/+$/, '')}/${nonce}.md`\n const { where } = await runTurn(access, 'Conformance: computer turn',\n `Conformance check: use the workspace computer to save a file at ${path} whose whole content is this one line, then reply with the word saved:\\n${nonce}`, turnMs, model)\n const read = await access.client.readFile(access.workspace.id, path)\n if (!read.succeeded) throw new Failure(`the turn succeeded, but the app does not serve ${path}: ${read.status} ${read.code} (${where})`)\n if (read.value.content.trim() !== nonce) {\n throw new Failure(`${path} holds ${JSON.stringify(read.value.content.slice(0, 80))}, not the nonce (${where})`)\n }\n return `the app serves ${path} with the nonce (${where})`\n}\n","import { readRevision } from './revision.js'\nimport { Failure, signIn, type MemberSession, type SignInMode } from './session.js'\nimport { computerTurn, mintKey, openOperatorAccess, plainTurn, revokeKey, type ComputerProof, type OperatorAccess } from './turns.js'\n\nexport type CheckName = 'sign-in' | 'revision' | 'operator-access' | 'plain-turn' | 'computer-turn' | 'key-revoke'\n\n/**\n * One check's verdict. `blocked` means an earlier check it depends on failed, so nothing was measured; a blocked\n * check fails the run like a failed one, and its cause names the check that blocked it.\n */\nexport interface CheckResult {\n /** When the check started, ISO 8601. */\n at: string\n app: string\n url: string\n check: CheckName\n status: 'pass' | 'fail' | 'blocked'\n ms: number\n /** Why a failed or blocked check is not a pass. */\n cause?: string\n /** What a passing check observed: the revision read, the thread a turn ran in. */\n detail?: string\n}\n\nexport interface ConformanceOptions {\n /** A label for the result lines, e.g. `gtm`. */\n app: string\n /** The deployed origin, e.g. `https://gtm.tangle.tools`. */\n origin: string\n /** The member that signs in. Required: sign-in is the first thing a customer does. */\n member?: { mode: SignInMode; email: string; password: string }\n /** A key that already has `operator:read` and `operator:run`; without one, the signed-in member mints a one-hour key. */\n operatorKey?: string\n /** Id or exact name of the workspace the turns run in: the app's canary or smoke workspace, never a customer's. */\n workspace?: string\n /** `digest` hashes a fresh nonce on the workspace computer; `file` has the computer save a file the app serves back;\n * `none` runs the plain turn only, for a check that asks exactly once (a post-serve first ask). */\n computer?: ComputerProof | 'none'\n /** The computer turn's model. The plain turn keeps the app's own model, so the served model is still checked once. */\n computerModel?: string\n /** Where the `file` proof is saved, relative to the workspace root. */\n fileDir?: string\n /** The budget of each turn, a cold box included. */\n turnMs?: number\n /** Fail unless the served revision starts with, or is a prefix of, this. */\n expectRevision?: string\n /** Called with each result as it lands. */\n onResult?(result: CheckResult): void\n}\n\nconst DEFAULT_TURN_MS = 300_000\n// Company spend rule: checks run on the flat-rate plan; per-token models are for product serving with real users.\nconst DEFAULT_COMPUTER_MODEL = 'glm-5.3'\n\n/** Why an unexpected error is not a pass, in a line. */\nfunction describe(error: unknown): string {\n if (error instanceof Failure) return error.message\n if (error instanceof Error) {\n const cause = error.cause as { code?: unknown } | undefined\n return `${error.name}: ${error.message}${typeof cause?.code === 'string' ? ` (${cause.code})` : ''}`\n }\n return String(error)\n}\n\n/** Runs the checks against one deployed app and returns every result, in the order they ran. */\nexport async function checkDeployedApp(options: ConformanceOptions): Promise<CheckResult[]> {\n const origin = options.origin.replace(/\\/+$/, '')\n const turnMs = options.turnMs ?? DEFAULT_TURN_MS\n const secrets = [options.member?.password, options.operatorKey].filter((value): value is string => Boolean(value && value.length >= 6))\n const redact = (text: string) => secrets.reduce((out, secret) => out.split(secret).join('[redacted]'), text)\n const results: CheckResult[] = []\n\n const record = (result: CheckResult) => {\n const clean = { ...result, ...(result.cause ? { cause: redact(result.cause) } : {}), ...(result.detail ? { detail: redact(result.detail) } : {}) }\n results.push(clean)\n options.onResult?.(clean)\n }\n /** Runs `body`; whatever it returns is the passing detail, whatever it throws is the cause. */\n async function check<T>(name: CheckName, body: () => Promise<{ value: T; detail?: string }>): Promise<T | undefined> {\n const at = new Date().toISOString()\n const started = Date.now()\n const base = { at, app: options.app, url: origin, check: name }\n try {\n const { value, detail } = await body()\n record({ ...base, status: 'pass', ms: Date.now() - started, ...(detail ? { detail } : {}) })\n return value\n } catch (error) {\n record({ ...base, status: 'fail', ms: Date.now() - started, cause: describe(error) })\n return undefined\n }\n }\n const blocked = (name: CheckName, because: string) =>\n record({ at: new Date().toISOString(), app: options.app, url: origin, check: name, status: 'blocked', ms: 0, cause: because })\n\n let session: MemberSession | undefined\n if (!options.member) {\n const at = new Date().toISOString()\n record({ at, app: options.app, url: origin, check: 'sign-in', status: 'fail', ms: 0, cause: 'no member is configured: give the canary member email and password' })\n } else {\n const member = options.member\n session = await check('sign-in', async () => {\n const signedIn = await signIn({ origin, ...member })\n return { value: signedIn.session, detail: signedIn.detail }\n })\n }\n\n await check('revision', async () => {\n const served = await readRevision(origin, options.expectRevision)\n return { value: served, detail: `${served.revision} (${served.source})` }\n })\n\n let minted: { id: string } | null = null\n let access: OperatorAccess | undefined\n if (!options.operatorKey && !session) {\n blocked('operator-access', 'blocked by sign-in: no operator key is configured, and the member did not sign in to mint one')\n } else {\n access = await check('operator-access', async () => {\n let secret = options.operatorKey\n if (!secret) {\n const created = await mintKey(session!)\n secrets.push(created.key)\n secret = created.key\n minted = { id: created.id }\n }\n const opened = await openOperatorAccess({ origin, key: secret, workspace: options.workspace, requestMs: turnMs + 60_000 })\n return {\n value: opened,\n detail: `${minted ? 'a minted one-hour key' : 'the configured operator key'} reaches \"${opened.workspace.name}\" with ${opened.scopes.join(', ')}`,\n }\n })\n }\n\n if (access) {\n const open = access\n await check('plain-turn', async () => ({ value: true, detail: await plainTurn(open, turnMs) }))\n const proof = options.computer ?? 'digest'\n if (proof !== 'none') {\n await check('computer-turn', async () => ({\n value: true, detail: await computerTurn(open, turnMs, proof, options.fileDir ?? 'proof', options.computerModel ?? DEFAULT_COMPUTER_MODEL),\n }))\n }\n } else {\n blocked('plain-turn', 'blocked by operator-access')\n if (options.computer !== 'none') blocked('computer-turn', 'blocked by operator-access')\n }\n\n // A key this run minted is revoked whether or not the turns ran: it names the member and would outlive the run.\n const mintedKey = minted as { id: string } | null\n if (mintedKey && session) {\n const member = session\n await check('key-revoke', async () => {\n await revokeKey(member, mintedKey.id)\n return { value: true, detail: 'the minted key was revoked' }\n })\n }\n return results\n}\n"],"mappings":";;;;;AASO,IAAM,UAAN,cAAsB,MAAM;AAAC;AAQpC,IAAM,aAAa;AAGnB,IAAM,MAAN,MAAU;AAAA,EACS,WAAW,oBAAI,IAAiC;AAAA,EAEjE,OAAO,KAAqB;AAC1B,WAAO,CAAC,GAAI,KAAK,SAAS,IAAI,IAAI,IAAI,GAAG,EAAE,MAAM,KAAK,CAAC,CAAE,EAAE,IAAI,CAAC,CAAC,MAAM,KAAK,MAAM,GAAG,IAAI,IAAI,KAAK,EAAE,EAAE,KAAK,IAAI;AAAA,EACjH;AAAA,EAEA,MAAM,KAAK,KAAa,OAAoB,CAAC,GAAsB;AACjE,UAAM,UAAU,IAAI,QAAQ,KAAK,OAAO;AACxC,UAAM,SAAS,KAAK,OAAO,GAAG;AAC9B,QAAI,OAAQ,SAAQ,IAAI,UAAU,MAAM;AACxC,UAAM,WAAW,MAAM,MAAM,KAAK,EAAE,GAAG,MAAM,SAAS,UAAU,UAAU,QAAQ,KAAK,UAAU,YAAY,QAAQ,UAAU,EAAE,CAAC;AAClI,SAAK,OAAO,KAAK,QAAQ;AACzB,WAAO;AAAA,EACT;AAAA,EAEQ,OAAO,KAAa,UAA0B;AACpD,UAAM,SAAS,IAAI,IAAI,GAAG,EAAE;AAC5B,UAAM,MAAM,KAAK,SAAS,IAAI,MAAM,KAAK,oBAAI,IAAoB;AACjE,eAAW,QAAQ,SAAS,QAAQ,aAAa,GAAG;AAClD,YAAM,CAAC,OAAO,IAAI,GAAG,UAAU,IAAI,KAAK,MAAM,GAAG;AAC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EACF,OAAO;AACL,YAAQ,cAAc,4BAA4B;AAClD,QAAI,QAAQ,aAAa,OAAQ,SAAQ,iBAAiB,4BAA4B;AAAA,EACxF;AAGA,QAAM,YAAY;AAClB,MAAI,aAAa,SAAS;AACxB,UAAM,SAAS;AACf,UAAM,MAAM,cAAc,YAAY;AACpC,YAAM,UAAU,QAAQ,UAAU,EAAE;AACpC,aAAO,EAAE,OAAO,MAAM,QAAQ,6BAA6B;AAAA,IAC7D,CAAC;AAAA,EACH;AACA,SAAO;AACT;","names":["REQUEST_MS","REQUEST_MS","where","text"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/chat-routes/sandbox-turn-usage.ts","../src/chat-routes/visible-text.ts","../src/chat-routes/draft-persistence.ts"],"sourcesContent":["import { asRecord, type JsonRecord } from '../stream/index'\nimport type { ChatTurnUsage } from './turn-routes'\n\n/** Every usage field a turn can record, in column order. */\nexport const TURN_USAGE_KEYS = [\n 'inputTokens', 'outputTokens', 'reasoningTokens', 'cacheReadTokens', 'cacheWriteTokens', 'costUsd', 'harnessCostUsd',\n] as const\n\n/** The usage fields a turn measured; unknown ones stay absent, never zero. */\nexport function measuredUsage(usage: ChatTurnUsage | undefined): ChatTurnUsage {\n const measured: ChatTurnUsage = {}\n for (const key of TURN_USAGE_KEYS) if (usage?.[key] !== undefined) measured[key] = usage[key]\n return measured\n}\n\n/** Add one canonical Sandbox `step-finish` receipt to a turn total. */\nexport function addStepFinishUsage(part: JsonRecord, usage: ChatTurnUsage): void {\n const tokens = asRecord(part.tokens)\n if (tokens) {\n const cache = asRecord(tokens.cache)\n const add = (current: number | undefined, value: unknown): number | undefined => {\n const n = Number(value)\n if (!Number.isFinite(n)) return current\n return (current ?? 0) + n\n }\n usage.inputTokens = add(usage.inputTokens, tokens.input)\n usage.outputTokens = add(usage.outputTokens, tokens.output)\n usage.reasoningTokens = add(usage.reasoningTokens, tokens.reasoning)\n if (cache) {\n usage.cacheReadTokens = add(usage.cacheReadTokens, cache.read)\n usage.cacheWriteTokens = add(usage.cacheWriteTokens, cache.write)\n }\n }\n const cost = Number(part.cost)\n if (Number.isFinite(cost)) usage.harnessCostUsd = (usage.harnessCostUsd ?? 0) + cost\n}\n","/**\n * Apply a product's final-text transform (a PII redactor, for example) to every\n * stored part a reader sees as words: the answer's text parts and the reasoning\n * parts, which also hold a Router turn's pre-tool narration. One rule for the\n * final row, the draft row and the detached-turn row.\n */\nexport function transformVisibleTextParts<T>(\n parts: readonly T[],\n transform: (text: string) => string | Promise<string>,\n): Promise<T[]> {\n return Promise.all(parts.map(async (part) => {\n const type = String((part as { type?: unknown }).type ?? '')\n return type === 'text' || type === 'reasoning'\n ? { ...part, text: await transform(String((part as { text?: unknown }).text ?? '')) }\n : part\n }))\n}\n","/**\n * Incremental (\"draft\") persistence of the assistant row WHILE a turn streams.\n *\n * Why this exists — the scale argument, not a convenience:\n *\n * A live turn is readable from two places. The hot path is the session\n * gateway's in-memory/Redis event buffer, which exists so a viewer survives a\n * network blip: it is keyed one sorted set per session, refreshed on every\n * push, and expires on a TTL. Its memory cost is `arrival_rate x TTL x\n * bytes_per_session` — strictly LINEAR in the TTL. Stretching that TTL to\n * cover \"a viewer who opens the tab later\" is a category error: it buys memory\n * proportional to the increase and still serves nothing to a viewer who\n * arrives past the new horizon.\n *\n * So the hot buffer must stay SHORT (live delivery + reconnect only), and\n * durable storage must serve history. That only works if durable storage\n * actually HAS the in-flight turn — which, before this module, it did not: the\n * assistant row was written once, after the stream drained. A viewer arriving\n * mid-turn past the hot window read an empty transcript.\n *\n * This module closes that gap: the assistant row is inserted early and patched\n * on a coalesced cadence, so the durable transcript is at most one interval\n * (default 2 s) behind the live stream and the hot buffer never has to be the\n * history tier.\n *\n * Mechanism only. It owns no vocabulary: the caller supplies the snapshot\n * function, the store, and the deterministic row id.\n *\n * Four properties the cadence guarantees:\n * - **Time-floored.** At most one write per `intervalMs`, never one per token.\n * - **Dirty-gated.** Only content-bearing events arm a write; heartbeats,\n * status pings, and lifecycle envelopes never do.\n * - **Single-flight.** A write already in flight suppresses the next trigger\n * instead of queueing; the final write is authoritative regardless of how\n * many drafts landed.\n * - **Best-effort.** A store failure is logged and swallowed — a durability\n * optimization must never kill a healthy stream (the same rule\n * `withDurableChatProjection` already states).\n */\n\nimport type { ChatMessageValues } from '../chat-store/core'\nimport { toChatMessageParts, type ChatMessagePart } from '../chat-store/parts'\nimport type { ChatTurnUsage } from './turn-routes'\nimport { measuredUsage } from './sandbox-turn-usage'\nimport { transformVisibleTextParts } from './visible-text'\n\n/** Message row shape the writer reads back when re-entering a turn. */\nexport interface DraftStoredMessage extends Pick<AssistantRowValues, keyof ChatTurnUsage> {\n id: string\n role: 'user' | 'assistant' | 'system' | 'tool'\n content: string\n parts?: ChatMessagePart[] | null\n model?: string | null\n requestedModel?: string | null\n servedModel?: string | null\n servedProvider?: string | null\n servedSource?: string | null\n}\n\n/** Values written to the assistant row — the intersection of the append and\n * patch shapes, so one snapshot serves both. */\nexport interface AssistantRowValues extends ChatMessageValues {}\n\n/** The store capability incremental persistence needs on top of\n * `appendMessage`. A store without `updateMessage` cannot patch a row, so it\n * cannot draft at all — the caller keeps today's single-write behavior. */\nexport interface AssistantDraftStore {\n listMessages(threadId: string): Promise<DraftStoredMessage[]>\n appendMessage(input: AssistantRowValues & {\n id?: string\n threadId: string\n role: 'user' | 'assistant'\n }): Promise<unknown>\n updateMessage?(id: string, patch: AssistantRowValues): Promise<unknown>\n deleteMessage?(id: string): Promise<unknown>\n}\n\n/** Live snapshot of the assistant body, taken from the producer's own\n * accumulators. `parts` is the DRAFT projection (`draftParts()`), never the\n * finalized one — see `draftAssistantParts`. */\nexport interface AssistantDraftSnapshot {\n content: string\n parts?: Array<Record<string, unknown>>\n usage?: ChatTurnUsage\n model?: string\n}\n\n/** Product-tunable cadence. Defaults are stated on each field; a product with\n * a chattier or heavier workload moves them without forking the writer. */\nexport interface DraftPersistenceTuning {\n /** Minimum wall-clock gap between draft writes, in ms. Default 2000.\n *\n * Justification for 2 s, from a measured tool-heavy production run (517\n * stream events over ~90 s wall = ~5.7 events/s): a 2 s floor with the\n * dirty gate turns 517 candidate writes into <= 45, while leaving the\n * durable row at most 2 s stale — an order of magnitude below the time it\n * takes a viewer to open a tab and render, so a late viewer never perceives\n * the lag. Fleet arithmetic at 10k concurrent 60 s runs: <= 30 updates per\n * run x 167 run-starts/s = ~334 row-updates/s spread over per-tenant\n * shards. Lower it and write amplification grows with no perceptible\n * freshness gain; raise it past ~5 s and a late viewer starts seeing a\n * visibly truncated answer. */\n intervalMs?: number\n /** Serialized-parts size (bytes) past which the interval backs off, so a\n * turn accumulating a megabyte-scale `parts` blob does not rewrite it every\n * interval. Default 262144 (256 KiB) -> interval x 2.5; ten times that ->\n * interval x 5. The final write is never throttled. */\n backoffBytes?: number\n /** Per-tool-part output cap applied to DRAFTS ONLY (bytes). A tool returning\n * a large blob would otherwise be rewritten in full on every draft. The\n * final write always carries the untruncated value. Default 32768 (32 KiB);\n * 0 disables truncation. */\n maxDraftToolOutputBytes?: number\n}\n\n/** Define the inputs required to construct an assistant draft writer */\nexport interface AssistantDraftWriterOptions extends DraftPersistenceTuning {\n store: AssistantDraftStore\n threadId: string\n /** DETERMINISTIC row id for this turn's assistant message — the whole\n * idempotency mechanism. Derived from the turn's existing identity\n * (`deriveExecutionId` in the interactive lane, the turn id in the detached\n * lane), so a re-entered turn addresses the SAME row: the writer looks the\n * id up before its first insert and patches what it finds. */\n messageId: string\n /** Read the producer's live accumulators. Returns null before the producer\n * is resolved (the assembly defers box resolution into the first pull). */\n snapshot(): AssistantDraftSnapshot | null\n /** Pre-persist text transform (`/redact`'s `redactPII`). Applied to the\n * draft's scalar content AND every draft text part — parity with the final\n * write, or incremental persistence would re-open the at-rest PII leak that\n * transform closed, just seconds earlier and on every turn. */\n transformText?(text: string): string | Promise<string>\n log?: (message: string, meta?: Record<string, unknown>) => void\n}\n\n/** Coalescing writer that keeps one durable assistant row in step with a\n * streaming turn. Created per turn; not reusable. */\nexport interface AssistantDraftWriter {\n /** Arm/trigger a draft write from one engine event. Synchronous by design —\n * the write itself is fire-and-forget so the stream is never blocked on\n * store latency. */\n notify(event: { type?: unknown }): void\n /** Stop drafting and settle any in-flight write. Called before the final\n * write so a late draft can never clobber the authoritative row. */\n close(): Promise<void>\n /** Write the AUTHORITATIVE completion values onto this turn's row —\n * insert-or-patch under the same deterministic id, un-throttled and\n * un-truncated. Errors propagate: the final write is the one that must not\n * fail silently. Implies {@link close}. */\n finalize(values: AssistantRowValues): Promise<void>\n /** The durable row this turn is writing, once one exists. */\n rowId(): string | undefined\n /** Retract the row for a turn that produced nothing (mirrors the final\n * write's empty-turn skip, which leaves no row at all today). Also retracts\n * a row a PREVIOUS attempt left behind, so a re-entered turn that ends\n * empty converges on \"no row\" rather than a stale partial. */\n discard(): Promise<void>\n /** Diagnostics: how many draft writes actually reached the store. */\n writeCount(): number\n}\n\n/** Event types that carry assistant content and therefore arm a draft write.\n * An allowlist on purpose: an unknown type (a product heartbeat, a bespoke\n * passthrough) must NEVER arm a write, or a silent producer would rewrite the\n * same row forever. */\nconst CONTENT_EVENT_TYPES: ReadonlySet<string> = new Set([\n 'text',\n 'reasoning',\n 'tool_call',\n 'tool_result',\n 'usage',\n 'notice',\n 'error',\n 'file',\n 'interaction',\n 'interaction.cancel',\n 'plan.submitted',\n 'message.part.updated',\n])\n\nconst DEFAULT_INTERVAL_MS = 2000\nconst DEFAULT_BACKOFF_BYTES = 262144\nconst DEFAULT_MAX_DRAFT_TOOL_OUTPUT_BYTES = 32768\n\n/** True when this event should arm a draft write. */\nexport function isDraftContentEvent(event: { type?: unknown }): boolean {\n return typeof event?.type === 'string' && CONTENT_EVENT_TYPES.has(event.type)\n}\n\n/** Caps one tool part's `output` for a DRAFT write. The value is replaced by a\n * truncated string plus a marker, so a reader can tell a clipped draft from a\n * real short output; the final write restores the untruncated value. */\nfunction capDraftToolOutput(part: Record<string, unknown>, maxBytes: number): Record<string, unknown> {\n if (maxBytes <= 0) return part\n if (String(part.type ?? '') !== 'tool') return part\n const state = part.state\n if (!state || typeof state !== 'object') return part\n const record = state as Record<string, unknown>\n const output = record.output\n if (output === undefined || output === null) return part\n const serialized = typeof output === 'string' ? output : safeStringify(output)\n if (serialized.length <= maxBytes) return part\n const metadata = (record.metadata && typeof record.metadata === 'object' ? record.metadata : {}) as Record<string, unknown>\n return {\n ...part,\n state: {\n ...record,\n output: `${serialized.slice(0, maxBytes)}…[draft-truncated ${serialized.length - maxBytes} chars]`,\n metadata: { ...metadata, draftTruncated: true },\n },\n }\n}\n\nfunction safeStringify(value: unknown): string {\n try {\n return JSON.stringify(value) ?? ''\n } catch {\n return String(value)\n }\n}\n\n/** Build the coalescing draft writer for one turn. */\nexport function createAssistantDraftWriter(options: AssistantDraftWriterOptions): AssistantDraftWriter {\n const log = options.log ?? (() => {})\n const baseIntervalMs = options.intervalMs ?? DEFAULT_INTERVAL_MS\n const backoffBytes = options.backoffBytes ?? DEFAULT_BACKOFF_BYTES\n const maxToolOutput = options.maxDraftToolOutputBytes ?? DEFAULT_MAX_DRAFT_TOOL_OUTPUT_BYTES\n\n let dirty = false\n let closed = false\n let inFlight: Promise<void> | undefined\n let lastWriteAt = 0\n let lastBlobBytes = 0\n let rowId: string | undefined\n let writes = 0\n\n /** Interval for the NEXT write, backed off by the size of the last blob\n * written — a turn accumulating a huge parts array rewrites it less often. */\n function currentIntervalMs(): number {\n if (lastBlobBytes >= backoffBytes * 10) return baseIntervalMs * 5\n if (lastBlobBytes >= backoffBytes) return Math.round(baseIntervalMs * 2.5)\n return baseIntervalMs\n }\n\n async function projectValues(snapshot: AssistantDraftSnapshot): Promise<AssistantRowValues> {\n const transform = options.transformText\n const content = transform ? await transform(snapshot.content) : snapshot.content\n let parts: ChatMessagePart[] | undefined\n if (snapshot.parts) {\n const capped = snapshot.parts.map((part) => capDraftToolOutput(part, maxToolOutput))\n const redacted = transform ? await transformVisibleTextParts(capped, transform) : capped\n parts = toChatMessageParts(redacted)\n }\n const usage = snapshot.usage ?? {}\n return {\n content,\n ...(parts && parts.length > 0 ? { parts } : {}),\n ...(snapshot.model ? { model: snapshot.model } : {}),\n ...measuredUsage(usage),\n }\n }\n\n /** Adopt the row a PREVIOUS attempt at this turn already inserted, if any.\n * This lookup — by the deterministic id, through the store's ordinary read\n * — is the whole crash-safety mechanism: no new state, no extra column, no\n * second index. */\n async function adoptRow(): Promise<string | undefined> {\n if (rowId) return rowId\n const existing = (await options.store.listMessages(options.threadId)).find(\n (message) => message.id === options.messageId,\n )\n if (existing) rowId = existing.id\n return rowId\n }\n\n /** Insert-or-patch one set of values onto this turn's single row. */\n async function writeOnce(values: AssistantRowValues): Promise<void> {\n if (await adoptRow()) {\n await options.store.updateMessage!(rowId!, values)\n writes += 1\n return\n }\n const inserted = await options.store.appendMessage({\n id: options.messageId,\n threadId: options.threadId,\n role: 'assistant',\n ...values,\n })\n // The `?? options.messageId` tail is valid HERE and only here: this writer\n // supplied the id, so a store that returns nothing still wrote that row.\n // A caller that did not assign an id has no such fallback — which is why\n // `rowIdOf` deliberately stops at the honest read.\n rowId = rowIdOf(inserted) ?? options.messageId\n writes += 1\n }\n\n function trigger(): void {\n if (closed) return\n if (!dirty) return\n // Single-flight: a write already in flight SUPPRESSES this trigger rather\n // than queueing behind it. `dirty` stays armed, so the next event after it\n // lands writes the newer snapshot — one write is never spent on state a\n // later one supersedes.\n if (inFlight) return\n const now = Date.now()\n // The first content event writes immediately (a late viewer sees a row at\n // once); the time floor governs every write after it.\n if (lastWriteAt !== 0 && now - lastWriteAt < currentIntervalMs()) return\n const snapshot = options.snapshot()\n if (!snapshot) return\n // Nothing to persist yet: an armed-but-empty snapshot (first event is a\n // tool call with no text and no parts) would insert a blank row.\n if (!snapshot.content && (!snapshot.parts || snapshot.parts.length === 0)) return\n dirty = false\n lastWriteAt = now\n inFlight = (async () => {\n try {\n const values = await projectValues(snapshot)\n lastBlobBytes = values.parts ? safeStringify(values.parts).length : 0\n await writeOnce(values)\n } catch (err) {\n // Best-effort by contract: a store outage degrades freshness for late\n // viewers, it does not fail a healthy turn.\n log('[chat-routes] incremental assistant persistence failed', {\n messageId: options.messageId,\n error: err instanceof Error ? err.message : String(err),\n })\n } finally {\n inFlight = undefined\n // A trigger that arrived while this write was in flight left `dirty`\n // armed with a NEWER snapshot. Re-run it here or that state would sit\n // unwritten until the next content event — and if this was the last\n // event of a quiet stretch, until the final write.\n if (dirty && !closed) trigger()\n }\n })()\n }\n\n return {\n notify(event) {\n if (closed) return\n if (isDraftContentEvent(event)) dirty = true\n trigger()\n },\n async close() {\n closed = true\n if (inFlight) await inFlight\n },\n async finalize(values) {\n closed = true\n if (inFlight) await inFlight\n await writeOnce(values)\n },\n rowId: () => rowId,\n async discard() {\n closed = true\n if (inFlight) await inFlight\n if (!options.store.deleteMessage) return\n try {\n if (!(await adoptRow())) return\n await options.store.deleteMessage(rowId!)\n rowId = undefined\n } catch (err) {\n log('[chat-routes] draft assistant row discard failed', {\n messageId: options.messageId,\n error: err instanceof Error ? err.message : String(err),\n })\n }\n },\n writeCount: () => writes,\n }\n}\n\n/** True when a store can support incremental persistence at all. Without\n * `updateMessage` a draft row could never be patched, so the caller keeps\n * today's exact single-write behavior. */\nexport function storeSupportsDraftPersistence(store: AssistantDraftStore): boolean {\n return typeof store.updateMessage === 'function'\n}\n\n/** The row id an `appendMessage` actually returned, or `null` when the store\n * returned nothing usable. `ChatTurnMessageStore.appendMessage` is typed\n * `Promise<unknown>` so a product adapter is free to resolve `void`; every\n * caller that wants to NAME the row it just wrote has to read defensively.\n *\n * Deliberately no fallback to a caller-assigned id — see `writeOnce`, which\n * adds its own. A caller that let the store mint the id has nothing to fall\n * back TO, and guessing one would report a row that may not exist. */\nexport function rowIdOf(inserted: unknown): string | null {\n const id = (inserted as { id?: unknown } | null | undefined)?.id\n return typeof id === 'string' && id ? id : null\n}\n\n/** The default deterministic assistant-row id for a turn. Readable on purpose\n * (an operator grepping a transcript row id finds the run), and stable across\n * re-entries because every input already is. */\nexport function assistant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