@tangle-network/agent-app 0.60.115 → 0.60.117

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 (91) hide show
  1. package/dist/VaultPane-OWOPGPXP.js +7 -0
  2. package/dist/assistant/index.js +11 -11
  3. package/dist/chat-react/index.js +4 -4
  4. package/dist/chat-routes/index.js +13 -6
  5. package/dist/chat-routes/index.js.map +1 -1
  6. package/dist/chat-routes/wire.d.ts +3 -1
  7. package/dist/chat-store/index.js +2 -2
  8. package/dist/{chunk-Y4WLCFDZ.js → chunk-2FLSODOX.js} +6 -6
  9. package/dist/{chunk-6XE77PTT.js → chunk-2NHJNINW.js} +1 -1
  10. package/dist/chunk-2NHJNINW.js.map +1 -0
  11. package/dist/{chunk-56GPDCOJ.js → chunk-7DXRHQZO.js} +7 -7
  12. package/dist/chunk-BTEVD7HG.js +198 -0
  13. package/dist/chunk-BTEVD7HG.js.map +1 -0
  14. package/dist/{chunk-RQSYR4AV.js → chunk-CLB4IQEG.js} +5 -5
  15. package/dist/{chunk-F2FH354I.js → chunk-D52LB6UQ.js} +2 -2
  16. package/dist/chunk-FVI2MHUL.js +1152 -0
  17. package/dist/chunk-FVI2MHUL.js.map +1 -0
  18. package/dist/{chunk-4G7HH6WQ.js → chunk-GU7OZFU7.js} +2 -2
  19. package/dist/{chunk-OGDEUCNW.js → chunk-JGLK5RDK.js} +176 -1
  20. package/dist/chunk-JGLK5RDK.js.map +1 -0
  21. package/dist/{chunk-FJQUMIM6.js → chunk-JZUSVGRJ.js} +3 -3
  22. package/dist/{chunk-AB63T2LM.js → chunk-KBJZMR4E.js} +8 -1
  23. package/dist/chunk-KBJZMR4E.js.map +1 -0
  24. package/dist/{chunk-JCSHTJT6.js → chunk-MGON3FE6.js} +22 -3
  25. package/dist/chunk-MGON3FE6.js.map +1 -0
  26. package/dist/{chunk-RQSNTJTW.js → chunk-MO7PDQRZ.js} +526 -187
  27. package/dist/chunk-MO7PDQRZ.js.map +1 -0
  28. package/dist/{chunk-MEUNTJL5.js → chunk-N3CYCSKK.js} +6 -1
  29. package/dist/chunk-N3CYCSKK.js.map +1 -0
  30. package/dist/journeys/cli.d.ts +2 -0
  31. package/dist/journeys/cli.js +165 -0
  32. package/dist/journeys/cli.js.map +1 -0
  33. package/dist/journeys/config.d.ts +96 -0
  34. package/dist/journeys/index.d.ts +18 -0
  35. package/dist/journeys/index.js +731 -0
  36. package/dist/journeys/index.js.map +1 -0
  37. package/dist/journeys/journey.d.ts +173 -0
  38. package/dist/journeys/page-reading.d.ts +42 -0
  39. package/dist/journeys/report.d.ts +51 -0
  40. package/dist/journeys/score.d.ts +115 -0
  41. package/dist/journeys/scrub.d.ts +21 -0
  42. package/dist/journeys/send.d.ts +46 -0
  43. package/dist/journeys/session.d.ts +27 -0
  44. package/dist/journeys/trace-zip.d.ts +28 -0
  45. package/dist/journeys/video.d.ts +53 -0
  46. package/dist/public-consultation/index.d.ts +2 -2
  47. package/dist/public-consultation/index.js +3 -3
  48. package/dist/runtime/index.js +1 -1
  49. package/dist/runtime/router-turn.d.ts +23 -2
  50. package/dist/runtime/router-turn.js +1 -1
  51. package/dist/sandbox/index.d.ts +2 -0
  52. package/dist/sandbox/index.js +13 -1
  53. package/dist/sandbox/sandbox-exec-tool.d.ts +68 -0
  54. package/dist/sandbox/sandbox-run-tool.d.ts +70 -0
  55. package/dist/studio-react/index.js +2 -2
  56. package/dist/teams/index.js +10 -6
  57. package/dist/teams/invitations-api.js +6 -3
  58. package/dist/teams/invitations-api.js.map +1 -1
  59. package/dist/teams/invitations.d.ts +4 -0
  60. package/dist/teams/members-api.js +2 -1
  61. package/dist/teams-react/components/InviteForm.d.ts +20 -0
  62. package/dist/teams-react/contracts.d.ts +2 -0
  63. package/dist/teams-react/index.js +196 -217
  64. package/dist/teams-react/index.js.map +1 -1
  65. package/dist/vault/VaultContentResults.d.ts +29 -0
  66. package/dist/vault/VaultHistoryPanel.d.ts +20 -0
  67. package/dist/vault/VaultPane.d.ts +3 -1
  68. package/dist/vault/contracts.d.ts +38 -0
  69. package/dist/vault/index.js +1 -1
  70. package/dist/vault/lazy.js +1 -1
  71. package/dist/web-react/index.js +25 -25
  72. package/dist/workspace-export/index.js +4 -193
  73. package/dist/workspace-export/index.js.map +1 -1
  74. package/dist/workspace-react/index.js +9 -7
  75. package/dist/workspace-react/index.js.map +1 -1
  76. package/dist/workspace-react/workspace-list.d.ts +7 -1
  77. package/package.json +8 -2
  78. package/dist/VaultPane-JUSNGOV7.js +0 -7
  79. package/dist/chunk-6XE77PTT.js.map +0 -1
  80. package/dist/chunk-AB63T2LM.js.map +0 -1
  81. package/dist/chunk-JCSHTJT6.js.map +0 -1
  82. package/dist/chunk-MEUNTJL5.js.map +0 -1
  83. package/dist/chunk-OGDEUCNW.js.map +0 -1
  84. package/dist/chunk-RQSNTJTW.js.map +0 -1
  85. /package/dist/{VaultPane-JUSNGOV7.js.map → VaultPane-OWOPGPXP.js.map} +0 -0
  86. /package/dist/{chunk-Y4WLCFDZ.js.map → chunk-2FLSODOX.js.map} +0 -0
  87. /package/dist/{chunk-56GPDCOJ.js.map → chunk-7DXRHQZO.js.map} +0 -0
  88. /package/dist/{chunk-RQSYR4AV.js.map → chunk-CLB4IQEG.js.map} +0 -0
  89. /package/dist/{chunk-F2FH354I.js.map → chunk-D52LB6UQ.js.map} +0 -0
  90. /package/dist/{chunk-4G7HH6WQ.js.map → chunk-GU7OZFU7.js.map} +0 -0
  91. /package/dist/{chunk-FJQUMIM6.js.map → chunk-JZUSVGRJ.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"],"sourcesContent":["/**\n * Whether a recorded chat turn worked, decided from what the person saw.\n *\n * On 2026-10-11 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 (measured on 2026-10-11), 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"],"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,EACA;AACF;AAEA,SAAS,UAAU,MAAsB;AACvC,SAAO,KAAK,QAAQ,QAAQ,GAAG,EAAE,KAAK;AACxC;AAGA,SAAS,aAAa,UAA8B,UAA2B,QAAkD;AAC/H,QAAM,SAAS,oBAAI,IAAoB;AACvC,QAAM,MAAM,CAAC,QAAgB,OAAO,IAAI,MAAM,OAAO,IAAI,GAAG,KAAK,KAAK,CAAC;AACvE,aAAW,OAAO,SAAS,OAAO;AAChC,UAAM,OAAO,UAAU,GAAG;AAC1B,QAAI,CAAC,QAAQ,OAAO,IAAI,IAAI,EAAG;AAC/B,QAAI,SAAS,QAAQ,KAAK,CAAC,MAAM,EAAE,KAAK,IAAI,CAAC,EAAG,KAAI,WAAW,IAAI,EAAE;AAAA,aAC5D,SAAS,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MAAK,KAAK,IAAI;AAC3B,UAAI,SAAS,WAAW,SAAS,WAAW,KAAK,WAAW,GAAG,EAAG;AAClE,UAAID,UAAS,IAAI,EAAE,YAAY,EAAG,OAAM,MAAM,QAAQ,CAAC;AAAA,IACzD;AAAA,EACF;AACA,QAAM,MAAM,CAAC;AACb,SAAO;AACT;","names":["openSync","closeSync","join","openSync","closeSync","join","existsSync","readdirSync","readFileSync","statSync","join","resolve","existsSync","mkdirSync","readFileSync","join","existsSync","readdirSync","readFileSync","statSync","join"]}
@@ -3,7 +3,7 @@ import {
3
3
  } from "./chunk-ZVEEWGDK.js";
4
4
  import {
5
5
  mentionKindForPath
6
- } from "./chunk-6XE77PTT.js";
6
+ } from "./chunk-2NHJNINW.js";
7
7
  import {
8
8
  persistedPartToInteraction
9
9
  } from "./chunk-6VQCFJWP.js";
@@ -135,4 +135,4 @@ export {
135
135
  buildAttachmentPromptBlock,
136
136
  historyContentWithAttachments
137
137
  };
138
- //# sourceMappingURL=chunk-4G7HH6WQ.js.map
138
+ //# sourceMappingURL=chunk-GU7OZFU7.js.map
@@ -412,6 +412,175 @@ function createSandboxPrewarmer(shell, options) {
412
412
  };
413
413
  }
414
414
 
415
+ // src/sandbox/sandbox-run-tool.ts
416
+ var SandboxRunError = class extends Error {
417
+ constructor(code, message, options) {
418
+ super(message, options);
419
+ this.code = code;
420
+ this.name = "SandboxRunError";
421
+ }
422
+ code;
423
+ };
424
+ var DEFAULT_TIMEOUT_MS = 5 * 6e4;
425
+ var TASK_LIMIT = 2e4;
426
+ var SANDBOX_RUN_DESCRIPTION = "Run work that needs a computer in this workspace's sandbox: executing code or scripts, reading or converting PDFs, spreadsheets and archives, filling forms with the installed toolkits, or editing many files. Describe the whole task and the result you need; the sandbox agent does it and returns its answer. Takes seconds to minutes, so use it only when the answer needs the computer.";
427
+ function sandboxPromptRunner(shell, prompt = {}) {
428
+ return (box, task, run) => runSandboxPrompt(shell, box, task, { ...prompt, ...run, disallowQuestions: true });
429
+ }
430
+ function createSandboxRunTool(options) {
431
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
432
+ const runTask = options.runTask;
433
+ const fail2 = (code, message, cause) => {
434
+ const error = new SandboxRunError(code, message, cause === void 0 ? void 0 : { cause });
435
+ options.onFailure?.(error);
436
+ throw error;
437
+ };
438
+ return {
439
+ name: options.name ?? "sandbox_run",
440
+ description: options.description ?? SANDBOX_RUN_DESCRIPTION,
441
+ inputSchema: {
442
+ type: "object",
443
+ properties: { task: { type: "string", description: "The complete task for the sandbox agent, with the result you need back." } },
444
+ required: ["task"],
445
+ additionalProperties: false
446
+ },
447
+ async run(args) {
448
+ const task = typeof args.task === "string" ? args.task.trim() : "";
449
+ if (!task || task.length > TASK_LIMIT) {
450
+ return fail2("invalid_arguments", `task must be 1 to ${TASK_LIMIT} characters`);
451
+ }
452
+ const started = Date.now();
453
+ const signal = AbortSignal.any([AbortSignal.timeout(timeoutMs), ...options.signal ? [options.signal] : []]);
454
+ if (options.warm) await options.warm.leases.turn(options.warm.key).catch(() => {
455
+ });
456
+ let box;
457
+ try {
458
+ box = await options.box(signal);
459
+ } catch (error) {
460
+ if (error instanceof SandboxRunError) return fail2(error.code, error.message, error.cause);
461
+ return fail2("sandbox_unavailable", "The sandbox for this workspace could not start, so this work was not done.", error);
462
+ }
463
+ let answer;
464
+ try {
465
+ answer = await Promise.race([
466
+ runTask(box, task, { signal, timeoutMs: Math.max(1, timeoutMs - (Date.now() - started)) }),
467
+ new Promise((_, reject) => {
468
+ if (signal.aborted) reject(signal.reason);
469
+ signal.addEventListener("abort", () => reject(signal.reason), { once: true });
470
+ })
471
+ ]);
472
+ } catch (error) {
473
+ const timedOut = signal.aborted && !options.signal?.aborted;
474
+ return fail2("sandbox_failed", timedOut ? `The sandbox did not finish within ${Math.round(timeoutMs / 1e3)} s, so this work was not done.` : "The sandbox run failed, so this work was not done.", error);
475
+ }
476
+ if (!answer.trim()) return fail2("sandbox_empty", "The sandbox finished without an answer.");
477
+ return { answer, ms: Date.now() - started };
478
+ }
479
+ };
480
+ }
481
+
482
+ // src/sandbox/sandbox-exec-tool.ts
483
+ var DEFAULT_TIMEOUT_MS2 = 2 * 6e4;
484
+ var DEFAULT_OUTPUT_CHARS = 2e4;
485
+ var COMMAND_LIMIT = 1e4;
486
+ var SANDBOX_EXEC_DESCRIPTION = "Run one shell command in this workspace's sandbox and get its exit code, stdout and stderr. Use it for the installed toolkits and scripts, file conversion and checks. A non-zero exit code is a result to read and fix, not a reason to stop.";
487
+ function tail(text, limit) {
488
+ return text.length > limit ? { text: `\u2026${text.slice(-limit)}`, cut: true } : { text, cut: false };
489
+ }
490
+ function raceAbort(work, signal) {
491
+ return Promise.race([work, new Promise((_, reject) => {
492
+ if (signal.aborted) reject(signal.reason);
493
+ signal.addEventListener("abort", () => reject(signal.reason), { once: true });
494
+ })]);
495
+ }
496
+ function createSandboxExecTool(options) {
497
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS2;
498
+ const outputChars = options.maxOutputChars ?? DEFAULT_OUTPUT_CHARS;
499
+ const fail2 = (code, message, cause) => {
500
+ const error = new SandboxRunError(code, message, cause === void 0 ? void 0 : { cause });
501
+ options.onFailure?.(error);
502
+ throw error;
503
+ };
504
+ let ready = null;
505
+ const place = (signal) => {
506
+ ready ??= (async () => {
507
+ let box;
508
+ try {
509
+ box = await options.box(signal);
510
+ } catch (error) {
511
+ if (error instanceof SandboxRunError) throw error;
512
+ throw new SandboxRunError("sandbox_unavailable", "The sandbox for this workspace could not start, so the command did not run.", { cause: error });
513
+ }
514
+ try {
515
+ await options.prepare?.(box, signal);
516
+ } catch (error) {
517
+ throw new SandboxRunError("sandbox_unavailable", "The sandbox could not be prepared for commands, so the command did not run.", { cause: error });
518
+ }
519
+ return box;
520
+ })();
521
+ ready.catch(() => {
522
+ ready = null;
523
+ });
524
+ return ready;
525
+ };
526
+ return {
527
+ name: options.name ?? "sandbox_exec",
528
+ description: options.description ?? SANDBOX_EXEC_DESCRIPTION,
529
+ inputSchema: {
530
+ type: "object",
531
+ properties: {
532
+ command: { type: "string", description: "One shell command, e.g. `tax-python fill_form.py --form 1040`." },
533
+ cwd: { type: "string", description: "Working directory; defaults to the workspace directory." }
534
+ },
535
+ required: ["command"],
536
+ additionalProperties: false
537
+ },
538
+ async run(args) {
539
+ const command = typeof args.command === "string" ? args.command.trim() : "";
540
+ if (!command || command.length > COMMAND_LIMIT) return fail2("invalid_arguments", `command must be 1 to ${COMMAND_LIMIT} characters`);
541
+ const refusal = options.allow?.(command);
542
+ if (refusal) return fail2("invalid_arguments", refusal);
543
+ const cwd = typeof args.cwd === "string" && args.cwd.trim() ? args.cwd.trim() : options.cwd;
544
+ const started = Date.now();
545
+ const signal = AbortSignal.any([AbortSignal.timeout(timeoutMs), ...options.signal ? [options.signal] : []]);
546
+ if (options.warm) await options.warm.leases.turn(options.warm.key).catch(() => {
547
+ });
548
+ let box;
549
+ try {
550
+ box = await raceAbort(place(signal), signal);
551
+ } catch (error) {
552
+ if (error instanceof SandboxRunError) {
553
+ options.onFailure?.(error);
554
+ throw error;
555
+ }
556
+ return fail2("sandbox_unavailable", "The sandbox did not start in time, so the command did not run.", error);
557
+ }
558
+ let result;
559
+ try {
560
+ result = await raceAbort(box.exec(command, {
561
+ ...cwd ? { cwd } : {},
562
+ ...options.env ? { env: options.env } : {},
563
+ timeoutMs: Math.max(1, timeoutMs - (Date.now() - started))
564
+ }), signal);
565
+ } catch (error) {
566
+ const timedOut = signal.aborted && !options.signal?.aborted;
567
+ return fail2("sandbox_failed", timedOut ? `The command did not finish within ${Math.round(timeoutMs / 1e3)} s.` : "The command could not run in the sandbox.", error);
568
+ }
569
+ const stdout = tail(result.stdout ?? "", outputChars);
570
+ const stderr = tail(result.stderr ?? "", outputChars);
571
+ const files = options.listFiles ? await options.listFiles(box, signal).catch(() => void 0) : void 0;
572
+ return {
573
+ exitCode: result.exitCode,
574
+ stdout: stdout.text,
575
+ stderr: stderr.text,
576
+ truncated: stdout.cut || stderr.cut,
577
+ ms: Date.now() - started,
578
+ ...files ? { files } : {}
579
+ };
580
+ }
581
+ };
582
+ }
583
+
415
584
  // src/sandbox/prewarm-claim-d1.ts
416
585
  var DEFAULT_PREWARM_CLAIM_TABLE = "sandbox_prewarm_claims";
417
586
  var PREWARM_CLAIM_TABLE_DDL = `CREATE TABLE IF NOT EXISTS ${DEFAULT_PREWARM_CLAIM_TABLE} (
@@ -3050,6 +3219,12 @@ export {
3050
3219
  createSandboxTerminalConnectionRoute,
3051
3220
  sandboxPrewarmClaimKey,
3052
3221
  createSandboxPrewarmer,
3222
+ SandboxRunError,
3223
+ SANDBOX_RUN_DESCRIPTION,
3224
+ sandboxPromptRunner,
3225
+ createSandboxRunTool,
3226
+ SANDBOX_EXEC_DESCRIPTION,
3227
+ createSandboxExecTool,
3053
3228
  DEFAULT_PREWARM_CLAIM_TABLE,
3054
3229
  PREWARM_CLAIM_TABLE_DDL,
3055
3230
  createD1PrewarmClaimStore,
@@ -3130,4 +3305,4 @@ export {
3130
3305
  isTerminalPromptEvent,
3131
3306
  detectInteractiveQuestion
3132
3307
  };
3133
- //# sourceMappingURL=chunk-OGDEUCNW.js.map
3308
+ //# sourceMappingURL=chunk-JGLK5RDK.js.map