@tangle-network/agent-app 0.63.17 → 0.63.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (128) hide show
  1. package/dist/agent-profiles/d1.js +2 -2
  2. package/dist/agent-profiles/index.js +2 -2
  3. package/dist/agent-profiles/switch.d.ts +1 -1
  4. package/dist/agent-profiles/switch.js +1 -1
  5. package/dist/app-auth/index.js.map +1 -1
  6. package/dist/chat-routes/hybrid-producer.d.ts +1 -1
  7. package/dist/chat-routes/index.js +11 -11
  8. package/dist/chat-routes/model-failover-stream.d.ts +1 -1
  9. package/dist/chat-routes/turn-prefetch.d.ts +1 -1
  10. package/dist/{chunk-Z4RD5UF7.js → chunk-2PCNHHN2.js} +2 -2
  11. package/dist/{chunk-I6BZVIRH.js → chunk-3CI35I4X.js} +1 -1
  12. package/dist/chunk-3CI35I4X.js.map +1 -0
  13. package/dist/{chunk-ISP6ZH3G.js → chunk-3Q3UEWKK.js} +1 -1
  14. package/dist/chunk-3Q3UEWKK.js.map +1 -0
  15. package/dist/{chunk-VDYEVCQQ.js → chunk-5WSSH3X5.js} +2 -2
  16. package/dist/chunk-5WSSH3X5.js.map +1 -0
  17. package/dist/{chunk-NUWSPR5O.js → chunk-G3LZITCA.js} +2 -2
  18. package/dist/{chunk-IX6UVHXY.js → chunk-JKECSYDB.js} +2 -2
  19. package/dist/{chunk-6GX3UHQW.js → chunk-K3A2YAIX.js} +6 -6
  20. package/dist/chunk-K3A2YAIX.js.map +1 -0
  21. package/dist/{chunk-5GSZGTPJ.js → chunk-KA6LD4OI.js} +3 -3
  22. package/dist/{chunk-A3BJDXPX.js → chunk-LMIP4OVR.js} +5 -5
  23. package/dist/chunk-LMIP4OVR.js.map +1 -0
  24. package/dist/{chunk-MT6ZTQGD.js → chunk-N5RWYR5N.js} +1 -1
  25. package/dist/chunk-N5RWYR5N.js.map +1 -0
  26. package/dist/{chunk-7VTGB4DM.js → chunk-OSMMEMDH.js} +1 -1
  27. package/dist/chunk-OSMMEMDH.js.map +1 -0
  28. package/dist/{chunk-5FAKBTCK.js → chunk-OYFA7BAK.js} +1 -1
  29. package/dist/chunk-OYFA7BAK.js.map +1 -0
  30. package/dist/{chunk-7EDNPQHW.js → chunk-OZDMIYES.js} +1 -1
  31. package/dist/chunk-OZDMIYES.js.map +1 -0
  32. package/dist/{chunk-ZLX4BA27.js → chunk-QUT3T2IN.js} +1 -1
  33. package/dist/chunk-QUT3T2IN.js.map +1 -0
  34. package/dist/{chunk-PK65B6HP.js → chunk-UJYEBQMS.js} +1 -1
  35. package/dist/{chunk-PK65B6HP.js.map → chunk-UJYEBQMS.js.map} +1 -1
  36. package/dist/{chunk-5UQJ7F3P.js → chunk-UULUBF5J.js} +1 -1
  37. package/dist/chunk-UULUBF5J.js.map +1 -0
  38. package/dist/{chunk-LRYY3OX7.js → chunk-VEPII3YP.js} +4 -4
  39. package/dist/chunk-VEPII3YP.js.map +1 -0
  40. package/dist/{chunk-AVBNS64P.js → chunk-W6G2HF6M.js} +1 -1
  41. package/dist/chunk-W6G2HF6M.js.map +1 -0
  42. package/dist/{chunk-4GINUJPF.js → chunk-WRCMVBUJ.js} +1 -1
  43. package/dist/{chunk-4GINUJPF.js.map → chunk-WRCMVBUJ.js.map} +1 -1
  44. package/dist/{chunk-E3AOUTIR.js → chunk-XGFGSZS5.js} +2 -2
  45. package/dist/chunk-XGFGSZS5.js.map +1 -0
  46. package/dist/{chunk-EKXG4JSN.js → chunk-YRWUJKW5.js} +2 -2
  47. package/dist/chunk-YRWUJKW5.js.map +1 -0
  48. package/dist/journeys/artifacts.d.ts +1 -0
  49. package/dist/journeys/cli.js +1 -1
  50. package/dist/journeys/index.js +55 -18
  51. package/dist/journeys/index.js.map +1 -1
  52. package/dist/journeys/journey.d.ts +1 -0
  53. package/dist/journeys/score.d.ts +1 -1
  54. package/dist/journeys/scoreboard.d.ts +1 -2
  55. package/dist/journeys/send.d.ts +1 -2
  56. package/dist/launch-invariants/auth-lookup-cache.d.ts +1 -1
  57. package/dist/launch-invariants/catalog.d.ts +3 -3
  58. package/dist/launch-invariants/cli.js +3 -3
  59. package/dist/launch-invariants/index.d.ts +1 -1
  60. package/dist/launch-invariants/index.js +3 -3
  61. package/dist/launch-invariants/index.js.map +1 -1
  62. package/dist/launch-invariants/limit-alarms.d.ts +1 -1
  63. package/dist/launch-invariants/pasted-code.d.ts +1 -1
  64. package/dist/launch-invariants/schedule.d.ts +1 -1
  65. package/dist/launch-invariants/settlement.d.ts +2 -2
  66. package/dist/launch-invariants/sized-reads.d.ts +1 -1
  67. package/dist/launch-invariants/testing.js +3 -3
  68. package/dist/model-resolution/index.js +1 -1
  69. package/dist/platform/billable-turn-admission.d.ts +1 -1
  70. package/dist/platform/delegated-keys.d.ts +2 -2
  71. package/dist/platform/delegated-turn-keys.d.ts +1 -1
  72. package/dist/platform/index.js.map +1 -1
  73. package/dist/preflight/cli.js +1 -1
  74. package/dist/preflight/index.d.ts +1 -1
  75. package/dist/preflight/index.js +1 -1
  76. package/dist/preset-cloudflare/index.js +6 -6
  77. package/dist/public-consultation/index.js +9 -9
  78. package/dist/rollout/cli.js +1 -1
  79. package/dist/rollout/d1.js +1 -1
  80. package/dist/rollout/index.d.ts +1 -1
  81. package/dist/rollout/index.js +1 -1
  82. package/dist/runtime/index.js +3 -3
  83. package/dist/runtime/router-turn.d.ts +3 -3
  84. package/dist/runtime/router-turn.js +2 -2
  85. package/dist/runtime/turn-knowledge.d.ts +1 -1
  86. package/dist/sandbox/index.js +5 -5
  87. package/dist/sandbox/model.d.ts +1 -1
  88. package/dist/sandbox/prewarm-claim-d1.d.ts +1 -1
  89. package/dist/sandbox/prewarm.d.ts +2 -2
  90. package/dist/sandbox/reuse-state.d.ts +1 -1
  91. package/dist/sandbox/terminal-connection.d.ts +4 -4
  92. package/dist/sandbox/warm-lease.d.ts +2 -2
  93. package/dist/sandbox/warm-receipts.d.ts +1 -1
  94. package/dist/signoff/app-defaults.d.ts +1 -1
  95. package/dist/signoff/cli.js +2 -2
  96. package/dist/signoff/index.js +2 -2
  97. package/dist/signoff/surface-ladder.d.ts +2 -2
  98. package/dist/signoff/workspace-surface.d.ts +1 -1
  99. package/dist/stream/index.js +2 -2
  100. package/dist/stream/turn-buffer.d.ts +1 -1
  101. package/dist/turn-health/index.js +1 -1
  102. package/dist/turn-health/index.js.map +1 -1
  103. package/dist/turn-stream/adapters.d.ts +1 -1
  104. package/dist/turn-stream/core.d.ts +1 -1
  105. package/dist/turn-stream/index.js +2 -2
  106. package/dist/turn-trace/index.js +1 -1
  107. package/dist/turn-trace/otel.d.ts +1 -1
  108. package/dist/workspace-export/index.js.map +1 -1
  109. package/package.json +1 -1
  110. package/dist/chunk-5FAKBTCK.js.map +0 -1
  111. package/dist/chunk-5UQJ7F3P.js.map +0 -1
  112. package/dist/chunk-6GX3UHQW.js.map +0 -1
  113. package/dist/chunk-7EDNPQHW.js.map +0 -1
  114. package/dist/chunk-7VTGB4DM.js.map +0 -1
  115. package/dist/chunk-A3BJDXPX.js.map +0 -1
  116. package/dist/chunk-AVBNS64P.js.map +0 -1
  117. package/dist/chunk-E3AOUTIR.js.map +0 -1
  118. package/dist/chunk-EKXG4JSN.js.map +0 -1
  119. package/dist/chunk-I6BZVIRH.js.map +0 -1
  120. package/dist/chunk-ISP6ZH3G.js.map +0 -1
  121. package/dist/chunk-LRYY3OX7.js.map +0 -1
  122. package/dist/chunk-MT6ZTQGD.js.map +0 -1
  123. package/dist/chunk-VDYEVCQQ.js.map +0 -1
  124. package/dist/chunk-ZLX4BA27.js.map +0 -1
  125. /package/dist/{chunk-Z4RD5UF7.js.map → chunk-2PCNHHN2.js.map} +0 -0
  126. /package/dist/{chunk-NUWSPR5O.js.map → chunk-G3LZITCA.js.map} +0 -0
  127. /package/dist/{chunk-IX6UVHXY.js.map → chunk-JKECSYDB.js.map} +0 -0
  128. /package/dist/{chunk-5GSZGTPJ.js.map → chunk-KA6LD4OI.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/journeys/score.ts","../src/journeys/config.ts","../src/journeys/scrub.ts","../src/journeys/trace-zip.ts","../src/journeys/session.ts","../src/journeys/video.ts","../src/journeys/report.ts","../src/journeys/scoreboard.ts"],"sourcesContent":["/**\n * Whether a recorded chat turn worked, decided from what the person saw.\n *\n * The GTM journey harness scored 6 of 6 failed turns \"completed\":\n * it read failure only from `role=\"alert\"` and from the tail of the assistant's\n * markdown, and the red failure card a person saw carried neither. One caption\n * read \"Turn complete after 159.6 s\" over \"The agent stopped before finishing\".\n * This module is the replacement rule, pure so every case is a unit test:\n *\n * - failure evidence is read from the transcript region (failure-marked\n * elements, failure lines in plain text, and a Retry control that appeared),\n * not from the reply alone, and from after the turn's own prompt when the\n * page shows it (see page-reading.ts);\n * - only evidence that appeared during the turn counts, so an earlier failure in\n * the same thread cannot fail a later turn, even one the page re-renders after\n * Send, and a card that Retry replaced with a new failure still counts;\n * - a turn that ends with no new reply text is `empty`, never `completed`;\n * - a turn the person stopped is `stopped`, not a success and not a crash.\n */\n\n/** What one poll of the page returns. Collected in the page, judged here. */\nexport interface TranscriptSnapshot {\n /** Visible lines of the transcript region, trimmed, empty lines dropped. */\n readonly lines: readonly string[]\n /** Text of every failure-marked element (including hidden details). */\n readonly failureNodes: readonly string[]\n /** Retry controls inside the transcript region. */\n readonly retryButtons: number\n /**\n * The fields above hold only what follows the turn's own prompt. Everything\n * after the prompt is the turn's, so no earlier floor applies to it.\n */\n readonly anchored?: boolean\n}\n\nexport interface FailurePatterns {\n /** A line matching one of these is failure evidence. */\n readonly failure: readonly RegExp[]\n /** A line matching one of these means the person stopped the turn. */\n readonly stopped: readonly RegExp[]\n}\n\n/**\n * Failure text any agent app can show: typed failure codes, provider errors and\n * this package's own sandbox-stream copy. An app adds its own card copy through\n * `chat.failureText` in its journeys config.\n *\n * Matched as substrings of whole lines. A reply that QUOTES one of these fails\n * the turn too; that direction is deliberate, because missing a failure passes a\n * broken product while over-matching only costs a rerun.\n */\nexport const DEFAULT_FAILURE_TEXT: readonly RegExp[] = [\n /\\b[a-z]+(?:_[a-z]+)*\\.[a-z]+(?:_[a-z]+)*_(?:failed|unavailable|timeout)\\b/,\n /\\bAPIError \\d{3}\\b/,\n /stopped before a clean completion/i,\n /Failed to connect to Sandbox API/i,\n /\\bbilling\\.balance_required\\b|Add balance or upgrade your plan/i,\n /Internal Server Error/,\n /\\bECONNREFUSED\\b/,\n /Something went wrong/i,\n // agent-app's own sandbox failure copy (`formatSandboxProvisioningUserMessage`),\n // which every app on the shared runtime can render as a reply. Tests drive the\n // formatter's every branch through these, so the copy and the scorer cannot drift.\n /unable to (?:re)?connect to the sandbox/i,\n /sandbox service didn.t answer/i,\n /Sandbox recovery is required before chat can continue/i,\n /couldn.t (?:finish copying|copy) your Vault into the sandbox/i,\n /too large (?:for the sandbox to accept|to copy into the sandbox)/i,\n /attachment data is staged in the sandbox/i,\n]\n\n/** Runtime wording for a turn the person stopped. Apps add their own copy. */\nexport const DEFAULT_STOPPED_TEXT: readonly RegExp[] = [\n /interrupted by the user/i,\n /cancell?ed by (?:the )?user/i,\n /stopped by (?:the )?user/i,\n]\n\nfunction normalize(line: string): string {\n return line.replace(/\\s+/g, ' ').trim()\n}\n\n/** Every keyed item of a snapshot that can count as failure evidence. */\nfunction evidenceKeys(snapshot: TranscriptSnapshot, patterns: FailurePatterns, ignore: ReadonlySet<string>): Map<string, number> {\n const counts = new Map<string, number>()\n const add = (key: string) => counts.set(key, (counts.get(key) ?? 0) + 1)\n for (const raw of snapshot.lines) {\n const line = normalize(raw)\n if (!line || ignore.has(line)) continue\n if (patterns.stopped.some((p) => p.test(line))) add(`stopped:${line}`)\n else if (patterns.failure.some((p) => p.test(line))) add(`text:${line}`)\n }\n for (const raw of snapshot.failureNodes) {\n const text = normalize(raw)\n if (text && !ignore.has(text)) add(`node:${text.slice(0, 300)}`)\n }\n for (let i = 0; i < snapshot.retryButtons; i += 1) add('retry')\n return counts\n}\n\n/**\n * Failure evidence that appeared after the turn was sent.\n *\n * `begin` takes the snapshot from just before Send. Every later `observe`\n * lowers each item's floor to the fewest copies seen so far: when Retry removes\n * the old card and a new failure renders the same words, the count dips to zero\n * and climbs back to one, and that one is new. Anything that rose above its\n * floor at any point counts, even if the page later replaced it: on 2026-10-11\n * GTM showed \"The sandbox model stream stopped before a clean completion …\n * Hub credential source is revoked or expired\" five minutes into a turn, then\n * swapped it for a different card six minutes later.\n */\nexport class TurnEvidence {\n private floor = new Map<string, number>()\n private peak = new Map<string, number>()\n private anchored = false\n private readonly ignore: Set<string>\n\n constructor(private readonly patterns: FailurePatterns, prompt: string) {\n // The person's own prompt is on the page too; a prompt that mentions an\n // error must not fail its own turn.\n this.ignore = new Set(prompt.split('\\n').map(normalize).filter(Boolean))\n this.ignore.add(normalize(prompt))\n }\n\n begin(snapshot: TranscriptSnapshot): void {\n this.floor = evidenceKeys(snapshot, this.patterns, this.ignore)\n this.peak = new Map()\n this.anchored = snapshot.anchored === true\n }\n\n /** Read one snapshot. Returns the evidence that appeared for the first time, as display text. */\n observe(snapshot: TranscriptSnapshot): string[] {\n if (snapshot.anchored && !this.anchored) {\n // The first read that shows this turn's prompt: a floor taken from the whole transcript no longer applies.\n this.floor = new Map()\n this.anchored = true\n }\n const now = evidenceKeys(snapshot, this.patterns, this.ignore)\n for (const [key, floor] of this.floor) {\n const count = now.get(key) ?? 0\n if (count < floor) this.floor.set(key, count)\n }\n const fresh: string[] = []\n for (const [key, count] of now) {\n const extra = count - (this.floor.get(key) ?? 0)\n if (extra <= (this.peak.get(key) ?? 0)) continue\n if (!this.peak.has(key)) fresh.push(display(key))\n this.peak.set(key, extra)\n }\n return fresh\n }\n\n /** Everything that rose above its floor during the turn, in the order it appeared. */\n added(): { failures: string[]; stopped: string[]; retryAppeared: boolean } {\n const failures: string[] = []\n const stopped: string[] = []\n let retryAppeared = false\n for (const key of this.peak.keys()) {\n if (key === 'retry') retryAppeared = true\n else if (key.startsWith('stopped:')) stopped.push(key.slice('stopped:'.length))\n else failures.push(key.slice(key.indexOf(':') + 1))\n }\n return { failures, stopped, retryAppeared }\n }\n}\n\nfunction display(key: string): string {\n return key === 'retry' ? 'a Retry control appeared in the transcript' : key.slice(key.indexOf(':') + 1)\n}\n\n/**\n * Whether a turn is still going, from what the page shows. A status line is\n * progress while it changes; one left unchanged for {@link STATUS_STALE_MS}\n * with no Stop control is a notice left behind (GTM's \"Request was\n * interrupted by the user. Send a new message to continue.\" is a lasting\n * `role=\"status\"`), and treating it as progress held a stopped turn open until\n * its 15-minute timeout.\n */\nexport const STATUS_STALE_MS = 20_000\n\nexport function turnLooksActive(page: { stopVisible: boolean; statusLines: number; msSinceStatusChanged: number }): boolean {\n return page.stopVisible || (page.statusLines > 0 && page.msSinceStatusChanged < STATUS_STALE_MS)\n}\n\nexport type TurnOutcome = 'completed' | 'failed' | 'stopped' | 'empty' | 'timeout' | 'not-sent'\n\nexport interface TurnVerdict {\n outcome: TurnOutcome\n /** Plain words for a caption: the first failure line, or why the turn is not a pass. */\n error: string | null\n /** Every piece of failure evidence the turn added, for the report. */\n failures: string[]\n}\n\nexport interface TurnFacts {\n /** The send never reached the app. */\n readonly notSent?: string\n /** The app still listed the turn as running when the wait ran out. */\n readonly timedOut: boolean\n readonly evidence: ReturnType<TurnEvidence['added']>\n /** New reply characters this turn added. */\n readonly replyChars: number\n /** The journey pressed Stop during this turn. */\n readonly stopPressed: boolean\n}\n\n/** The one place a turn's outcome is decided. Order matters: evidence first. */\nexport function scoreTurn(facts: TurnFacts): TurnVerdict {\n if (facts.notSent) return { outcome: 'not-sent', error: facts.notSent, failures: [] }\n const { failures, stopped, retryAppeared } = facts.evidence\n const all = [...stopped, ...failures, ...(retryAppeared ? ['a Retry control appeared in the transcript'] : [])]\n // A Stop that took effect. One that did not (still running at the deadline)\n // falls through to `timeout`, because Stop failing is itself the defect.\n if (stopped.length || (facts.stopPressed && !facts.timedOut)) {\n return { outcome: 'stopped', error: stopped[0] ?? failures[0] ?? 'stopped by the journey', failures: all }\n }\n if (failures.length || retryAppeared) {\n return { outcome: 'failed', error: failures[0] ?? 'a Retry control appeared in the transcript', failures: all }\n }\n if (facts.timedOut) return { outcome: 'timeout', error: 'the turn was still running when the wait ended', failures: all }\n if (facts.replyChars === 0) return { outcome: 'empty', error: 'the turn ended without any reply text', failures: all }\n return { outcome: 'completed', error: null, failures: [] }\n}\n","/**\n * What an app tells the journeys kit about itself: where it is served, which\n * test identities may sign in, and the chat DOM a turn is measured on.\n *\n * It lives at the app root as `journeys.config.mjs`, beside\n * `launch-invariants.config.mjs`:\n *\n * import { defineJourneys } from '@tangle-network/agent-app/journeys'\n * export default defineJourneys({\n * app: 'gtm',\n * baseUrl: 'https://gtm.tangle.tools',\n * identities: {\n * member: { emailEnv: 'SMOKE_EMAIL', passwordEnv: 'SMOKE_PASSWORD', signIn: 'tangle' },\n * },\n * chat: { assistant: '.gtm-assistant-markdown', failureText: [/stopped before finishing/i] },\n * })\n *\n * Credentials are named, never stored: the config holds environment variable\n * names, and the values reach the process from the host's vault.\n */\nimport { existsSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { join, resolve } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport { DEFAULT_FAILURE_TEXT, DEFAULT_STOPPED_TEXT } from './score.js'\n\nexport type SignInMethod = 'password' | 'tangle'\n\nexport interface JourneyIdentity {\n /** Environment variable that holds the account's email. */\n readonly emailEnv: string\n /** Environment variable that holds the account's password. */\n readonly passwordEnv: string\n /**\n * `password`: the app's own email sign-in (better-auth `sign-in/email`).\n * `tangle`: \"Log in with Tangle\": the app's SSO start, the Platform's email\n * sign-in, then the app's callback.\n */\n readonly signIn: SignInMethod\n}\n\n/** The ids a thread URL carries. */\nexport interface ThreadRoute {\n readonly threadId: string\n readonly workspaceId?: string\n}\n\n/**\n * The chat DOM a turn is read from. Defaults are agent-app's own components:\n * `ChatComposer` (the composer card, \"Message input\", \"Send\", \"Stop response\")\n * and the transcript's failure rows (`role=\"alert\"`, `data-notice-tone=\"error\"`).\n */\nexport interface ChatContract {\n /** Region whose text decides a turn's outcome. */\n readonly transcript: string\n /** Assistant reply blocks. `null` measures reply text as transcript growth beyond the prompt. */\n readonly assistant: string | null\n /** Progress lines inside the transcript (\"Sending…\", \"Searching the web\"). */\n readonly status: string\n /** Elements that mark a failed turn. */\n readonly failureNodes: string\n /** Failure lines this app shows in plain text, added to the package defaults. */\n readonly failureText: readonly RegExp[]\n /** Lines meaning the person stopped the turn, added to the package defaults. */\n readonly stoppedText: readonly RegExp[]\n /** The card holding the composer's input and action row. */\n readonly composer: string\n /** Accessible names inside the composer card. */\n readonly inputName: string\n readonly sendName: string\n readonly stopName: string\n /** Accessible name of a failed turn's retry control. */\n readonly retryName: RegExp\n /** A created thread's path. Named groups `threadId` (required) and `workspaceId`. */\n readonly threadPath: RegExp | null\n /** Path that lists a thread's running turns as JSON `{ running: string[] }`; the server's word on completion. */\n readonly runningTurns: ((route: ThreadRoute) => string) | null\n /** POST paths that mean the composer submitted, besides the page's own route. */\n readonly sendPaths: readonly RegExp[]\n}\n\nexport interface AuthPaths {\n readonly session: string\n readonly passwordSignIn: string\n readonly tangleStart: string\n}\n\nexport interface JourneysConfig {\n /** Short name, used for state and output folders. */\n readonly app: string\n /** Origin the journeys drive. `JOURNEYS_BASE_URL` overrides it, for a local stack. */\n readonly baseUrl: string\n readonly identities: Readonly<Record<string, JourneyIdentity>>\n readonly chat?: Partial<ChatContract>\n readonly auth?: Partial<AuthPaths>\n /** Chat turns one journey may send. Default 6. */\n readonly maxTurns?: number\n /** Sessions and raw recordings. Default `~/.local/state/agent-app-journeys/<app>`. */\n readonly stateDir?: string\n /** Files safe to copy off the host. Default `<stateDir>/out`. */\n readonly outDir?: string\n}\n\nexport interface ResolvedJourneysConfig {\n /** Marks a config whose defaults are filled; resolving it again returns it unchanged. */\n readonly resolved: true\n readonly app: string\n readonly baseUrl: string\n readonly identities: Readonly<Record<string, JourneyIdentity>>\n readonly chat: ChatContract\n readonly auth: AuthPaths\n readonly maxTurns: number\n readonly stateDir: string\n readonly outDir: string\n}\n\nexport const DEFAULT_CHAT_CONTRACT: ChatContract = {\n transcript: 'main',\n assistant: null,\n status: '[role=\"status\"]',\n failureNodes: '[role=\"alert\"], [data-notice-tone=\"error\"]',\n failureText: [],\n stoppedText: [],\n composer: '[data-testid=\"composer-card\"]',\n inputName: 'Message input',\n sendName: 'Send',\n stopName: 'Stop response',\n retryName: /^Retry$/,\n threadPath: null,\n runningTurns: null,\n sendPaths: [/^\\/api\\/(?:[^/]+\\/)*chat$/],\n}\n\nexport const DEFAULT_AUTH_PATHS: AuthPaths = {\n session: '/api/auth/get-session',\n passwordSignIn: '/api/auth/sign-in/email',\n tangleStart: '/auth/tangle/start',\n}\n\nexport const CONFIG_FILE_NAMES = ['journeys.config.mjs', 'journeys.config.js'] as const\n\n/** Identity for a typed config; also validates it. */\nexport function defineJourneys(config: JourneysConfig): JourneysConfig {\n resolveJourneysConfig(config)\n return config\n}\n\nconst ENV_NAME = /^[A-Z_][A-Z0-9_]*$/\n\n/** Fill defaults and refuse a config that cannot drive a journey. */\nexport function resolveJourneysConfig(config: JourneysConfig | ResolvedJourneysConfig, env: Record<string, string | undefined> = process.env): ResolvedJourneysConfig {\n if ('resolved' in config && config.resolved === true) return config\n const problems: string[] = []\n if (!/^[a-z0-9][a-z0-9-]{0,40}$/.test(config.app ?? '')) problems.push('app must be a short lowercase name such as \"gtm\"')\n const base = (env.JOURNEYS_BASE_URL ?? config.baseUrl ?? '').replace(/\\/$/, '')\n if (!/^https?:\\/\\/[^/]+$/.test(base)) problems.push(`baseUrl must be an origin such as https://app.example.com, got \"${base}\"`)\n const identities = config.identities ?? {}\n if (Object.keys(identities).length === 0) problems.push('identities must name at least one test identity')\n for (const [name, identity] of Object.entries(identities)) {\n if (name === 'anon') problems.push('\"anon\" is reserved for a signed-out context')\n if (!/^[a-z][a-z0-9-]*$/.test(name)) problems.push(`identity \"${name}\": use a lowercase name`)\n for (const key of ['emailEnv', 'passwordEnv'] as const) {\n if (!ENV_NAME.test(identity[key] ?? '')) problems.push(`identity \"${name}\": ${key} must be an environment variable NAME, not a value`)\n }\n if (identity.signIn !== 'password' && identity.signIn !== 'tangle') problems.push(`identity \"${name}\": signIn must be \"password\" or \"tangle\"`)\n }\n const chat: ChatContract = {\n ...DEFAULT_CHAT_CONTRACT,\n ...config.chat,\n failureText: [...DEFAULT_FAILURE_TEXT, ...(config.chat?.failureText ?? [])],\n stoppedText: [...DEFAULT_STOPPED_TEXT, ...(config.chat?.stoppedText ?? [])],\n }\n if (chat.threadPath && !/\\(\\?<threadId>/.test(chat.threadPath.source)) problems.push('chat.threadPath needs a named group (?<threadId>…)')\n const maxTurns = config.maxTurns ?? 6\n if (!Number.isInteger(maxTurns) || maxTurns < 0) problems.push('maxTurns must be a whole number')\n if (problems.length) throw new Error(`journeys config: ${problems.join('; ')}`)\n const stateDir = resolve(env.JOURNEYS_STATE_DIR ?? config.stateDir ?? join(homedir(), '.local/state/agent-app-journeys', config.app))\n return {\n resolved: true,\n app: config.app,\n baseUrl: base,\n identities,\n chat,\n auth: { ...DEFAULT_AUTH_PATHS, ...config.auth },\n maxTurns,\n stateDir,\n outDir: resolve(env.JOURNEYS_OUT ?? config.outDir ?? join(stateDir, 'out')),\n }\n}\n\n/** The ids in a thread URL, or null when the URL is not a thread on this origin. */\nexport function threadRouteIn(url: string, config: Pick<ResolvedJourneysConfig, 'baseUrl' | 'chat'>): ThreadRoute | null {\n if (!config.chat.threadPath) return null\n let parsed: URL\n try {\n parsed = new URL(url)\n } catch {\n return null\n }\n if (parsed.origin !== new URL(config.baseUrl).origin) return null\n const match = config.chat.threadPath.exec(parsed.pathname)\n const threadId = match?.groups?.threadId\n if (!threadId) return null\n const workspaceId = match?.groups?.workspaceId\n return workspaceId ? { threadId, workspaceId } : { threadId }\n}\n\n/** Environment variable names the config needs, for a vault loader. */\nexport function credentialNames(config: Pick<JourneysConfig, 'identities'>): string[] {\n return [...new Set(Object.values(config.identities).flatMap((identity) => [identity.emailEnv, identity.passwordEnv]))]\n}\n\n/** `JOURNEYS_CONFIG`, else the first config file in `dir`. */\nexport async function loadJourneysConfig(dir = process.cwd(), env: Record<string, string | undefined> = process.env): Promise<ResolvedJourneysConfig> {\n const file = env.JOURNEYS_CONFIG\n ? resolve(dir, env.JOURNEYS_CONFIG)\n : CONFIG_FILE_NAMES.map((name) => join(dir, name)).find((path) => existsSync(path))\n if (!file || !existsSync(file)) {\n throw new Error(`no ${CONFIG_FILE_NAMES[0]} in ${dir}; add one at the app root or set JOURNEYS_CONFIG`)\n }\n const loaded = (await import(pathToFileURL(file).href)) as { default?: JourneysConfig }\n if (!loaded.default) throw new Error(`${file} must export default defineJourneys({ … })`)\n return resolveJourneysConfig(loaded.default, env)\n}\n","/**\n * Making a journey's files safe to copy off the host.\n *\n * `scrubTrace` rewrites a Playwright trace.zip: it blanks cookie and\n * authorization headers and HAR cookie lists, blanks token-like query values,\n * drops the bodies of auth, token, session and collaboration calls, and then\n * replaces every needle (passwords, cookie values, the identities' emails)\n * anywhere in any entry. `assertNoSecrets` re-reads every output file, inside\n * the zips too, and refuses the whole folder if a password or cookie value\n * survived anywhere.\n */\nimport { readdirSync, readFileSync, statSync, openSync, closeSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { createZipWriter, inflateEntry, readCentralDirectory, readRaw } from './trace-zip.js'\n\nconst SENSITIVE_HEADERS = new Set([\n 'cookie', 'set-cookie', 'authorization', 'proxy-authorization', 'x-api-key',\n 'x-auth-token', 'x-stream-token', 'cf-access-token', 'x-csrf-token',\n])\nconst SENSITIVE_PATH = /\\/api\\/auth\\/|\\/auth\\/tangle\\/|token|session|\\/api\\/collaboration\\/|oauth|\\/consent|\\/api-access|api-key/i\nconst QUERY_NAMES = 'token|access_token|refresh_token|id_token|code|state|key|api_key|apikey|signature|sig|jwt|ticket|secret'\nconst QUERY = new RegExp(`([?&](?:${QUERY_NAMES})=)[^&\"'\\\\s\\\\\\\\]+`, 'gi')\nconst QUERY_NAME = new RegExp(`^(?:${QUERY_NAMES})$`, 'i')\nconst REDACTED = 'REDACTED'\n\ntype Json = null | boolean | number | string | Json[] | { [key: string]: Json }\ntype JsonObject = { [key: string]: Json }\n\nconst isObject = (v: Json | undefined): v is JsonObject => typeof v === 'object' && v !== null && !Array.isArray(v)\n\nfunction scrubHeaders(headers: Json | undefined): void {\n if (Array.isArray(headers)) {\n for (const h of headers) {\n if (isObject(h) && SENSITIVE_HEADERS.has(String(h.name ?? '').toLowerCase())) h.value = REDACTED\n }\n } else if (isObject(headers)) {\n for (const key of Object.keys(headers)) if (SENSITIVE_HEADERS.has(key.toLowerCase())) headers[key] = REDACTED\n }\n}\n\n/** Drop an inline or stored body; Playwright points at stored ones with `_file` or `_sha1`. */\nfunction forgetBody(holder: JsonObject, drop: Set<string>): void {\n for (const key of ['_file', '_sha1']) {\n const ref = holder[key]\n if (ref) {\n drop.add(String(ref).split('/').pop() ?? '')\n holder[key] = null\n }\n }\n if ('text' in holder) holder.text = REDACTED\n}\n\n/** Scrub any HAR-like request/response anywhere in one trace event. */\nfunction walk(node: Json | undefined, drop: Set<string>): void {\n if (Array.isArray(node)) {\n for (const v of node) walk(v, drop)\n return\n }\n if (!isObject(node)) return\n const req = node.request\n const res = node.response\n if (isObject(req) && 'url' in req) {\n const sensitive = SENSITIVE_PATH.test(String(req.url ?? '').split('?')[0] ?? '')\n scrubHeaders(req.headers)\n if ('cookies' in req) req.cookies = []\n const query = req.queryString\n if (Array.isArray(query)) {\n for (const q of query) if (isObject(q) && QUERY_NAME.test(String(q.name ?? ''))) q.value = REDACTED\n }\n if (sensitive && isObject(req.postData)) forgetBody(req.postData, drop)\n if (isObject(res)) {\n scrubHeaders(res.headers)\n if ('cookies' in res) res.cookies = []\n if (sensitive && isObject(res.content)) forgetBody(res.content, drop)\n }\n }\n for (const [key, value] of Object.entries(node)) {\n if (key.toLowerCase() === 'cookies' && Array.isArray(value)) node[key] = []\n else if (key === 'storageState') node[key] = null\n else if (SENSITIVE_HEADERS.has(key.toLowerCase()) && typeof value === 'string') node[key] = REDACTED\n else walk(value, drop)\n }\n}\n\n/** One `.trace` or `.network` JSONL entry, scrubbed. Bodies it dropped are added to `drop`. */\nexport function scrubJsonl(text: string, drop: Set<string>): string {\n const out: string[] = []\n for (const line of text.split('\\n')) {\n if (!line.trim()) continue\n let event: Json\n try {\n event = JSON.parse(line) as Json\n } catch {\n out.push(line.replace(QUERY, `$1${REDACTED}`))\n continue\n }\n walk(event, drop)\n out.push(JSON.stringify(event).replace(QUERY, `$1${REDACTED}`))\n }\n return out.join('\\n') + '\\n'\n}\n\n/** Every occurrence of every needle replaced. */\nexport function replaceNeedles(data: Buffer, needles: readonly string[]): Buffer {\n let out = data\n for (const needle of needles) {\n if (!needle) continue\n const n = Buffer.from(needle, 'utf8')\n if (out.indexOf(n) < 0) continue\n const parts: Buffer[] = []\n let from = 0\n for (let at = out.indexOf(n); at >= 0; at = out.indexOf(n, from)) {\n parts.push(out.subarray(from, at), Buffer.from(REDACTED))\n from = at + n.length\n }\n parts.push(out.subarray(from))\n out = Buffer.concat(parts)\n }\n return out\n}\n\nconst isEvents = (name: string) => name.endsWith('.trace') || name.endsWith('.network')\n\n/** Write a scrubbed copy of `src` to `dst`. Entries keep their order; dropped bodies are left out. */\nexport function scrubTrace(src: string, dst: string, needles: readonly string[]): { entries: number; dropped: number; rewritten: number } {\n const fd = openSync(src, 'r')\n try {\n const entries = readCentralDirectory(fd)\n const drop = new Set<string>()\n // Events first, so the bodies they point at are known before resources are copied.\n const events = new Map<string, Buffer>()\n for (const entry of entries) {\n if (!isEvents(entry.name)) continue\n events.set(entry.name, Buffer.from(scrubJsonl(inflateEntry(entry, readRaw(fd, entry)).toString('utf8'), drop), 'utf8'))\n }\n const writer = createZipWriter(dst)\n let dropped = 0\n let rewritten = 0\n for (const entry of entries) {\n const base = entry.name.split('/').pop() ?? ''\n if (entry.name.startsWith('resources/') && drop.has(base)) {\n dropped += 1\n continue\n }\n const raw = readRaw(fd, entry)\n const content = events.get(entry.name) ?? inflateEntry(entry, raw)\n const clean = replaceNeedles(content, needles)\n if (!events.has(entry.name) && clean === content) {\n writer.copy(entry, raw)\n } else {\n writer.add(entry.name, clean, entry)\n rewritten += 1\n }\n }\n writer.close()\n return { entries: entries.length, dropped, rewritten }\n } finally {\n closeSync(fd)\n }\n}\n\n/** Entries of a zip that still hold a hard needle, and how many mention a soft one. */\nfunction scanZip(path: string, hard: readonly string[], soft: readonly string[]): { hard: string[]; soft: number } {\n const fd = openSync(path, 'r')\n try {\n const hits: string[] = []\n let softHits = 0\n const hardBytes = hard.filter(Boolean).map((n) => Buffer.from(n, 'utf8'))\n const softBytes = soft.filter(Boolean).map((n) => Buffer.from(n, 'utf8'))\n for (const entry of readCentralDirectory(fd)) {\n const content = inflateEntry(entry, readRaw(fd, entry))\n if (hardBytes.some((n) => content.includes(n))) hits.push(entry.name)\n if (softBytes.some((n) => content.includes(n))) softHits += 1\n }\n return { hard: hits, soft: softHits }\n } finally {\n closeSync(fd)\n }\n}\n\n/**\n * Refuse to hand over a folder whose files hold a password or cookie value.\n * An identity's email only warns: it is a company test address, not a secret,\n * but it should be blurred before footage is shown outside the company.\n */\nexport function assertNoSecrets(dir: string, needles: { hard: readonly string[]; soft: readonly string[] }): { softHits: string[] } {\n const hits: string[] = []\n const softHits: string[] = []\n const hard = needles.hard.filter(Boolean).map((n) => Buffer.from(n, 'utf8'))\n const soft = needles.soft.filter(Boolean).map((n) => Buffer.from(n, 'utf8'))\n const visit = (d: string) => {\n for (const name of readdirSync(d)) {\n const path = join(d, name)\n if (statSync(path).isDirectory()) {\n visit(path)\n continue\n }\n if (path.endsWith('.zip')) {\n const found = scanZip(path, needles.hard, needles.soft)\n if (found.hard.length) hits.push(`${path} (${found.hard.slice(0, 5).join(', ')})`)\n if (found.soft) softHits.push(`${path} (${found.soft} entries)`)\n continue\n }\n const buf = readFileSync(path)\n if (hard.some((n) => buf.includes(n))) hits.push(path)\n if (soft.some((n) => buf.includes(n))) softHits.push(path)\n }\n }\n visit(dir)\n if (softHits.length) console.warn(`note: a test identity's email appears in ${softHits.join(', ')}; blur it before sharing outside the company`)\n if (hits.length) throw new Error(`REFUSING: secret material found in ${hits.join(', ')}; do not copy ${dir}`)\n return { softHits }\n}\n","/**\n * The slice of PKZIP a Playwright trace needs: read every entry of an archive\n * on disk one at a time, and write a new archive entry by entry.\n *\n * Why not `documents/zip`: that reader holds the archive in memory and refuses\n * zip64, and a recorded hour-long journey's trace is 6.6 GB with 49,117\n * entries, so offsets pass 4 GiB. This reader keeps\n * one entry in memory at a time and reads the zip64 records; the writer emits\n * zip64 fields only when a size, an offset or the entry count needs them.\n */\nimport { closeSync, fstatSync, openSync, readSync, writeSync } from 'node:fs'\nimport { deflateRawSync, inflateRawSync } from 'node:zlib'\nimport { crc32Update } from '../workspace-export/checksum.js'\n\nconst EOCD = 0x06054b50\nconst ZIP64_EOCD = 0x06064b50\nconst ZIP64_LOCATOR = 0x07064b50\nconst CENTRAL = 0x02014b50\nconst LOCAL = 0x04034b50\nconst U16 = 0xffff\nconst U32 = 0xffffffff\n\ninterface ZipEntryInfo {\n readonly name: string\n readonly method: number\n readonly crc32: number\n readonly compressedSize: number\n readonly uncompressedSize: number\n readonly localOffset: number\n readonly dosTime: number\n readonly dosDate: number\n}\n\nfunction readAt(fd: number, position: number, length: number): Buffer {\n const out = Buffer.alloc(length)\n let done = 0\n while (done < length) {\n const n = readSync(fd, out, done, length - done, position + done)\n if (n === 0) throw new Error(`zip: unexpected end of file at ${position + done}`)\n done += n\n }\n return out\n}\n\nconst u64 = (b: Buffer, at: number) => Number(b.readBigUInt64LE(at))\n\n/** Every entry in the central directory, sizes and offsets resolved through zip64 extras. */\nexport function readCentralDirectory(fd: number): ZipEntryInfo[] {\n const size = fstatSync(fd).size\n const tailLength = Math.min(size, 22 + U16 + 20)\n const tail = readAt(fd, size - tailLength, tailLength)\n let eocd = -1\n for (let i = tail.length - 22; i >= 0; i -= 1) {\n if (tail.readUInt32LE(i) === EOCD && i + 22 + tail.readUInt16LE(i + 20) === tail.length) {\n eocd = i\n break\n }\n }\n if (eocd < 0) throw new Error('zip: no end-of-central-directory record')\n let count = tail.readUInt16LE(eocd + 10)\n let cdSize = tail.readUInt32LE(eocd + 12)\n let cdOffset = tail.readUInt32LE(eocd + 16)\n if (eocd >= 20 && tail.readUInt32LE(eocd - 20) === ZIP64_LOCATOR) {\n const record = readAt(fd, u64(tail, eocd - 20 + 8), 56)\n if (record.readUInt32LE(0) !== ZIP64_EOCD) throw new Error('zip: zip64 locator points at no zip64 record')\n count = u64(record, 32)\n cdSize = u64(record, 40)\n cdOffset = u64(record, 48)\n }\n const cd = readAt(fd, cdOffset, cdSize)\n const entries: ZipEntryInfo[] = []\n let at = 0\n for (let i = 0; i < count; i += 1) {\n if (cd.readUInt32LE(at) !== CENTRAL) throw new Error(`zip: central directory is broken at entry ${i + 1} of ${count}`)\n const nameLength = cd.readUInt16LE(at + 28)\n const extraLength = cd.readUInt16LE(at + 30)\n const commentLength = cd.readUInt16LE(at + 32)\n let compressedSize = cd.readUInt32LE(at + 20)\n let uncompressedSize = cd.readUInt32LE(at + 24)\n let localOffset = cd.readUInt32LE(at + 42)\n const extra = cd.subarray(at + 46 + nameLength, at + 46 + nameLength + extraLength)\n for (let e = 0; e + 4 <= extra.length; ) {\n const id = extra.readUInt16LE(e)\n const len = extra.readUInt16LE(e + 2)\n if (id === 0x0001) {\n // Present in this order, and only for the fields set to 0xffffffff.\n let p = e + 4\n if (uncompressedSize === U32) { uncompressedSize = u64(extra, p); p += 8 }\n if (compressedSize === U32) { compressedSize = u64(extra, p); p += 8 }\n if (localOffset === U32) { localOffset = u64(extra, p); p += 8 }\n }\n e += 4 + len\n }\n entries.push({\n name: cd.toString('utf8', at + 46, at + 46 + nameLength),\n method: cd.readUInt16LE(at + 10),\n crc32: cd.readUInt32LE(at + 16),\n compressedSize,\n uncompressedSize,\n localOffset,\n dosTime: cd.readUInt16LE(at + 12),\n dosDate: cd.readUInt16LE(at + 14),\n })\n at += 46 + nameLength + extraLength + commentLength\n }\n return entries\n}\n\n/** One entry's stored bytes, still compressed. */\nexport function readRaw(fd: number, entry: ZipEntryInfo): Buffer {\n const local = readAt(fd, entry.localOffset, 30)\n if (local.readUInt32LE(0) !== LOCAL) throw new Error(`zip: '${entry.name}' has no local header`)\n const start = entry.localOffset + 30 + local.readUInt16LE(26) + local.readUInt16LE(28)\n return readAt(fd, start, entry.compressedSize)\n}\n\n/** One entry's content. */\nexport function inflateEntry(entry: ZipEntryInfo, raw: Buffer): Buffer {\n if (entry.method === 0) return raw\n if (entry.method === 8) return inflateRawSync(raw)\n throw new Error(`zip: '${entry.name}' uses unsupported compression method ${entry.method}`)\n}\n\ninterface ZipWriter {\n /** Add an entry from its content (deflated here). */\n add(name: string, content: Buffer, from?: Pick<ZipEntryInfo, 'dosTime' | 'dosDate'>): void\n /** Add an entry exactly as another archive stored it. */\n copy(entry: ZipEntryInfo, raw: Buffer): void\n close(): void\n}\n\ninterface Written {\n name: Buffer\n method: number\n crc32: number\n compressedSize: number\n uncompressedSize: number\n offset: number\n dosTime: number\n dosDate: number\n}\n\n/** Write a zip to `path`, entries in the order added. `forceZip64` exercises the large-archive records in tests. */\nexport function createZipWriter(path: string, opts: { forceZip64?: boolean } = {}): ZipWriter {\n const fd = openSync(path, 'w', 0o600)\n let position = 0\n const written: Written[] = []\n const put = (b: Buffer) => {\n let done = 0\n while (done < b.length) done += writeSync(fd, b, done, b.length - done)\n position += b.length\n }\n const big = (n: number) => opts.forceZip64 === true || n >= U32\n const writeEntry = (w: Omit<Written, 'offset'>, data: Buffer) => {\n const zip64 = big(w.compressedSize) || big(w.uncompressedSize)\n const header = Buffer.alloc(30 + w.name.length + (zip64 ? 20 : 0))\n header.writeUInt32LE(LOCAL, 0)\n header.writeUInt16LE(zip64 ? 45 : 20, 4)\n header.writeUInt16LE(0x0800, 6)\n header.writeUInt16LE(w.method, 8)\n header.writeUInt16LE(w.dosTime, 10)\n header.writeUInt16LE(w.dosDate, 12)\n header.writeUInt32LE(w.crc32, 14)\n header.writeUInt32LE(zip64 ? U32 : w.compressedSize, 18)\n header.writeUInt32LE(zip64 ? U32 : w.uncompressedSize, 22)\n header.writeUInt16LE(w.name.length, 26)\n header.writeUInt16LE(zip64 ? 20 : 0, 28)\n w.name.copy(header, 30)\n if (zip64) {\n const e = 30 + w.name.length\n header.writeUInt16LE(0x0001, e)\n header.writeUInt16LE(16, e + 2)\n header.writeBigUInt64LE(BigInt(w.uncompressedSize), e + 4)\n header.writeBigUInt64LE(BigInt(w.compressedSize), e + 12)\n }\n const offset = position\n put(header)\n put(data)\n written.push({ ...w, offset })\n }\n return {\n add(name, content, from) {\n const data = deflateRawSync(content)\n writeEntry({\n name: Buffer.from(name, 'utf8'),\n method: 8,\n crc32: crc32Update(0, content),\n compressedSize: data.length,\n uncompressedSize: content.length,\n dosTime: from?.dosTime ?? 0,\n dosDate: from?.dosDate ?? 0x21,\n }, data)\n },\n copy(entry, raw) {\n writeEntry({\n name: Buffer.from(entry.name, 'utf8'),\n method: entry.method,\n crc32: entry.crc32,\n compressedSize: entry.compressedSize,\n uncompressedSize: entry.uncompressedSize,\n dosTime: entry.dosTime,\n dosDate: entry.dosDate,\n }, raw)\n },\n close() {\n const cdOffset = position\n for (const w of written) {\n const fields: bigint[] = []\n if (big(w.uncompressedSize)) fields.push(BigInt(w.uncompressedSize))\n if (big(w.compressedSize)) fields.push(BigInt(w.compressedSize))\n if (big(w.offset)) fields.push(BigInt(w.offset))\n const extraLength = fields.length ? 4 + 8 * fields.length : 0\n const h = Buffer.alloc(46 + w.name.length + extraLength)\n h.writeUInt32LE(CENTRAL, 0)\n h.writeUInt16LE(45, 4)\n h.writeUInt16LE(fields.length ? 45 : 20, 6)\n h.writeUInt16LE(0x0800, 8)\n h.writeUInt16LE(w.method, 10)\n h.writeUInt16LE(w.dosTime, 12)\n h.writeUInt16LE(w.dosDate, 14)\n h.writeUInt32LE(w.crc32, 16)\n h.writeUInt32LE(big(w.compressedSize) ? U32 : w.compressedSize, 20)\n h.writeUInt32LE(big(w.uncompressedSize) ? U32 : w.uncompressedSize, 24)\n h.writeUInt16LE(w.name.length, 28)\n h.writeUInt16LE(extraLength, 30)\n h.writeUInt32LE(big(w.offset) ? U32 : w.offset, 42)\n w.name.copy(h, 46)\n if (fields.length) {\n const e = 46 + w.name.length\n h.writeUInt16LE(0x0001, e)\n h.writeUInt16LE(8 * fields.length, e + 2)\n fields.forEach((v, i) => h.writeBigUInt64LE(v, e + 4 + 8 * i))\n }\n put(h)\n }\n const cdSize = position - cdOffset\n const count = written.length\n const zip64 = opts.forceZip64 === true || count >= U16 || cdOffset >= U32 || cdSize >= U32\n if (zip64) {\n const recordOffset = position\n const r = Buffer.alloc(56)\n r.writeUInt32LE(ZIP64_EOCD, 0)\n r.writeBigUInt64LE(44n, 4)\n r.writeUInt16LE(45, 12)\n r.writeUInt16LE(45, 14)\n r.writeBigUInt64LE(BigInt(count), 24)\n r.writeBigUInt64LE(BigInt(count), 32)\n r.writeBigUInt64LE(BigInt(cdSize), 40)\n r.writeBigUInt64LE(BigInt(cdOffset), 48)\n put(r)\n const l = Buffer.alloc(20)\n l.writeUInt32LE(ZIP64_LOCATOR, 0)\n l.writeBigUInt64LE(BigInt(recordOffset), 8)\n l.writeUInt32LE(1, 16)\n put(l)\n }\n const end = Buffer.alloc(22)\n end.writeUInt32LE(EOCD, 0)\n end.writeUInt16LE(zip64 ? U16 : count, 8)\n end.writeUInt16LE(zip64 ? U16 : count, 10)\n end.writeUInt32LE(zip64 ? U32 : cdSize, 12)\n end.writeUInt32LE(zip64 ? U32 : cdOffset, 16)\n put(end)\n closeSync(fd)\n },\n }\n}\n","/**\n * Signed-in browser state for an app's test identities, with no login form in\n * any recorded frame.\n *\n * Sign-in happens over HTTP, never in a rendered page, so a recording starts\n * already signed in and no frame can show a password. The resulting storage\n * state (session cookies) is cached per origin and identity under the state\n * directory (mode 0600) and reused while the app's session endpoint still\n * answers with a verified user. Journeys running in parallel share it, so a\n * burst of journeys cannot trip an auth rate limit.\n *\n * Never press Sign out in a shared session: it revokes the session every\n * journey on the host is using. A journey that signs out opens its context with\n * `{ fresh: true }`, which signs in a session of its own.\n */\nimport { chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync } from 'node:fs'\nimport { join } from 'node:path'\nimport type { APIRequestContext } from 'playwright'\nimport type { JourneyIdentity, ResolvedJourneysConfig } from './config.js'\n\nexport interface SessionUser {\n id: string\n name: string | null\n emailVerified: boolean\n}\n\nclass SignInError extends Error {\n constructor(readonly status: number, message: string) {\n super(message)\n }\n}\n\nconst sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms))\n\nasync function playwrightRequest() {\n try {\n return (await import('playwright')).request\n } catch {\n throw new Error('journeys need the optional `playwright` peer: install playwright in the app that runs them')\n }\n}\n\nfunction sessionDir(config: ResolvedJourneysConfig): string {\n return join(config.stateDir, 'sessions', new URL(config.baseUrl).host)\n}\n\nfunction storageStatePath(config: ResolvedJourneysConfig, identity: string): string {\n return join(sessionDir(config), `${identity}.storage.json`)\n}\n\nfunction need(name: string): string {\n const value = process.env[name]?.trim()\n if (!value) throw new Error(`${name} is unset: load it from the host's vault into this process (the value is never printed)`)\n return value\n}\n\n/** The signed-in user behind a storage state, or null when it no longer signs in. */\nexport async function sessionUser(config: ResolvedJourneysConfig, state: string): Promise<SessionUser | null> {\n if (!existsSync(state)) return null\n const request = await playwrightRequest()\n const ctx = await request.newContext({ baseURL: config.baseUrl, storageState: state })\n try {\n const r = await ctx.get(config.auth.session, { maxRedirects: 0, timeout: 20_000 })\n if (!r.ok()) return null\n const body = (await r.json().catch(() => null)) as { user?: { id?: string; name?: string; emailVerified?: boolean } } | null\n const user = body?.user\n if (!user?.id) return null\n return { id: user.id, name: user.name ?? null, emailVerified: user.emailVerified === true }\n } finally {\n await ctx.dispose()\n }\n}\n\nasync function signInWithPassword(ctx: APIRequestContext, config: ResolvedJourneysConfig, email: string, password: string): Promise<void> {\n const r = await ctx.post(`${config.baseUrl}${config.auth.passwordSignIn}`, {\n headers: { 'content-type': 'application/json', origin: config.baseUrl },\n data: { email, password },\n maxRedirects: 0,\n })\n if (r.status() !== 200) throw new SignInError(r.status(), `email sign-in returned ${r.status()}`)\n}\n\n/** \"Log in with Tangle\": the app's start route, Platform sign-in, authorize, the app's callback. */\nasync function signInWithTangle(ctx: APIRequestContext, config: ResolvedJourneysConfig, email: string, password: string): Promise<void> {\n const base = config.baseUrl\n const start = await ctx.get(`${base}${config.auth.tangleStart}`, { maxRedirects: 0 })\n const first = start.headers()['location']\n if (!first) throw new SignInError(start.status(), `SSO start returned ${start.status()} without a redirect`)\n const authorize = new URL(first, base).toString()\n const platform = new URL(authorize).origin\n const signIn = await ctx.post(`${platform}/api/auth/sign-in/email`, {\n headers: { 'content-type': 'application/json', origin: platform },\n data: { email, password },\n maxRedirects: 0,\n })\n if (signIn.status() !== 200) throw new SignInError(signIn.status(), `Platform sign-in returned ${signIn.status()}`)\n const startPrefix = config.auth.tangleStart.replace(/\\/start$/, '/')\n let next = authorize\n for (let hop = 0; hop < 8; hop += 1) {\n const r = await ctx.get(next, { maxRedirects: 0 })\n const location = r.headers()['location']\n // Only a pathname is ever reported: the query carries OAuth codes.\n if (!location) throw new SignInError(r.status(), `SSO stopped at ${new URL(next).pathname} with ${r.status()}`)\n const url = new URL(location, next)\n if (url.origin === new URL(base).origin && !url.pathname.startsWith(startPrefix)) {\n if (url.pathname.startsWith('/login')) throw new SignInError(401, 'the app callback refused the sign-in')\n return\n }\n next = url.toString()\n }\n throw new SignInError(0, 'SSO did not return to the app within 8 redirects')\n}\n\n/** A cross-process lock: mkdir is atomic. A lock older than two minutes is stale. */\nasync function withLock<T>(dir: string, work: () => Promise<T>): Promise<T> {\n const deadline = Date.now() + 180_000\n for (;;) {\n try {\n mkdirSync(dir)\n break\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error\n const age = Date.now() - (statSync(dir, { throwIfNoEntry: false })?.mtimeMs ?? Date.now())\n if (age > 120_000) rmSync(dir, { recursive: true, force: true })\n if (Date.now() > deadline) throw new Error(`timed out waiting for ${dir}`)\n await sleep(500)\n }\n }\n try {\n return await work()\n } finally {\n rmSync(dir, { recursive: true, force: true })\n }\n}\n\nfunction identityOf(config: ResolvedJourneysConfig, name: string): JourneyIdentity {\n const identity = config.identities[name]\n if (!identity) throw new Error(`\"${name}\" is not an identity in the ${config.app} journeys config (${Object.keys(config.identities).join(', ')})`)\n return identity\n}\n\n/**\n * Path to a storage state signed in as `identity`. Reused while valid;\n * `fresh` signs in a session of its own (for a journey that signs out).\n */\nexport async function storageStateFor(\n config: ResolvedJourneysConfig,\n name: string,\n opts: { fresh?: boolean } = {},\n): Promise<{ path: string; user: SessionUser }> {\n const identity = identityOf(config, name)\n const dir = sessionDir(config)\n mkdirSync(dir, { recursive: true, mode: 0o700 })\n const file = opts.fresh ? join(dir, `${name}.${process.pid}.${Date.now()}.storage.json`) : storageStatePath(config, name)\n const request = await playwrightRequest()\n return withLock(join(dir, `signin-${name}.lock`), async () => {\n if (!opts.fresh) {\n const cached = await sessionUser(config, file)\n if (cached) return { path: file, user: cached }\n }\n const email = need(identity.emailEnv)\n const password = need(identity.passwordEnv)\n for (let attempt = 1; ; attempt += 1) {\n const ctx = await request.newContext({ baseURL: config.baseUrl })\n try {\n if (identity.signIn === 'password') await signInWithPassword(ctx, config, email, password)\n else await signInWithTangle(ctx, config, email, password)\n const tmp = `${file}.tmp`\n await ctx.storageState({ path: tmp })\n chmodSync(tmp, 0o600)\n renameSync(tmp, file)\n break\n } catch (error) {\n const status = error instanceof SignInError ? error.status : 0\n if (status !== 429 || attempt >= 4) throw error\n await sleep(15_000 * attempt)\n } finally {\n await ctx.dispose()\n }\n }\n const user = await sessionUser(config, file)\n if (!user) throw new Error(`${name} signed in but ${config.auth.session} has no user`)\n // A read-only journey can still run; one that chats will be refused, so say so before it tries.\n if (!user.emailVerified) console.warn(`${name} signed in but is not email-verified; an app that requires verification will refuse its chat`)\n return { path: file, user }\n })\n}\n\n/**\n * Every value that must never leave the host. `hard`: passwords and each cookie\n * value (whole, URL-decoded, and its token half). `soft`: the identities'\n * emails, which are warned about but not refused.\n */\nexport function secretNeedles(config: ResolvedJourneysConfig): { hard: string[]; soft: string[] } {\n const hard = new Set<string>()\n const soft = new Set<string>()\n for (const identity of Object.values(config.identities)) {\n const password = process.env[identity.passwordEnv]?.trim()\n if (password) hard.add(password)\n const email = process.env[identity.emailEnv]?.trim()\n if (email) soft.add(email)\n }\n const root = join(config.stateDir, 'sessions')\n const stack = existsSync(root) ? [root] : []\n while (stack.length) {\n const dir = stack.pop()!\n for (const entry of readdirSync(dir, { withFileTypes: true })) {\n const path = join(dir, entry.name)\n if (entry.isDirectory()) stack.push(path)\n else if (entry.name.endsWith('.storage.json')) addCookieNeedles(path, hard)\n }\n }\n return { hard: [...hard], soft: [...soft] }\n}\n\nfunction addCookieNeedles(file: string, hard: Set<string>): void {\n try {\n const state = JSON.parse(readFileSync(file, 'utf8')) as { cookies?: { value: string }[] }\n for (const { value } of state.cookies ?? []) {\n if (!value || value.length < 16) continue\n hard.add(value)\n let decoded = value\n try {\n decoded = decodeURIComponent(value)\n } catch {\n // A value that is not URI-encoded is already its own decoded form.\n }\n hard.add(decoded)\n const token = decoded.split('.')[0] ?? ''\n if (token.length >= 16) hard.add(token)\n }\n } catch {\n // A half-written state file holds nothing a finished run used.\n }\n}\n","/**\n * A recording turned into files a person can watch.\n *\n * <label>-full.mp4 H.264, the whole session at real speed, with an 84 px\n * caption bar under the UI: the chapter line and an elapsed clock\n * <label>.srt the same chapters as a sidecar caption file\n * <label>-highlights.mp4 at most 178 s: waits and idle stretches sped up, and the caption\n * says by how much (\"[01:09] First text after 23 s » 4.2x, 21 s real (whole wait 41 s)\")\n * <label>-x2.mp4 optional: the full video at 2x\n *\n * Captions sit in their own bar so they never cover the composer or a toast.\n * Needs `ffmpeg` and `ffprobe` on PATH; work runs at nice 10 on 2 threads.\n */\nimport { execFileSync } from 'node:child_process'\nimport { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'\nimport { basename, join } from 'node:path'\n\nexport interface Chapter {\n /** Epoch ms. */\n at: number\n caption: string\n /** Context label, or null for every context. */\n label: string | null\n kind: 'step' | 'wait'\n /** Epoch ms a wait ended. */\n until?: number\n}\n\nexport interface Cue {\n start: number\n end: number\n text: string\n}\n\nexport interface HighlightSegment {\n /** Source range, seconds. */\n a: number\n b: number\n /** Speed-up factor. */\n k: number\n text: string\n}\n\nconst W = 1440\nconst H = 900\nconst BAR = 84\nexport const MAX_HIGHLIGHTS_S = 178\n\nconst FONT_CANDIDATES = [\n '/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',\n '/usr/share/fonts/dejavu/DejaVuSansMono.ttf',\n '/System/Library/Fonts/Menlo.ttc',\n]\n\nfunction monoFont(): string | null {\n const configured = process.env.JOURNEYS_FONT_MONO\n if (configured && existsSync(configured)) return configured\n return FONT_CANDIDATES.find((path) => existsSync(path)) ?? null\n}\n\nfunction ff(args: string[]): void {\n execFileSync('nice', ['-n', '10', 'ffmpeg', '-hide_banner', '-loglevel', 'error', '-y', ...args], { stdio: ['ignore', 'inherit', 'inherit'] })\n}\n\nexport function probeSeconds(file: string): number {\n const out = execFileSync('ffprobe', ['-v', 'error', '-show_entries', 'format=duration', '-of', 'default=nw=1:nk=1', file], { encoding: 'utf8' }).trim()\n const n = Number(out)\n if (!Number.isFinite(n) || n <= 0) throw new Error(`ffprobe could not read the duration of ${file}: ${out}`)\n return n\n}\n\nconst pad2 = (n: number) => String(Math.floor(n)).padStart(2, '0')\nconst mmss = (s: number) => `${pad2(s / 60)}:${pad2(s % 60)}`\nconst srtTime = (s: number) => {\n const ms = Math.max(0, Math.round(s * 1000))\n return `${pad2(ms / 3_600_000)}:${pad2((ms / 60_000) % 60)}:${pad2((ms / 1000) % 60)},${String(ms % 1000).padStart(3, '0')}`\n}\nconst assTime = (s: number) => {\n const cs = Math.max(0, Math.round(s * 100))\n return `${Math.floor(cs / 360_000)}:${pad2((cs / 6000) % 60)}:${pad2((cs / 100) % 60)}.${String(cs % 100).padStart(2, '0')}`\n}\nconst humanSeconds = (s: number) => (s >= 90 ? `${Math.floor(s / 60)} min ${Math.round(s % 60)} s` : `${Math.round(s)} s`)\n\n/** Chapters on the video's own clock; each caption holds until the next. */\nexport function chapterCues(chapters: readonly Chapter[], t0: number, duration: number): Cue[] {\n const points = chapters\n .map((c) => ({ ...c, s: (c.at - t0) / 1000, e: c.until ? (c.until - t0) / 1000 : undefined }))\n .filter((c) => c.s < duration)\n .sort((a, b) => a.s - b.s)\n const cues: Cue[] = []\n for (let i = 0; i < points.length; i += 1) {\n const c = points[i]!\n const start = Math.max(0, c.s)\n const end = Math.min(duration, points[i + 1]?.s ?? duration)\n if (end - start < 0.05) continue\n const text = c.kind === 'wait' && c.e !== undefined ? `${c.caption} (real wait ${humanSeconds(c.e - c.s)})` : c.caption\n cues.push({ start, end, text })\n }\n return cues\n}\n\nfunction srtText(cues: readonly Cue[]): string {\n return cues.map((c, i) => `${i + 1}\\n${srtTime(c.start)} --> ${srtTime(c.end)}\\n${c.text}\\n`).join('\\n')\n}\n\nfunction assText(cues: readonly Cue[]): string {\n const esc = (t: string) => t.replace(/\\\\/g, '\\\\\\\\').replace(/[{}]/g, '').replace(/\\n/g, '\\\\N')\n const head = `[Script Info]\\nScriptType: v4.00+\\nPlayResX: ${W}\\nPlayResY: ${H + BAR}\\nWrapStyle: 0\\n\\n[V4+ Styles]\\nFormat: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding\\nStyle: Bar,DejaVu Sans,26,&H00FFFFFF,&H00FFFFFF,&H00000000,&H00000000,0,0,0,0,100,100,0,0,1,0,0,1,28,200,14,1\\n\\n[Events]\\nFormat: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\\n`\n return head + cues.map((c) => `Dialogue: 0,${assTime(c.start)},${assTime(c.end)},Bar,,0,0,0,,${esc(c.text)}`).join('\\n') + '\\n'\n}\n\n/**\n * The highlights cut: which source ranges, at what speed, under which caption.\n * A wait longer than 6 s plays in about 5 s; an idle stretch longer than 15 s\n * plays in about 10 s; then everything scales to fit {@link MAX_HIGHLIGHTS_S}.\n */\nexport function highlightPlan(chapters: readonly Chapter[], t0: number, duration: number): HighlightSegment[] {\n const pts = chapters\n .map((c) => ({ ...c, s: Math.max(0, (c.at - t0) / 1000), e: c.until ? (c.until - t0) / 1000 : undefined }))\n .sort((x, y) => x.s - y.s)\n const cuts = new Set<number>([0, duration])\n for (const p of pts) {\n if (p.s < duration) cuts.add(Math.round(p.s * 10) / 10)\n if (p.e !== undefined && p.e < duration) cuts.add(Math.round(p.e * 10) / 10)\n }\n const bounds = [...cuts].sort((x, y) => x - y)\n const segs: { a: number; b: number; k: number; text: string; wait: boolean; whole: number }[] = []\n for (let i = 0; i + 1 < bounds.length; i += 1) {\n const a = bounds[i]!\n const b = bounds[i + 1]!\n if (b - a < 0.15) continue\n const wait = [...pts].reverse().find((p) => p.kind === 'wait' && p.e !== undefined && p.s <= a + 0.05 && a < p.e - 0.05)\n // The latest step caption wins (e.g. \"First text after 31 s\" inside a wait); the wait adds its total.\n const step = [...pts].reverse().find((p) => p.kind === 'step' && p.s <= a + 0.05 && (!wait || p.s >= wait.s - 0.05))\n const len = b - a\n const k = wait ? (len > 6 ? len / 5 : 1) : len > 15 ? len / 10 : 1\n segs.push({ a, b, k, text: step?.caption ?? wait?.caption ?? '', wait: Boolean(wait), whole: wait?.e !== undefined ? wait.e - wait.s : 0 })\n }\n const shown = segs.reduce((n, s) => n + (s.b - s.a) / s.k, 0)\n const f = shown > MAX_HIGHLIGHTS_S ? shown / MAX_HIGHLIGHTS_S : 1\n return segs.map((s) => {\n const k = s.k * f\n const len = s.b - s.a\n const x = k >= 10 ? Math.round(k) : Math.round(k * 10) / 10\n const speed = k > 1.05 ? ` » ${x}x, ${humanSeconds(len)} real${s.wait ? ` (whole wait ${humanSeconds(s.whole)})` : ''}` : ''\n return { a: s.a, b: s.b, k, text: `[${mmss(s.a)}] ${s.text}${speed}` }\n })\n}\n\ninterface PostProcessInput {\n webm: string\n /** Raw working folder on the host; keeps the webm and chapters for a rebuild. */\n workDir: string\n videoDir: string\n label: string\n /** Epoch ms the recorded page was created. */\n t0: number\n wallSeconds: number\n chapters: readonly Chapter[]\n speedup2x: boolean\n}\n\nexport function postProcessVideo(o: PostProcessInput): string[] {\n mkdirSync(o.videoDir, { recursive: true })\n const keep = join(o.workDir, `${o.label}.webm`)\n if (o.webm !== keep) copyFileSync(o.webm, keep)\n writeFileSync(join(o.workDir, `${o.label}.chapters.json`), JSON.stringify({ t0: o.t0, wallSeconds: o.wallSeconds, chapters: o.chapters }))\n return renderAll(keep, o.workDir, o.videoDir, o.label, o.t0, o.chapters, o.speedup2x, o.wallSeconds)\n}\n\n/** Re-render from a raw folder after editing `<label>.chapters.json` by hand. */\nexport function rebuildVideo(rawLabelDir: string, videoDir: string, label: string, speedup2x: boolean): string[] {\n const meta = JSON.parse(readFileSync(join(rawLabelDir, `${label}.chapters.json`), 'utf8')) as { t0: number; wallSeconds: number; chapters: Chapter[] }\n return renderAll(join(rawLabelDir, `${label}.webm`), rawLabelDir, videoDir, label, meta.t0, meta.chapters, speedup2x, meta.wallSeconds)\n}\n\nfunction renderAll(webm: string, work: string, videoDir: string, label: string, t0: number, chapters: readonly Chapter[], speedup2x: boolean, wallSeconds: number): string[] {\n const clean = join(work, `${label}.clean.mp4`)\n ff(['-i', webm, '-vf', `fps=25,scale=${W}:${H}:flags=lanczos,format=yuv420p`, '-c:v', 'libx264', '-preset', 'veryfast', '-crf', '22', '-threads', '2', '-an', clean])\n const duration = probeSeconds(clean)\n // Measured 2026-10-11 against a clock burned into the page: video time tracks\n // wall clock from page creation to within 0.2 s.\n if (duration < wallSeconds - 3) console.warn(`video is ${duration.toFixed(1)} s but ${wallSeconds.toFixed(1)} s passed before recording stopped; late captions may be early`)\n\n const cues = chapterCues(chapters, t0, duration)\n const srt = join(videoDir, `${label}.srt`)\n writeFileSync(srt, srtText(cues))\n const ass = join(work, `${label}.full.ass`)\n writeFileSync(ass, assText(cues))\n const full = join(videoDir, `${label}-full.mp4`)\n const font = monoFont()\n const clock = `drawtext=${font ? `fontfile=${font}` : 'font=monospace'}:text='%{pts\\\\:hms}':x=w-tw-28:y=h-${BAR / 2}-th/2:fontsize=26:fontcolor=white@0.8`\n ff(['-i', clean, '-vf', `pad=${W}:${H + BAR}:0:0:color=0x111111,ass=${ass},${clock}`, '-c:v', 'libx264', '-preset', 'veryfast', '-crf', '23', '-threads', '2', '-pix_fmt', 'yuv420p', '-movflags', '+faststart', full])\n\n const plan = highlightPlan(chapters, t0, duration)\n const segDir = join(work, `${label}.segments`)\n mkdirSync(segDir, { recursive: true })\n const list: string[] = []\n const hcues: Cue[] = []\n let at = 0\n plan.forEach((s, i) => {\n const seg = join(segDir, `${String(i).padStart(3, '0')}.mp4`)\n ff(['-ss', s.a.toFixed(3), '-t', (s.b - s.a).toFixed(3), '-i', clean, '-vf', `setpts=PTS/${s.k.toFixed(4)},fps=25`, '-an', '-c:v', 'libx264', '-preset', 'veryfast', '-crf', '23', '-threads', '2', '-pix_fmt', 'yuv420p', seg])\n const len = probeSeconds(seg)\n list.push(`file '${seg}'`)\n hcues.push({ start: at, end: at + len, text: s.text })\n at += len\n })\n const listFile = join(segDir, 'list.txt')\n writeFileSync(listFile, list.join('\\n') + '\\n')\n const joined = join(work, `${label}.highlights.raw.mp4`)\n ff(['-f', 'concat', '-safe', '0', '-i', listFile, '-c', 'copy', joined])\n const hass = join(work, `${label}.highlights.ass`)\n writeFileSync(hass, assText(hcues))\n const highlights = join(videoDir, `${label}-highlights.mp4`)\n ff(['-i', joined, '-vf', `pad=${W}:${H + BAR}:0:0:color=0x111111,ass=${hass}`, '-c:v', 'libx264', '-preset', 'veryfast', '-crf', '23', '-threads', '2', '-pix_fmt', 'yuv420p', '-movflags', '+faststart', highlights])\n const out = [full, srt, highlights]\n if (speedup2x) {\n const x2 = join(videoDir, `${label}-x2.mp4`)\n ff(['-i', full, '-vf', 'setpts=PTS/2,fps=25', '-an', '-c:v', 'libx264', '-preset', 'veryfast', '-crf', '23', '-threads', '2', '-pix_fmt', 'yuv420p', '-movflags', '+faststart', x2])\n out.push(x2)\n }\n console.log(`video ${label}: full ${duration.toFixed(1)} s, highlights ${at.toFixed(1)} s from ${plan.length} segments`)\n return out\n}\n\n/** Seconds at which to grab frames: one per caption (1.5 s in), at most `max`, evenly spread. */\nexport function frameTimes(srt: string | null, times: readonly number[], max = 10): number[] {\n let ts = [...times]\n if (!ts.length && srt) {\n ts = srt.split('\\n').filter((l) => l.includes('-->')).map((l) => {\n const [h = '0', m = '0', rest = '0'] = l.split(' --> ')[0]!.split(':')\n return Number(h) * 3600 + Number(m) * 60 + Number(rest.replace(',', '.')) + 1.5\n })\n }\n if (ts.length > max) {\n const step = ts.length / max\n ts = Array.from({ length: max }, (_, i) => ts[Math.floor(i * step)]!)\n }\n return ts\n}\n\n/** PNG frames of a video, named by label and timestamp, into `outDir`. */\nexport function extractFrames(video: string, srtFile: string | null, outDir: string, times: readonly number[], max = 10): string[] {\n const srt = srtFile && existsSync(srtFile) ? readFileSync(srtFile, 'utf8') : null\n return frameTimes(srt, times, max).map((t, i) => {\n const f = join(outDir, `frame-${basename(video).replace(/-full\\.mp4$/, '')}-${String(i + 1).padStart(2, '0')}-${mmss(t).replace(':', 'm')}s.png`)\n ff(['-ss', t.toFixed(2), '-i', video, '-frames:v', '1', f])\n return f\n })\n}\n","/**\n * The one file a reviewer opens: INDEX.md for a folder of recorded journeys.\n *\n * It lists the highlight cuts first, the critic's scorecard, the ranked fix\n * list (verified failures by rank, each with its evidence, fix, number to beat\n * and proving test), every recorded turn with its scored outcome, every video,\n * and what stayed unproven. The renderer is pure; `collectJourneyFiles` reads\n * the folder.\n */\nimport { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'\nimport { join, relative } from 'node:path'\nimport type { TurnRecord } from './journey.js'\n\n/** What the skeptical critic returns; the same shape the prove-journeys workflow asks for. */\nexport interface CriticResult {\n headline: string\n scorecard?: { journey: string; verifiedVerdict: string; keyTiming?: string; qualityGrade?: string; topIssue: string; video?: string }[]\n verifiedFailures?: {\n rank: number\n severity: string\n what: string\n journeys?: string[]\n evidence: string\n likelyCause?: string\n fix: string\n numberToBeat: string\n test: string\n }[]\n refutedOrUnproven?: string[]\n coverageGaps?: string[]\n}\n\nexport interface JourneyFiles {\n /** Folder relative to the index root, e.g. `j1-new-customer` or `j1-new-customer/r2`. */\n dir: string\n videos: { file: string; seconds: number | null }[]\n turns: Pick<TurnRecord, 'label' | 'outcome' | 'firstTextS' | 'completeS' | 'replyChars' | 'error' | 'sentAt'>[]\n}\n\nexport interface IndexInput {\n title: string\n critic?: CriticResult\n journeys: JourneyFiles[]\n}\n\nconst seconds = (s: number | null) => (s === null ? '?' : `${Math.round(s).toLocaleString('en-US')} s`)\nconst cell = (text: string | number | null | undefined) => String(text ?? '').replace(/\\|/g, '\\\\|').replace(/\\s*\\n\\s*/g, ' ')\nconst firstLine = (text: string) => text.split('\\n')[0]!.trim()\n\nfunction videoLabel(file: string): { base: string; kind: string } {\n const name = file.split('/').pop() ?? file\n const m = /^(.*)-(highlights|full|x2)\\.mp4$/.exec(name)\n return m ? { base: m[1]!, kind: m[2]! } : { base: name.replace(/\\.mp4$/, ''), kind: 'other' }\n}\n\n/** Every recorded turn's outcome, counted. The denominator is every turn in the folder's timings.json files. */\nexport function tallyTurns(journeys: readonly JourneyFiles[]): { total: number; byOutcome: Record<string, number> } {\n const byOutcome: Record<string, number> = {}\n let total = 0\n for (const j of journeys) {\n for (const t of j.turns) {\n total += 1\n byOutcome[t.outcome] = (byOutcome[t.outcome] ?? 0) + 1\n }\n }\n return { total, byOutcome }\n}\n\nexport function renderIndex(input: IndexInput): string {\n const out: string[] = [`# ${input.title}`, '']\n const { critic } = input\n const tally = tallyTurns(input.journeys)\n if (critic?.headline) out.push(`**Result.** ${critic.headline}`, '')\n if (tally.total) {\n const parts = Object.entries(tally.byOutcome).sort((a, b) => b[1] - a[1]).map(([k, n]) => `${n} ${k}`)\n out.push(`**Turns, as scored by the recorder:** ${parts.join(', ')}, of ${tally.total} recorded turns (source: each journey's timings.json).`, '')\n }\n\n const all = input.journeys.flatMap((j) => j.videos.map((v) => ({ ...v, dir: j.dir, path: j.dir ? `${j.dir}/${v.file}` : v.file })))\n const highlights = all.filter((v) => videoLabel(v.file).kind === 'highlights')\n const scoreVideos = (critic?.scorecard ?? []).map((s) => s.video ?? '').filter(Boolean)\n const rankOf = (path: string) => {\n const i = scoreVideos.findIndex((v) => v.endsWith(path))\n return i < 0 ? Number.MAX_SAFE_INTEGER : i\n }\n highlights.sort((a, b) => rankOf(a.path) - rankOf(b.path) || a.path.localeCompare(b.path))\n if (highlights.length) {\n out.push('## Start here: highlights, at most 3 minutes each', '')\n highlights.forEach((v, i) => {\n const card = critic?.scorecard?.find((s) => s.video?.endsWith(v.path))\n out.push(`${i + 1}. \\`${v.path}\\` (${seconds(v.seconds)})${card ? `. ${card.journey}: ${firstLine(card.topIssue)}` : ''}`)\n })\n out.push('')\n }\n\n if (critic?.scorecard?.length) {\n out.push('## Scorecard', '', '| Journey | Verdict | Key timing | Output | Top issue |', '|---|---|---|---|---|')\n for (const s of critic.scorecard) out.push(`| ${cell(s.journey)} | ${cell(s.verifiedVerdict)} | ${cell(s.keyTiming)} | ${cell(s.qualityGrade)} | ${cell(s.topIssue)} |`)\n out.push('')\n }\n\n const fixes = [...(critic?.verifiedFailures ?? [])].sort((a, b) => a.rank - b.rank)\n if (fixes.length) {\n out.push('## Ranked fixes (verified failures, customer impact first)', '')\n for (const f of fixes) {\n out.push(`${f.rank}. **${firstLine(f.what)}** (${f.severity}${f.journeys?.length ? `; ${f.journeys.join(', ')}` : ''})`)\n // Later lines keep their breaks, so a list inside `what` nests under its rank.\n for (const line of f.what.split('\\n').slice(1)) if (line.trim()) out.push(` ${line.trim()}`)\n out.push(` - Evidence: ${cell(f.evidence)}`)\n if (f.likelyCause) out.push(` - Likely cause: ${cell(f.likelyCause)}`)\n out.push(` - Fix: ${cell(f.fix)}`, ` - Number to beat: ${cell(f.numberToBeat)}`, ` - Proving test: ${cell(f.test)}`)\n }\n out.push('')\n }\n\n const turns = input.journeys.flatMap((j) => j.turns.map((t) => ({ ...t, dir: j.dir })))\n if (turns.length) {\n out.push('## Every recorded turn', '', '| Journey | Context | Sent | Outcome | First text | End | Reply chars | What went wrong |', '|---|---|---|---|---|---|---|---|')\n for (const t of turns) {\n out.push(`| ${cell(t.dir || '.')} | ${cell(t.label)} | ${cell(t.sentAt.slice(11, 19))}Z | ${cell(t.outcome)} | ${seconds(t.firstTextS)} | ${seconds(t.completeS)} | ${t.replyChars.toLocaleString('en-US')} | ${cell(t.error ?? '')} |`)\n }\n out.push('')\n }\n\n if (all.length) {\n out.push('## Every video', '')\n const dirs = [...new Set(all.map((v) => v.dir))]\n for (const dir of dirs) {\n out.push(`### \\`${dir || '.'}\\``, '')\n const byBase = new Map<string, typeof all>()\n for (const v of all.filter((x) => x.dir === dir)) {\n const { base } = videoLabel(v.file)\n byBase.set(base, [...(byBase.get(base) ?? []), v])\n }\n for (const [base, vids] of byBase) {\n const order = ['highlights', 'full', 'x2', 'other']\n vids.sort((a, b) => order.indexOf(videoLabel(a.file).kind) - order.indexOf(videoLabel(b.file).kind))\n out.push(`- ${base}: ${vids.map((v) => `\\`${v.file}\\` (${seconds(v.seconds)})`).join(', ')}`)\n }\n out.push('')\n }\n }\n\n const unproven = [...(critic?.refutedOrUnproven ?? []), ...(critic?.coverageGaps ?? [])]\n if (unproven.length) {\n out.push('## Refuted, unproven and not covered', '')\n for (const u of unproven) out.push(`- ${cell(u)}`)\n out.push('')\n }\n return out.join('\\n')\n}\n\n/**\n * Every journey folder under `root`: one that holds a `timings.json` or a\n * `video/` folder, at any depth. `probe` returns a video's duration in seconds.\n */\nexport function collectJourneyFiles(root: string, probe: (file: string) => number | null): JourneyFiles[] {\n const found: JourneyFiles[] = []\n const visit = (dir: string, depth: number) => {\n const timings = join(dir, 'timings.json')\n const videoDir = join(dir, 'video')\n const hasVideo = existsSync(videoDir) && statSync(videoDir).isDirectory()\n if (existsSync(timings) || hasVideo) {\n const videos = hasVideo\n ? readdirSync(videoDir).filter((f) => f.endsWith('.mp4')).sort().map((f) => ({ file: `video/${f}`, seconds: probe(join(videoDir, f)) }))\n : []\n let turns: JourneyFiles['turns'] = []\n if (existsSync(timings)) {\n try {\n turns = ((JSON.parse(readFileSync(timings, 'utf8')) as { turns?: JourneyFiles['turns'] }).turns ?? [])\n } catch {\n turns = []\n }\n }\n found.push({ dir: relative(root, dir), videos, turns })\n }\n if (depth >= 4) return\n for (const name of readdirSync(dir).sort()) {\n const path = join(dir, name)\n if (name === 'video' || name === 'turns' || name.startsWith('.')) continue\n if (statSync(path).isDirectory()) visit(path, depth + 1)\n }\n }\n visit(root, 0)\n return found\n}\n","/**\n * The readiness scoreboard writer: one run's journey summary as the writes\n * that put it on the shared board, so every app's rows land in one schema.\n *\n * The board is an artifact page whose shared store holds three collections:\n * `flows` (one row per flow), `prs` and `meta` (one document per app; Hardware's\n * is `board`, written before the board was shared). A row carries `app` and\n * `flowId`; a row without `app` belongs to Hardware. Hardware's rows predate the\n * shared board and live at their bare flow id and `meta/board`; its runner\n * passes `legacyIds` so those rows are updated in place, never duplicated.\n *\n * A document that already exists is merged (`update`) and pinned to the\n * version the caller read from the store (`versions`), so the text a person\n * wrote for a flow (what the customer does, its pass bar) survives every run,\n * and a field the run no longer has (an old blocker on a flow that now passes)\n * is deleted. A document with no known version is created with `set`; the\n * store refuses a `set` without a version on a document that already exists\n * (version_mismatch, nothing written; checked against the board's store), so a row a person wrote is never replaced.\n *\n * Pure: the same summary and options give the same writes, in the same order.\n */\n\nexport const SCOREBOARD_STATUSES = ['pass', 'fail', 'stall', 'blocked-host', 'blocked', 'skipped', 'unrecorded'] as const\nexport type ScoreboardStatus = (typeof SCOREBOARD_STATUSES)[number]\n\n/** Rows a store wrote before the board was shared, with no `app` field, belong to this app. */\nexport const LEGACY_SCOREBOARD_APP = 'hardware'\n\n/** One journey in a run's `summary.json`. */\nexport interface JourneySummaryEntry {\n /** Flow id, e.g. `c2` or `C2`; written upper-case. */\n id: string\n status: string\n /** Why it was blocked, skipped, stalled or failed. */\n reason?: string\n firstTextS?: number\n completeS?: number\n /** Links a reviewer can open. Only http(s) URLs are written; host paths are dropped. */\n videoUrl?: string\n traceUrl?: string\n evidenceUrl?: string\n}\n\n/** A run's summary, as an app's journey runner writes it. */\nexport interface JourneySummary {\n origin?: string\n /** Commit the run served. */\n sha?: string\n model?: string\n lane?: string\n /** ISO time of the run; required, so two runs are told apart. */\n updatedAt?: string\n journeys: JourneySummaryEntry[]\n}\n\nexport interface ScoreboardOptions {\n /** Short app name, e.g. `casework`. */\n app: string\n /** Current version of each document that exists, by `collection/docId`. */\n versions?: Readonly<Record<string, number>>\n /**\n * Write at the ids the board used before it was shared: the bare flow id and\n * `meta/board`. Only Hardware's runner sets this; every other app's rows are\n * `<app>-<flowId>` and `meta/<app>`.\n */\n legacyIds?: boolean\n}\n\n/** One entry of an artifact store batch, in the shape the batch write takes. */\nexport interface ScoreboardWrite {\n op: 'update' | 'set'\n collection: 'flows' | 'meta'\n doc_id: string\n data: Record<string, unknown>\n if_version?: number\n}\n\nexport interface ScoreboardResult {\n writes: ScoreboardWrite[]\n /** Entries the writer could not take as given, each with what it did instead. */\n warnings: string[]\n}\n\nconst DELETE = { __delete__: true } as const\nconst APP_NAME = /^[a-z][a-z0-9-]{0,40}$/\n\nconst isStatus = (value: string): value is ScoreboardStatus => (SCOREBOARD_STATUSES as readonly string[]).includes(value)\nconst url = (value: unknown): string | undefined => (typeof value === 'string' && /^https?:\\/\\//.test(value) ? value : undefined)\nconst seconds = (value: unknown): number | undefined => (typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined)\n\n/** The document id a flow row lives at. */\nexport function scoreboardDocId(app: string, flowId: string, legacyIds = false): string {\n return legacyIds ? flowId : `${app}-${flowId}`\n}\n\n/** The `meta` document an app's run facts live at. */\nexport function scoreboardMetaId(app: string, legacyIds = false): string {\n return legacyIds ? 'board' : app\n}\n\n/** Keys in a fixed order, so the same input always serializes the same way. */\nfunction sorted(data: Record<string, unknown>): Record<string, unknown> {\n return Object.fromEntries(Object.keys(data).sort().map((key) => [key, data[key]]))\n}\n\n/**\n * A document with a known version is merged, pinned to that version. One with\n * none is created with `set`, which takes no delete markers; if it does exist\n * after all, the store refuses the unpinned write and names it, so nothing a\n * person wrote there is overwritten.\n */\nfunction pinned(write: Omit<ScoreboardWrite, 'if_version'>, versions: ScoreboardOptions['versions']): ScoreboardWrite {\n const version = versions?.[`${write.collection}/${write.doc_id}`]\n if (version !== undefined) return { ...write, op: 'update', if_version: version }\n const data = Object.fromEntries(Object.entries(write.data).filter(([, value]) => value !== DELETE))\n return { ...write, op: 'set', data }\n}\n\nexport function scoreboardRows(summary: JourneySummary, options: ScoreboardOptions): ScoreboardResult {\n const app = options.app\n if (!APP_NAME.test(app)) throw new Error(`scoreboard: app must be a short lowercase name such as \"casework\", got \"${app}\"`)\n if (!summary || !Array.isArray(summary.journeys)) throw new Error('scoreboard: the summary has no journeys array')\n if (!summary.updatedAt || Number.isNaN(Date.parse(summary.updatedAt))) throw new Error('scoreboard: the summary needs updatedAt, an ISO time')\n\n const warnings: string[] = []\n const flows = new Map<string, ScoreboardWrite>()\n for (const entry of summary.journeys) {\n const flowId = String(entry.id ?? '').trim().toUpperCase()\n if (!flowId) { warnings.push('a journey without an id was skipped'); continue }\n let status: ScoreboardStatus\n if (isStatus(entry.status)) status = entry.status\n else { status = 'unrecorded'; warnings.push(`${flowId}: status \"${entry.status}\" is not one of ${SCOREBOARD_STATUSES.join(', ')}; written as unrecorded`) }\n if (flows.has(flowId)) warnings.push(`${flowId}: listed twice; the last entry wins`)\n for (const key of ['videoUrl', 'traceUrl', 'evidenceUrl'] as const) {\n if (entry[key] !== undefined && !url(entry[key])) warnings.push(`${flowId}: ${key} is not an http(s) link and was dropped`)\n }\n const reason = typeof entry.reason === 'string' && entry.reason.trim() ? entry.reason.trim() : undefined\n const data: Record<string, unknown> = {\n app,\n flowId,\n status,\n // A pass carries no blocker; any other status names why, or clears a stale one.\n blocker: status !== 'pass' && reason ? reason : DELETE,\n firstTextS: seconds(entry.firstTextS) ?? DELETE,\n completeS: seconds(entry.completeS) ?? DELETE,\n videoUrl: url(entry.videoUrl) ?? DELETE,\n traceUrl: url(entry.traceUrl) ?? DELETE,\n evidenceUrl: url(entry.evidenceUrl) ?? DELETE,\n sha: summary.sha ?? DELETE,\n recordedAt: summary.updatedAt,\n }\n flows.set(flowId, { op: 'update', collection: 'flows', doc_id: scoreboardDocId(app, flowId, options.legacyIds), data: sorted(data) })\n }\n\n const writes = [...flows.values()]\n .sort((a, b) => a.doc_id.localeCompare(b.doc_id, undefined, { numeric: true }))\n .map((write) => pinned(write, options.versions))\n const meta: Record<string, unknown> = {\n origin: summary.origin ?? DELETE,\n sha: summary.sha ?? DELETE,\n model: summary.model ?? DELETE,\n lane: summary.lane ?? DELETE,\n updatedAt: summary.updatedAt,\n }\n writes.push(pinned({ op: 'update', collection: 'meta', doc_id: scoreboardMetaId(app, options.legacyIds), data: sorted(meta) }, options.versions))\n return { writes, warnings }\n}\n"],"mappings":";;;;;AAmDO,IAAM,uBAA0C;AAAA,EACrD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA;AAAA;AAAA,EAIA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAGO,IAAM,uBAA0C;AAAA,EACrD;AAAA,EACA;AAAA,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xB,MAAM,QAAQ,QAAQ;AAAA,IACtB,WAAW,QAAQ;AAAA,EACrB;AACA,SAAO,KAAK,OAAO,EAAE,IAAI,UAAU,YAAY,QAAQ,QAAQ,iBAAiB,KAAK,QAAQ,SAAS,GAAG,MAAM,OAAO,IAAI,EAAE,GAAG,QAAQ,QAAQ,CAAC;AAChJ,SAAO,EAAE,QAAQ,SAAS;AAC5B;","names":["url","openSync","closeSync","join","openSync","closeSync","join","existsSync","readdirSync","readFileSync","statSync","join","resolve","url","existsSync","mkdirSync","readFileSync","join","existsSync","readdirSync","readFileSync","statSync","join","seconds"]}
@@ -180,4 +180,4 @@ export {
180
180
  runWithModelFailover,
181
181
  buildModelChain
182
182
  };
183
- //# sourceMappingURL=chunk-ZLX4BA27.js.map
183
+ //# sourceMappingURL=chunk-QUT3T2IN.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/model-resolution/failover.ts"],"sourcesContent":["/**\n * Model failover — the answer to \"one upstream hit a quota wall and the customer\n * got a Bad Gateway even though the router had abundant healthy capacity\".\n *\n * This is deliberately NOT a health probe. Probing before every turn buys a\n * round-trip of latency on the happy path and still races the outage (a model\n * healthy at probe time can 502 a second later). Failover is REACTIVE: run the\n * preferred model, and on an upstream-outage signal move to the next model in\n * the chain. Zero added latency when the preferred model works.\n *\n * Two facts drive the design, both measured against a live box during the\n * 2026-07-25 Anthropic/DeepSeek outage:\n *\n * 1. An outage is NOT always a thrown error. The sandbox resolves with a\n * payload — `{ success: false, errorCode: 'provider_inference_unavailable' }`\n * — so a classifier that only inspects `catch` misses the customer-visible\n * case entirely. `isUpstreamUnavailable` inspects resolved values too.\n * 2. Catalog membership is NOT liveness. The router's `/v1/models` still listed\n * every dead model during the outage, so `validateChatModelId` admitted\n * `claude-sonnet-4-6` while every call to it returned 502. Nothing upstream\n * of the actual call can be trusted to tell you a model is serving.\n *\n * Substrate-free: the caller injects `run`, so this composes with a sandbox\n * turn, a router chat completion, or a test fake without importing any of them.\n */\n\nimport {\n checkModelPolicy,\n type ModelPolicy,\n} from '../policy-filters/index'\n\n/**\n * Error codes that mean \"this model's upstream is unavailable — a different\n * model may still work\". Deliberately excludes codes that would fail identically\n * on every model (bad request, auth, content filter): retrying those down a\n * chain burns latency and money to reach the same failure.\n */\nexport const UPSTREAM_UNAVAILABLE_CODES: readonly string[] = [\n 'provider_inference_unavailable',\n 'provider_quota_exhausted',\n 'upstream_unavailable',\n 'insufficient_quota',\n 'model_not_available',\n 'server_error',\n 'bad_gateway',\n 'service_unavailable',\n]\n\n/** HTTP statuses that indicate an upstream capacity/availability problem. */\nexport const UPSTREAM_UNAVAILABLE_STATUSES: readonly number[] = [429, 500, 502, 503, 504]\n\n/**\n * Statuses that mean the REQUEST is wrong, so every model in the chain would\n * fail on it identically. Listed explicitly rather than as \"any 4xx\" because\n * 404 is NOT one of them: a model the endpoint cannot find is model-scoped, and\n * the next model in the chain may well be there. 429 is absent for the same\n * reason in reverse — it is a capacity signal and lives in the list above.\n */\nconst REQUEST_ERROR_STATUSES: readonly number[] = [400, 401, 403, 405, 413, 422]\n\n/**\n * Message fragments emitted by real upstreams during this class of outage.\n * Matched case-insensitively as a last resort, after code and status.\n */\nconst UPSTREAM_UNAVAILABLE_MESSAGES: readonly string[] = [\n 'bad gateway',\n 'service unavailable',\n 'inference temporarily unavailable',\n 'provider inference is unavailable',\n 'insufficient balance',\n 'usage limits',\n 'quota exceeded',\n 'rate limit',\n 'overloaded',\n 'temporarily unavailable',\n // Model-SCOPED unavailability. A different model in the chain can still\n // serve, so this belongs here and not with the client errors. Measured on a\n // real box 2026-07-27: the sandbox now reports an unservable model as a\n // terminal `error` whose data is `{\"message\":\"Session error:\n // {\\\"error\\\":{\\\"name\\\":\\\"UnknownError\\\",\\\"data\\\":{\\\"message\\\":\\\"Model not\n // found: openai-compat/zai/glm-4.7.\\\"}}}\"}` — no `code`, no numeric status,\n // and none of the fragments above. The shipped live product-path proof went\n // red on exactly this: `usedFallback:false`, `failed:true`, an error row to\n // the customer where a fallback was available and would have answered.\n 'model not found',\n 'is not currently available',\n]\n\n/**\n * Textual forms an HTTP status arrives in when NO numeric field carries it.\n *\n * The case that forced this is the opaque Cloudflare 502. Captured verbatim\n * from `router.tangle.tools` (cf-ray\n * `a21d793899f6cef3-DEN`): `HTTP/2 502`, `content-type: text/plain;\n * charset=UTF-8`, a 16-byte body reading `error code: 502\\n`, `server:\n * cloudflare`, and **zero `x-tangle-*` headers** where a healthy 200 from the\n * same endpoint carries nine of them.\n *\n * That capture was originally read as \"zero headers means the origin never\n * executed\". It does not, and the correction matters more than the original\n * guess did. Matching client-observed cf-rays against the origin's own access\n * log (tangle-router #307) showed all 62 of those responses WERE produced by\n * the router — `content-type: application/json`, an `X-Generation-Id`, and a\n * routing trace showing the upstream had returned 200 — and Cloudflare\n * replaced the body and every response header with its own error page, because\n * an origin 502 reads to the edge as the origin having failed.\n *\n * The classifier's BEHAVIOR here was right for the wrong reason, and stays\n * exactly as it is. What changes is why: the rescue is needed not because the\n * origin is unreachable, but because a response the origin carefully\n * structured arrives at the client as sixteen unlabelled bytes. The router now\n * emits 503 instead of 502 on those paths so the body survives, but this\n * pattern must remain — it is the client's only handle on any origin 5xx the\n * edge decides to rewrite, including from a router that has not deployed the\n * fix yet.\n *\n * Every pattern below matches a string a real producer emits:\n * - `error code: 502` — Cloudflare's edge body (the capture above).\n * - `(HTTP 502)` — `src/runtime/openai-stream.ts` wrapping a non-ok response.\n * - `returned 502` — `src/runtime/model-catalog.ts`.\n * - `failed with status 502` — `src/turn-stream/adapters.ts`.\n * - `502 Bad Gateway` — an HTTP/1.1 status line. HTTP/2 carries no reason\n * phrase at all, which is precisely why matching the phrase alone (the\n * `'bad gateway'` fragment below) read the capture as a non-outage.\n */\nconst HTTP_STATUS_HINT_PATTERNS: readonly RegExp[] = [\n /\\berror\\s+code:?\\s*([1-5]\\d{2})\\b/i,\n /\\bhttp(?:\\/[\\d.]+)?[\\s:]\\s*([1-5]\\d{2})\\b/i,\n /\\bstatus(?:\\s*code)?[\\s:=]\\s*([1-5]\\d{2})\\b/i,\n /\\b(?:returned|responded(?:\\s+with)?)\\s+([1-5]\\d{2})\\b/i,\n /\\b([1-5]\\d{2})\\s+(?:bad\\s+gateway|service\\s+unavailable|gateway\\s+time-?out|internal\\s+server\\s+error|too\\s+many\\s+requests)\\b/i,\n]\n\n/**\n * The HTTP status a message states in prose, or `undefined` when it states\n * none. Deliberately NOT \"any three digits in the string\" — an unanchored digit\n * scan would read a token count or a duration as a status.\n */\nexport function readHttpStatusHint(text: string): number | undefined {\n for (const pattern of HTTP_STATUS_HINT_PATTERNS) {\n const match = pattern.exec(text)\n if (match?.[1]) return Number(match[1])\n }\n return undefined\n}\n\nfunction readString(source: Record<string, unknown>, key: string): string | undefined {\n const value = source[key]\n return typeof value === 'string' && value.trim().length > 0 ? value : undefined\n}\n\n/** Read a recognized upstream code, including the terminal message-only shape. */\nexport function readUpstreamUnavailableCode(signal: unknown): string | undefined {\n if (signal === null || typeof signal !== 'object') return undefined\n const record = signal as Record<string, unknown>\n const nested = record.error\n const nestedRecord = nested !== null && typeof nested === 'object' ? (nested as Record<string, unknown>) : undefined\n const code =\n readString(record, 'errorCode') ??\n readString(record, 'code') ??\n (nestedRecord ? (readString(nestedRecord, 'code') ?? readString(nestedRecord, 'type')) : undefined)\n if (code && UPSTREAM_UNAVAILABLE_CODES.includes(code)) return code\n\n const message =\n readString(record, 'message') ??\n readString(record, 'error') ??\n (nestedRecord ? readString(nestedRecord, 'message') : undefined)\n return message && /\\(\\s*provider_quota_exhausted\\s*\\)/i.test(message)\n ? 'provider_quota_exhausted'\n : undefined\n}\n\n/**\n * True when `signal` — a thrown error OR a resolved result payload — indicates\n * the model's upstream is unavailable and another model is worth trying.\n *\n * Checked in order of decreasing confidence: explicit code, HTTP status, then\n * message text. A resolved payload only counts as a failure when it carries an\n * explicit failure marker (`success: false`, or an `error`/`errorCode` field) —\n * a successful result is never misread as an outage.\n */\nexport function isUpstreamUnavailable(signal: unknown): boolean {\n if (signal === null || typeof signal !== 'object') return false\n const record = signal as Record<string, unknown>\n\n // A resolved payload that explicitly reports success is never an outage.\n if (record.success === true) return false\n\n const nested = record.error\n const nestedRecord = nested !== null && typeof nested === 'object' ? (nested as Record<string, unknown>) : undefined\n if (readUpstreamUnavailableCode(record)) return true\n\n for (const key of ['status', 'statusCode', 'httpStatus']) {\n const value = record[key]\n if (typeof value === 'number' && UPSTREAM_UNAVAILABLE_STATUSES.includes(value)) return true\n }\n\n const message =\n readString(record, 'message') ??\n readString(record, 'error') ??\n (nestedRecord ? readString(nestedRecord, 'message') : undefined)\n if (!message) return false\n\n // A status carried as PROSE, checked before the fragment list because it is\n // the stronger signal and it cuts BOTH ways. An edge 502 names no exception\n // type and sets no numeric field, so without this the shipped classifier read\n // `error code: 502` as a non-outage and handed the customer a Bad Gateway\n // instead of trying the next model — the exact failure the router cannot\n // rescue from inside its own origin.\n const hinted = readHttpStatusHint(message)\n if (hinted !== undefined) {\n if (UPSTREAM_UNAVAILABLE_STATUSES.includes(hinted)) return true\n // An explicit REQUEST-error status is decisive the OTHER way. A 400\n // carrying a validation message must surface rather than walk the chain,\n // even when its body happens to contain a word from the fragment list —\n // the router's own `Function tools with reasoning_effort are not supported`\n // 400 is a request-shaping bug that fails identically on every model.\n if (REQUEST_ERROR_STATUSES.includes(hinted)) return false\n }\n\n const lowered = message.toLowerCase()\n return UPSTREAM_UNAVAILABLE_MESSAGES.some((fragment) => lowered.includes(fragment))\n}\n\n/** One model tried, and how it went. */\nexport interface ModelFailoverAttempt {\n model: string\n ok: boolean\n /** Why this model was abandoned. Absent when `ok`. */\n reason?: string\n /** Recognized upstream code carried by this failed attempt. */\n errorCode?: string\n}\n\n/** The outcome of a failover run: the value plus the full attempt trail. */\nexport interface ModelFailoverResult<T> {\n value: T\n /** The model that actually produced `value`. */\n model: string\n attempts: ModelFailoverAttempt[]\n /** True when the preferred (first) model did not serve the request. */\n usedFallback: boolean\n}\n\n/** Every model in the chain failed; carries the trail for logging. */\nexport class ModelFailoverExhaustedError extends Error {\n readonly attempts: ModelFailoverAttempt[]\n /** Last recognized upstream code across the exhausted chain, when present. */\n readonly upstreamCode?: string\n constructor(attempts: ModelFailoverAttempt[]) {\n const trail = attempts.map((a) => `${a.model}: ${a.reason ?? 'failed'}`).join(' | ')\n super(`All ${attempts.length} model(s) failed. ${trail}`)\n this.name = 'ModelFailoverExhaustedError'\n this.attempts = attempts\n this.upstreamCode = [...attempts].reverse().find((attempt) => attempt.errorCode)?.errorCode\n }\n}\n\n/** Inputs to {@link runWithModelFailover}. */\nexport interface RunWithModelFailoverInput<T> {\n /** Preferred model first, then fallbacks in descending preference. */\n models: readonly string[]\n /** Executes one turn with the given model. */\n run: (model: string) => Promise<T>\n /**\n * Product admission policy applied to EVERY chain member before it runs.\n * Without this a compliant model 502ing mid-turn would silently re-run the\n * turn's data through a non-compliant fallback: availability is not\n * eligibility. A member the policy refuses is SKIPPED (recorded in the\n * attempt trail with the refusal as its reason) and the walk continues; when\n * no member is admitted the run ends in {@link ModelFailoverExhaustedError}\n * like any other exhausted chain. Fail-closed — a member carrying no policy\n * metadata is refused.\n */\n policy?: ModelPolicy\n /**\n * Classifies a resolved result as an upstream outage. Defaults to\n * {@link isUpstreamUnavailable}, which understands the sandbox's\n * `{ success: false, errorCode }` payload.\n */\n isUnavailableResult?: (result: T) => boolean\n /** Classifies a thrown error. Defaults to {@link isUpstreamUnavailable}. */\n isUnavailableError?: (error: unknown) => boolean\n /** Observability hook fired each time a model is abandoned — including a\n * policy refusal, whose `reason` is the policy's own refusal text. */\n onFallback?: (attempt: ModelFailoverAttempt, nextModel: string) => void\n}\n\nfunction describe(signal: unknown): string {\n if (signal instanceof Error) return signal.message\n if (signal !== null && typeof signal === 'object') {\n const record = signal as Record<string, unknown>\n const message = readString(record, 'error') ?? readString(record, 'message') ?? readString(record, 'errorCode')\n if (message) return message\n }\n return String(signal)\n}\n\n/**\n * Run `run` against the first model in `models` that does not report an upstream\n * outage, falling through the chain in order.\n *\n * A non-outage failure (bad request, auth, content filter) is re-thrown\n * immediately rather than retried down the chain — those fail identically on\n * every model, so walking the chain would only multiply latency and spend.\n *\n * @throws ModelFailoverExhaustedError when every model reports an outage or is\n * refused by the configured admission policy.\n */\nexport async function runWithModelFailover<T>(\n input: RunWithModelFailoverInput<T>,\n): Promise<ModelFailoverResult<T>> {\n const models = input.models.map((m) => m.trim()).filter((m) => m.length > 0)\n if (models.length === 0) throw new Error('runWithModelFailover requires at least one model')\n\n const isUnavailableResult = input.isUnavailableResult ?? ((r: T) => isUpstreamUnavailable(r))\n const isUnavailableError = input.isUnavailableError ?? isUpstreamUnavailable\n const attempts: ModelFailoverAttempt[] = []\n\n for (let index = 0; index < models.length; index += 1) {\n const model = models[index]!\n\n // Policy BEFORE run: a chain member the deployment does not admit never\n // sees the turn's data. The refusal is one failed attempt — the walk\n // continues to the next member, and an all-refused chain exhausts exactly\n // like an all-dead one.\n if (input.policy) {\n const decision = await checkModelPolicy(model, input.policy.catalog, input.policy.filter, input.policy.context)\n if (!decision.allowed) {\n const attempt: ModelFailoverAttempt = { model, ok: false, reason: decision.reason }\n attempts.push(attempt)\n const next = models[index + 1]\n if (next) input.onFallback?.(attempt, next)\n continue\n }\n }\n\n let result: T\n try {\n result = await input.run(model)\n } catch (error) {\n if (!isUnavailableError(error)) throw error\n const errorCode = readUpstreamUnavailableCode(error)\n const attempt: ModelFailoverAttempt = {\n model,\n ok: false,\n reason: describe(error),\n ...(errorCode ? { errorCode } : {}),\n }\n attempts.push(attempt)\n const next = models[index + 1]\n if (next) input.onFallback?.(attempt, next)\n continue\n }\n\n if (isUnavailableResult(result)) {\n const errorCode = readUpstreamUnavailableCode(result)\n const attempt: ModelFailoverAttempt = {\n model,\n ok: false,\n reason: describe(result),\n ...(errorCode ? { errorCode } : {}),\n }\n attempts.push(attempt)\n const next = models[index + 1]\n if (next) input.onFallback?.(attempt, next)\n continue\n }\n\n attempts.push({ model, ok: true })\n return { value: result, model, attempts, usedFallback: index > 0 }\n }\n\n throw new ModelFailoverExhaustedError(attempts)\n}\n\n/**\n * Build a failover chain: the preferred model first, then `fallbacks`, with\n * duplicates removed so a model is never retried twice in one turn.\n */\nexport function buildModelChain(preferred: string, fallbacks: readonly string[]): string[] {\n const chain: string[] = []\n for (const model of [preferred, ...fallbacks]) {\n const cleaned = typeof model === 'string' ? model.trim() : ''\n if (cleaned.length > 0 && !chain.includes(cleaned)) chain.push(cleaned)\n }\n return chain\n}\n"],"mappings":";;;;;AAqCO,IAAM,6BAAgD;AAAA,EAC3D;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAGO,IAAM,gCAAmD,CAAC,KAAK,KAAK,KAAK,KAAK,GAAG;AASxF,IAAM,yBAA4C,CAAC,KAAK,KAAK,KAAK,KAAK,KAAK,GAAG;AAM/E,IAAM,gCAAmD;AAAA,EACvD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA;AAAA,EACA;AACF;AAuCA,IAAM,4BAA+C;AAAA,EACnD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAOO,SAAS,mBAAmB,MAAkC;AACnE,aAAW,WAAW,2BAA2B;AAC/C,UAAM,QAAQ,QAAQ,KAAK,IAAI;AAC/B,QAAI,QAAQ,CAAC,EAAG,QAAO,OAAO,MAAM,CAAC,CAAC;AAAA,EACxC;AACA,SAAO;AACT;AAEA,SAAS,WAAW,QAAiC,KAAiC;AACpF,QAAM,QAAQ,OAAO,GAAG;AACxB,SAAO,OAAO,UAAU,YAAY,MAAM,KAAK,EAAE,SAAS,IAAI,QAAQ;AACxE;AAGO,SAAS,4BAA4B,QAAqC;AAC/E,MAAI,WAAW,QAAQ,OAAO,WAAW,SAA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;AAC7C,UAAM,UAAU,OAAO,UAAU,WAAW,MAAM,KAAK,IAAI;AAC3D,QAAI,QAAQ,SAAS,KAAK,CAAC,MAAM,SAAS,OAAO,EAAG,OAAM,KAAK,OAAO;AAAA,EACxE;AACA,SAAO;AACT;","names":[]}
@@ -577,4 +577,4 @@ export {
577
577
  SandboxTransientDeadlineError,
578
578
  retrySandboxTransient
579
579
  };
580
- //# sourceMappingURL=chunk-PK65B6HP.js.map
580
+ //# sourceMappingURL=chunk-UJYEBQMS.js.map