@tangle-network/agent-app 0.60.114 → 0.60.116
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/VaultPane-OWOPGPXP.js +7 -0
- package/dist/assistant/index.js +8 -8
- package/dist/chat-react/index.js +2 -2
- package/dist/chat-routes/index.js +2 -2
- package/dist/{chunk-Y4WLCFDZ.js → chunk-2FLSODOX.js} +6 -6
- package/dist/chunk-BTEVD7HG.js +198 -0
- package/dist/chunk-BTEVD7HG.js.map +1 -0
- package/dist/chunk-FVI2MHUL.js +1152 -0
- package/dist/chunk-FVI2MHUL.js.map +1 -0
- package/dist/{chunk-RQSYR4AV.js → chunk-GHUQ5HXU.js} +4 -4
- package/dist/{chunk-Q7M3GVLL.js → chunk-JCSHTJT6.js} +36 -2
- package/dist/chunk-JCSHTJT6.js.map +1 -0
- package/dist/{chunk-OGDEUCNW.js → chunk-JGLK5RDK.js} +176 -1
- package/dist/chunk-JGLK5RDK.js.map +1 -0
- package/dist/{chunk-AB63T2LM.js → chunk-KBJZMR4E.js} +8 -1
- package/dist/chunk-KBJZMR4E.js.map +1 -0
- package/dist/{chunk-RQSNTJTW.js → chunk-MO7PDQRZ.js} +526 -187
- package/dist/chunk-MO7PDQRZ.js.map +1 -0
- package/dist/{chunk-MEUNTJL5.js → chunk-N3CYCSKK.js} +6 -1
- package/dist/chunk-N3CYCSKK.js.map +1 -0
- package/dist/{chunk-56GPDCOJ.js → chunk-TSGWACTC.js} +5 -5
- package/dist/eval/index.d.ts +2 -0
- package/dist/eval/index.js +64 -0
- package/dist/eval/index.js.map +1 -1
- package/dist/eval/parity.d.ts +74 -0
- package/dist/journeys/cli.d.ts +2 -0
- package/dist/journeys/cli.js +165 -0
- package/dist/journeys/cli.js.map +1 -0
- package/dist/journeys/config.d.ts +96 -0
- package/dist/journeys/index.d.ts +18 -0
- package/dist/journeys/index.js +731 -0
- package/dist/journeys/index.js.map +1 -0
- package/dist/journeys/journey.d.ts +173 -0
- package/dist/journeys/page-reading.d.ts +42 -0
- package/dist/journeys/report.d.ts +51 -0
- package/dist/journeys/score.d.ts +115 -0
- package/dist/journeys/scrub.d.ts +21 -0
- package/dist/journeys/send.d.ts +46 -0
- package/dist/journeys/session.d.ts +27 -0
- package/dist/journeys/trace-zip.d.ts +28 -0
- package/dist/journeys/video.d.ts +53 -0
- package/dist/public-consultation/index.d.ts +1 -1
- package/dist/runtime/index.js +9 -3
- package/dist/runtime/index.js.map +1 -1
- package/dist/runtime/router-turn.d.ts +8 -1
- package/dist/runtime/router-turn.js +9 -3
- package/dist/runtime/turn-knowledge.d.ts +50 -0
- package/dist/sandbox/index.d.ts +2 -0
- package/dist/sandbox/index.js +13 -1
- package/dist/sandbox/sandbox-exec-tool.d.ts +68 -0
- package/dist/sandbox/sandbox-run-tool.d.ts +70 -0
- package/dist/studio-react/index.js +2 -2
- package/dist/teams/index.js +10 -6
- package/dist/teams/invitations-api.js +6 -3
- package/dist/teams/invitations-api.js.map +1 -1
- package/dist/teams/invitations.d.ts +4 -0
- package/dist/teams/members-api.js +2 -1
- package/dist/teams-react/components/InviteForm.d.ts +20 -0
- package/dist/teams-react/contracts.d.ts +2 -0
- package/dist/teams-react/index.js +196 -217
- package/dist/teams-react/index.js.map +1 -1
- package/dist/vault/VaultContentResults.d.ts +29 -0
- package/dist/vault/VaultHistoryPanel.d.ts +20 -0
- package/dist/vault/VaultPane.d.ts +3 -1
- package/dist/vault/contracts.d.ts +38 -0
- package/dist/vault/index.js +1 -1
- package/dist/vault/lazy.js +1 -1
- package/dist/web-react/index.js +22 -22
- package/dist/workspace-export/index.js +4 -193
- package/dist/workspace-export/index.js.map +1 -1
- package/dist/workspace-react/index.js +9 -7
- package/dist/workspace-react/index.js.map +1 -1
- package/dist/workspace-react/workspace-list.d.ts +7 -1
- package/package.json +8 -2
- package/dist/VaultPane-JUSNGOV7.js +0 -7
- package/dist/chunk-AB63T2LM.js.map +0 -1
- package/dist/chunk-MEUNTJL5.js.map +0 -1
- package/dist/chunk-OGDEUCNW.js.map +0 -1
- package/dist/chunk-Q7M3GVLL.js.map +0 -1
- package/dist/chunk-RQSNTJTW.js.map +0 -1
- /package/dist/{VaultPane-JUSNGOV7.js.map → VaultPane-OWOPGPXP.js.map} +0 -0
- /package/dist/{chunk-Y4WLCFDZ.js.map → chunk-2FLSODOX.js.map} +0 -0
- /package/dist/{chunk-RQSYR4AV.js.map → chunk-GHUQ5HXU.js.map} +0 -0
- /package/dist/{chunk-56GPDCOJ.js.map → chunk-TSGWACTC.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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AACxE,QAAIH,YAAW,OAAO,KAAK,UAAU;AACnC,YAAM,SAAS,WACXC,aAAY,QAAQ,EAAE,OAAO,CAAC,MAAM,EAAE,SAAS,MAAM,CAAC,EAAE,KAAK,EAAE,IAAI,CAAC,OAAO,EAAE,MAAM,SAAS,CAAC,IAAI,SAAS,MAAMG,MAAK,UAAU,CAAC,CAAC,EAAE,EAAE,IACrI,CAAC;AACL,UAAI,QAA+B,CAAC;AACpC,UAAIJ,YAAW,OAAO,GAAG;AACvB,YAAI;AACF,kBAAU,KAAK,MAAME,cAAa,SAAS,MAAM,CAAC,EAAwC,SAAS,CAAC;AAAA,QACtG,QAAQ;AACN,kBAAQ,CAAC;AAAA,QACX;AAAA,MACF;AACA,YAAM,KAAK,EAAE,KAAK,SAAS,MAAM,GAAG,GAAG,QAAQ,MAAM,CAAC;AAAA,IACxD;AACA,QAAI,SAAS,EAAG;AAChB,eAAW,QAAQD,aAAY,GAAG,EAAE,KAAK,GAAG;AAC1C,YAAM,OAAOG,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"]}
|
|
@@ -1,9 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
joinClasses
|
|
3
3
|
} from "./chunk-L7MB2LLM.js";
|
|
4
|
-
import {
|
|
5
|
-
filterCommandPaletteItems
|
|
6
|
-
} from "./chunk-SJWIZT7B.js";
|
|
7
4
|
import {
|
|
8
5
|
AgentSessionControls,
|
|
9
6
|
acceptRejectionReason,
|
|
@@ -16,6 +13,9 @@ import {
|
|
|
16
13
|
POPOVER_OPTION_FOCUS,
|
|
17
14
|
PopoverSurface
|
|
18
15
|
} from "./chunk-HG4OONJA.js";
|
|
16
|
+
import {
|
|
17
|
+
filterCommandPaletteItems
|
|
18
|
+
} from "./chunk-SJWIZT7B.js";
|
|
19
19
|
import {
|
|
20
20
|
ATTACHMENT_ACCEPT,
|
|
21
21
|
ATTACHMENT_MAX_COUNT,
|
|
@@ -1551,4 +1551,4 @@ export {
|
|
|
1551
1551
|
ComposerModeControls,
|
|
1552
1552
|
EntryComposer
|
|
1553
1553
|
};
|
|
1554
|
-
//# sourceMappingURL=chunk-
|
|
1554
|
+
//# sourceMappingURL=chunk-GHUQ5HXU.js.map
|
|
@@ -157,6 +157,36 @@ async function* streamChatCompletions(doFetch, url, apiKey, body, attribution, h
|
|
|
157
157
|
}
|
|
158
158
|
}
|
|
159
159
|
|
|
160
|
+
// src/runtime/turn-knowledge.ts
|
|
161
|
+
var DEFAULT_FILE_BYTES = 8e3;
|
|
162
|
+
var DEFAULT_TEXT_BYTES = 16e3;
|
|
163
|
+
var DEFAULT_MAX_FILES = 60;
|
|
164
|
+
function budgetTurnKnowledge(files, budget = {}) {
|
|
165
|
+
const fileBytes = budget.fileBytes ?? DEFAULT_FILE_BYTES;
|
|
166
|
+
let remaining = budget.textBytes ?? DEFAULT_TEXT_BYTES;
|
|
167
|
+
return [...files].sort((a, b) => a.path.localeCompare(b.path)).slice(0, budget.maxFiles ?? DEFAULT_MAX_FILES).map((file) => {
|
|
168
|
+
const fits = file.text !== null && file.size <= fileBytes && file.size <= remaining;
|
|
169
|
+
if (fits) remaining -= file.size;
|
|
170
|
+
return { path: file.path, size: file.size, text: fits ? file.text : null };
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
function turnKnowledgeInstructions(files, options = {}) {
|
|
174
|
+
const read = options.readTool;
|
|
175
|
+
return [
|
|
176
|
+
"Answer questions about this business or its work (hours, times, policies, codes, passwords, prices, contacts, amenities, procedures) only from the knowledge in these instructions, the knowledge files below, or a tool result. Never give a typical or assumed value, and do not say something is absent unless a source says so." + (read ? ` When a listed file without its text may cover the question, read it with ${read} before answering.` : "") + " When nothing covers it, say you do not have that information and offer to ask the owner.",
|
|
177
|
+
...files.map((file) => file.text !== null ? `Knowledge file ${file.path}:
|
|
178
|
+
${file.text}` : `Knowledge file ${file.path} (${file.size} bytes, text not shown)${read ? `: read it with ${read} when the question may be covered by it.` : "."}`)
|
|
179
|
+
];
|
|
180
|
+
}
|
|
181
|
+
async function workspaceKnowledgeForTurn(store, workspaceId, options = {}) {
|
|
182
|
+
const entries = await store.list(workspaceId, options.prefix ?? "/files/");
|
|
183
|
+
return budgetTurnKnowledge(entries.filter((entry) => entry.kind === "file").map((entry) => ({
|
|
184
|
+
path: entry.path,
|
|
185
|
+
size: entry.content !== void 0 ? new TextEncoder().encode(entry.content).byteLength : entry.bytes?.size ?? 0,
|
|
186
|
+
text: entry.content ?? null
|
|
187
|
+
})), options);
|
|
188
|
+
}
|
|
189
|
+
|
|
160
190
|
// src/runtime/router-turn.ts
|
|
161
191
|
var DEFAULT_BUDGET_MS = 9e4;
|
|
162
192
|
var TOOL_RESULT_LIMIT = 12e3;
|
|
@@ -164,7 +194,8 @@ function routerFunctionName(name) {
|
|
|
164
194
|
return name.replace(/[^A-Za-z0-9_-]/g, "_").slice(0, 64);
|
|
165
195
|
}
|
|
166
196
|
function composeRouterTurnPrompt(profile, options = {}) {
|
|
167
|
-
const
|
|
197
|
+
const knowledge = options.knowledge ? turnKnowledgeInstructions(options.knowledge.files, { readTool: options.knowledge.readTool }) : [];
|
|
198
|
+
const text = [profile.prompt?.systemPrompt ?? "", ...profile.prompt?.instructions ?? [], ...knowledge, ...options.context ?? []].filter((part) => part.trim()).join("\n\n");
|
|
168
199
|
return [...options.toolNames ?? []].sort((a, b) => b.length - a.length).reduce((out, name) => out.split(name).join(routerFunctionName(name)), text);
|
|
169
200
|
}
|
|
170
201
|
function defaultToolError(error) {
|
|
@@ -344,8 +375,11 @@ export {
|
|
|
344
375
|
createOpenAICompatStreamTurn,
|
|
345
376
|
runToolLoop,
|
|
346
377
|
streamToolLoop,
|
|
378
|
+
budgetTurnKnowledge,
|
|
379
|
+
turnKnowledgeInstructions,
|
|
380
|
+
workspaceKnowledgeForTurn,
|
|
347
381
|
routerFunctionName,
|
|
348
382
|
composeRouterTurnPrompt,
|
|
349
383
|
runRouterTurn
|
|
350
384
|
};
|
|
351
|
-
//# sourceMappingURL=chunk-
|
|
385
|
+
//# sourceMappingURL=chunk-JCSHTJT6.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/runtime/loop.ts","../src/runtime/openai-stream.ts","../src/runtime/turn-knowledge.ts","../src/runtime/router-turn.ts"],"sourcesContent":["/**\n * The bounded agent tool-loop — owned by `@tangle-network/agent-runtime`.\n *\n * A model turn may emit tool calls (integration-hub actions, the app tools from\n * `../tools`, delegation). The loop streams a turn, collects the executable tool\n * calls, dispatches each, appends the results to history in OpenAI\n * function-calling shape, and re-runs so the model reads them — bounded by\n * `maxToolTurns`, a wall-clock `deadlineMs`, and a `maxCostUsd` budget.\n *\n * The history shape is the OpenAI function-calling contract: the assistant turn\n * that emitted tool calls is preserved as an `assistant` message carrying its\n * `tool_calls` array, and each result is its own `{ role: 'tool', tool_call_id,\n * content }` message keyed to the call. A strict model (Claude, and any\n * OpenAI-compatible provider that validates tool history) needs this to read its\n * own tool use back; folding results into a `user` message makes such models\n * re-issue the same call in a loop.\n *\n * The loop is substrate-owned (`runToolLoop` / `streamToolLoop`); the app\n * supplies `streamTurn` (wrapping its model endpoint) and `executeToolCall`\n * (routing to its integration + app-tool executors). The app-facing names below\n * are 1:1 aliases of the canonical symbols, kept so this package's consumers and\n * the in-package `createAgentRuntime` read against a single, stable vocabulary.\n *\n * This is the LEAF the runtime barrel and its children both import — keeping the\n * tool-loop vocabulary out of any import cycle. The barrel re-exports it.\n */\n\nexport {\n runToolLoop as runAppToolLoop,\n streamToolLoop as streamAppToolLoop,\n} from '@tangle-network/agent-runtime/tool-loop'\nexport type {\n ToolLoopCall as LoopToolCall,\n ToolLoopAssistantToolCall as LoopAssistantToolCall,\n ToolLoopMessage as LoopMessage,\n ToolLoopEvent,\n ToolLoopStopReason,\n ToolLoopResult,\n RunToolLoopOptions as AppToolLoopOptions,\n StreamToolLoopOptions as StreamAppToolLoopOptions,\n StreamToolLoopYield as StreamLoopYield,\n} from '@tangle-network/agent-runtime/tool-loop'\n\n/**\n * Events the app's OpenAI-compat stream adapter ({@link toLoopEvents}) yields.\n *\n * This is the app's own `Raw` event type for the streaming loop — the canonical\n * `streamToolLoop<Raw>` is generic over it. It widens the substrate's\n * tool-loop event with `reasoning` (DeepSeek/router `reasoning_content` /\n * `thinking` deltas, rendered as thinking sections) and `usage` (per-message\n * token accounting) — neither belongs in the substrate's loop contract, so they\n * stay here. The adapter maps each into the `streamTurn` seam; `text` and\n * `tool_call` drive the loop, `reasoning` / `usage` pass through to the UI.\n */\nexport type LoopEvent =\n | { type: 'text'; text: string }\n | { type: 'reasoning'; text: string }\n /** The model has begun a tool call: its name is known, its arguments are\n * still streaming. Emitted once per call, before its `tool_call`. Lets a\n * caller start slow work the call will need (resuming a sandbox box for\n * `sandbox_run`) while the arguments arrive. Consumers that do not care\n * ignore it: it never drives the loop. */\n | { type: 'tool_call_start'; toolCallId?: string; toolName: string }\n | {\n type: 'tool_call'\n call: import('@tangle-network/agent-runtime/tool-loop').ToolLoopCall\n }\n | { type: 'usage'; usage: { promptTokens: number; completionTokens: number } }\n | { type: 'other'; event: unknown }\n","/**\n * OpenAI-compatible stream → `LoopEvent` adapter, for NON-sandbox copilots.\n *\n * `streamAppToolLoop` takes a `streamTurn` seam that yields `LoopEvent`s. A\n * sandboxed agent produces those from its container; a browser/edge copilot\n * instead calls a model directly. The Tangle Router, the tcloud SDK, and most\n * providers all speak the OpenAI Chat Completions streaming shape — so the ONE\n * reusable piece is assembling that stream (content deltas + FRAGMENTED\n * tool-call deltas) into `LoopEvent`s. That assembly is the boilerplate every\n * copilot would re-write (and get wrong — OpenAI streams tool-call arguments in\n * pieces across chunks).\n *\n * This does NOT implement an HTTP client beyond a minimal `fetch` + SSE reader\n * (browser/edge/Node-safe, zero deps). For richer transport use the tcloud SDK\n * or the Vercel AI SDK and pipe their stream through {@link toLoopEvents}.\n */\nimport type { LoopEvent, LoopMessage, LoopToolCall } from './loop'\nimport { normalizeModelId } from './model-catalog'\n\n/** Minimal OpenAI Chat Completions streaming chunk (structural — no `openai` dep). */\nexport interface OpenAIStreamChunk {\n /** The model that produced this chunk. The Tangle Router reports the DATED\n * upstream id here (`gpt-5-2025-08-07`) whether or not it substituted, so\n * this is a served-model source only after id folding — see\n * {@link OpenAICompatServedModel}. */\n model?: string\n choices?: Array<{\n delta?: {\n content?: string | null\n /** Reasoning deltas — DeepSeek/router use `reasoning_content`; some proxies use `thinking`. */\n reasoning_content?: string | null\n thinking?: string | null\n tool_calls?: Array<{\n index: number\n id?: string\n function?: { name?: string; arguments?: string }\n /** Provider-specific call data the next request must echo back. Gemini 3\n * sends `{ google: { thought_signature } }` here and answers HTTP 400\n * when a later request's assistant `tool_calls` entry lacks it. */\n extra_content?: unknown\n }>\n }\n finish_reason?: string | null\n }>\n /** Token accounting (requires `stream_options.include_usage`). Cumulative for\n * the call: the Tangle Router can send it on more than one chunk. */\n usage?: {\n prompt_tokens?: number\n completion_tokens?: number\n } | null\n}\n\ninterface PartialToolCall {\n id?: string\n name: string\n args: string\n extraContent?: unknown\n announced: boolean\n}\n\n/**\n * Map an OpenAI-compat streaming chunk iterator to `LoopEvent`s: each content\n * delta → a `text` event; tool-call deltas are accumulated by index across\n * chunks and emitted as one complete `tool_call` event when the stream finishes\n * (arguments JSON-parsed; an empty/garbled args string yields `{}` rather than\n * throwing). Works for the Tangle Router, tcloud, or any OpenAI-compat source.\n *\n * A call's `extra_content` is kept as `providerFields.extra_content`, which the\n * tool loop echoes on the call's assistant `tool_calls` entry in the next request.\n * Usage is cumulative per call and may arrive on several chunks, so it is\n * yielded once, the last value, when the stream ends.\n *\n * Each call also yields one `tool_call_start` as soon as its name arrives,\n * while its arguments are still streaming, so a caller can start work the call\n * will need. Providers send the whole name in the call's first delta.\n */\nexport async function* toLoopEvents(chunks: AsyncIterable<OpenAIStreamChunk>): AsyncIterable<LoopEvent> {\n const calls = new Map<number, PartialToolCall>()\n let usage: { promptTokens: number; completionTokens: number } | undefined\n for await (const chunk of chunks) {\n // Usage can ride a chunk with an empty choices array — read it before the\n // choice guard. Each report is cumulative, so the last one is the call's.\n if (chunk.usage?.prompt_tokens != null || chunk.usage?.completion_tokens != null) {\n usage = {\n promptTokens: chunk.usage.prompt_tokens ?? 0,\n completionTokens: chunk.usage.completion_tokens ?? 0,\n }\n }\n const choice = chunk.choices?.[0]\n if (!choice) continue\n const content = choice.delta?.content\n if (content) yield { type: 'text', text: content }\n const reasoning = choice.delta?.reasoning_content ?? choice.delta?.thinking\n if (reasoning) yield { type: 'reasoning', text: reasoning }\n for (const tc of choice.delta?.tool_calls ?? []) {\n const cur = calls.get(tc.index) ?? { name: '', args: '', announced: false }\n if (tc.id) cur.id = tc.id\n if (tc.function?.name) cur.name += tc.function.name\n if (tc.function?.arguments) cur.args += tc.function.arguments\n if (tc.extra_content !== undefined) cur.extraContent = tc.extra_content\n calls.set(tc.index, cur)\n if (!cur.announced && cur.name) {\n cur.announced = true\n yield { type: 'tool_call_start', ...(cur.id ? { toolCallId: cur.id } : {}), toolName: cur.name }\n }\n }\n }\n if (usage) yield { type: 'usage', usage }\n for (const [, c] of [...calls.entries()].sort((a, b) => a[0] - b[0])) {\n if (!c.name) continue\n yield {\n type: 'tool_call',\n call: {\n toolCallId: c.id,\n toolName: c.name,\n args: safeParse(c.args),\n ...(c.extraContent !== undefined ? { providerFields: { extra_content: c.extraContent } } : {}),\n } satisfies LoopToolCall,\n }\n }\n}\n\nfunction safeParse(s: string): Record<string, unknown> {\n if (!s.trim()) return {}\n try {\n const v = JSON.parse(s)\n return v && typeof v === 'object' && !Array.isArray(v) ? (v as Record<string, unknown>) : {}\n } catch {\n return {}\n }\n}\n\n/**\n * Which model actually served one direct-router turn.\n *\n * The router substitutes models on purpose — a quota-walled primary comes back\n * `200` answered by a different model — and says so in response headers. This\n * lane used to drop the whole `Response` after taking `.body`, so a turn\n * requested as `claude-sonnet-4-6` and answered by `openai/gpt-5` was recorded\n * by its caller as Claude: per-model quality scoring blamed the wrong model and\n * cost used the wrong price basis.\n *\n * Map this onto the shell's existing attribution contract rather than inventing\n * a second channel — `ChatTurnRouteProducer.modelAttribution()` (`/chat-routes`):\n *\n * modelAttribution: () => ({ requestedModel, servedModel, echoReceived: true })\n *\n * Leave that contract's `servedSource` unset: its union is sandbox\n * profile-resolution vocabulary with no router analogue.\n */\nexport interface OpenAICompatServedModel {\n /** The model id this turn asked for (`OpenAICompatStreamTurnOptions.model`). */\n requestedModel: string\n /** The model the router/provider reports having actually served. */\n servedModel: string\n /** Where `servedModel` was read from. The header is the router's own\n * substitution signal; the body is the backstop that survives CORS. */\n source: 'router_header' | 'response_body'\n /** True when served differs from requested after id folding. Folded, not\n * compared raw: the body reports a dated id on EVERY turn, so `!==` would\n * claim a substitution every time. */\n substituted: boolean\n /** `x-tangle-failover` `trigger=` — why the router swapped. Absent when the\n * router did not inject the substitute (a caller-supplied fallback chain\n * sets the served-model header without the failover one). */\n trigger?: string\n /** `x-tangle-failover` `degraded=`. */\n degraded?: boolean\n}\n\n/** Parse `from=…; to=…; trigger=…; degraded=…` down to the fields we report.\n * Absent/garbled segments are simply omitted — attribution is best-effort and\n * must never fail a turn that is otherwise streaming fine. */\nfunction parseFailoverHeader(raw: string | null): { trigger?: string; degraded?: boolean } {\n if (!raw) return {}\n const fields = new Map<string, string>()\n for (const segment of raw.split(';')) {\n const eq = segment.indexOf('=')\n if (eq === -1) continue\n fields.set(segment.slice(0, eq).trim().toLowerCase(), segment.slice(eq + 1).trim())\n }\n const trigger = fields.get('trigger')\n const degraded = fields.get('degraded')\n return {\n ...(trigger ? { trigger } : {}),\n ...(degraded != null ? { degraded: degraded === 'true' } : {}),\n }\n}\n\n/** Define options for configuring an OpenAI-compatible streaming chat turn including API details and tools */\nexport interface OpenAICompatStreamTurnOptions {\n /** OpenAI-compat base URL (e.g. the Tangle Router `https://router.tangle.tools/v1`). */\n baseUrl: string\n apiKey: string\n model: string\n /** OpenAI tool definitions — pass `buildAppToolOpenAITools(taxonomy)` so the\n * model can call the app tools. Omit for a tool-free copilot. */\n tools?: unknown[]\n temperature?: number\n fetchImpl?: typeof fetch\n /** Extra body fields (e.g. `max_tokens`). */\n extraBody?: Record<string, unknown>\n /** Extra request headers, e.g. a trace id the router records with the generation. */\n headers?: Record<string, string>\n /**\n * Called at most ONCE per turn, as soon as the serving model is\n * determinable, with what actually answered. Never called when neither the\n * header nor the body names a model — silence means \"learned nothing\", not\n * \"nothing was substituted\".\n *\n * `streamTurn` runs once per TOOL turn, so a multi-turn `runAppToolLoop`\n * fires this once per turn; take the last for row attribution.\n */\n onServedModel?: (served: OpenAICompatServedModel) => void\n}\n\n/**\n * Build a `streamTurn` that calls an OpenAI-compatible `/chat/completions`\n * endpoint (Tangle Router / tcloud / any compat provider) with `stream: true`\n * and yields `LoopEvent`s via {@link toLoopEvents}. Browser/edge/Node-safe —\n * just `fetch` + an SSE reader. Drop straight into `streamAppToolLoop`:\n *\n * const cfg = resolveTangleModelConfig() // or { baseUrl, apiKey, model }\n * streamAppToolLoop({ streamTurn: createOpenAICompatStreamTurn({ ...cfg, tools }), executeToolCall, ... })\n */\nexport function createOpenAICompatStreamTurn(\n opts: OpenAICompatStreamTurnOptions,\n): (messages: LoopMessage[]) => AsyncIterable<LoopEvent> {\n const base = opts.baseUrl.replace(/\\/+$/, '')\n const doFetch = opts.fetchImpl ?? fetch\n return (messages) =>\n toLoopEvents(\n streamChatCompletions(doFetch, `${base}/chat/completions`, opts.apiKey, {\n model: opts.model,\n messages,\n stream: true,\n stream_options: { include_usage: true },\n ...(opts.tools && opts.tools.length > 0 ? { tools: opts.tools } : {}),\n ...(opts.temperature != null ? { temperature: opts.temperature } : {}),\n ...opts.extraBody,\n }, opts.onServedModel ? { requestedModel: opts.model, report: opts.onServedModel } : undefined, opts.headers),\n )\n}\n\n/** Stream + parse an OpenAI-compat SSE response into chunks. Tolerates `data:`\n * framing, multi-line buffers, and the terminal `[DONE]`. */\nasync function* streamChatCompletions(\n doFetch: typeof fetch,\n url: string,\n apiKey: string,\n body: Record<string, unknown>,\n attribution?: { requestedModel: string; report: (served: OpenAICompatServedModel) => void },\n headers?: Record<string, string>,\n): AsyncIterable<OpenAIStreamChunk> {\n const res = await doFetch(url, {\n method: 'POST',\n headers: { ...headers, Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json', Accept: 'text/event-stream' },\n body: JSON.stringify(body),\n })\n if (!res.ok || !res.body) {\n const text = res.body ? await res.text().catch(() => '') : ''\n const error = new Error(`OpenAI-compat stream failed (HTTP ${res.status})${text ? `: ${text.slice(0, 200)}` : ''}`)\n // Stamp the NUMERIC status. `isUpstreamUnavailable` (`/model-resolution`)\n // reads a numeric field first and prose only as a backstop, and a\n // Cloudflare EDGE 502 gives it nothing else to read: `content-type:\n // text/plain`, a body of `error code: 502`, and none of the router's own\n // `x-tangle-*` headers, because the origin never ran. Carrying the status\n // as data keeps THIS path — the browser/edge copilot lane, which calls the\n // router directly — out of the string-matching business entirely.\n Object.assign(error, { status: res.status })\n throw error\n }\n // Served-model attribution, fired at most once, as early as it is knowable.\n //\n // The header comes first because it is the router's OWN substitution signal:\n // `X-Tangle-Served-Model` is set only when the served model differs from the\n // requested one, so its presence is authoritative and it arrives before the\n // first byte of content. `X-Tangle-Failover` rides along only when the router\n // itself picked the substitute (a caller-supplied fallback chain sets the\n // former without the latter), which is why `trigger`/`degraded` are optional.\n //\n // The body is the backstop for when the header cannot reach us. In a BROWSER,\n // headers are invisible to JS unless the server lists them in\n // `Access-Control-Expose-Headers` — tangle-router#324 added both, but that\n // only helps once it is DEPLOYED, and any other OpenAI-compat endpoint\n // pointed at this client exposes nothing. The chunk `model` field is not\n // subject to CORS, so it keeps the browser lane attributable regardless.\n let reported = false\n const report = (served: OpenAICompatServedModel): void => {\n if (reported || !attribution) return\n reported = true\n attribution.report(served)\n }\n if (attribution) {\n const servedHeader = res.headers.get('x-tangle-served-model')\n if (servedHeader) {\n report({\n requestedModel: attribution.requestedModel,\n servedModel: servedHeader,\n source: 'router_header',\n substituted: normalizeModelId(servedHeader) !== normalizeModelId(attribution.requestedModel),\n ...parseFailoverHeader(res.headers.get('x-tangle-failover')),\n })\n }\n }\n const reader = res.body.getReader()\n const decoder = new TextDecoder()\n let buffer = ''\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n buffer += decoder.decode(value, { stream: true })\n const lines = buffer.split('\\n')\n buffer = lines.pop() ?? ''\n for (const line of lines) {\n const trimmed = line.trim()\n if (!trimmed.startsWith('data:')) continue\n const data = trimmed.slice(5).trim()\n if (data === '[DONE]') return\n let chunk: OpenAIStreamChunk\n try {\n chunk = JSON.parse(data) as OpenAIStreamChunk\n } catch {\n continue /* skip a partial/garbled SSE frame */\n }\n // Body fallback: only when the header said nothing. Fold both ids before\n // comparing — the router reports the dated upstream id (`gpt-5-2025-08-07`)\n // for a request of `openai/gpt-5` even with NO substitution, so a raw\n // `!==` would report a swap on literally every turn.\n if (attribution && !reported && chunk.model) {\n report({\n requestedModel: attribution.requestedModel,\n servedModel: chunk.model,\n source: 'response_body',\n substituted: normalizeModelId(chunk.model) !== normalizeModelId(attribution.requestedModel),\n })\n }\n yield chunk\n }\n }\n}\n","/**\n * Knowledge in every turn: the index of an app's knowledge files, the full\n * text of the small ones, and the rule that keeps answers on them.\n *\n * Measured on Hospitality production (2026-10-11): a Router turn that had to\n * discover files through list/read tools answered 17/17 correctly but needed\n * 3 tool calls (first words 12-17 s), and a turn that skipped the tools\n * answered from model defaults (\"checkout 11:00\" when the file said 12 pm).\n * Putting the text in the prompt removes both failure modes.\n */\n/** The fields read from an agent-runtime workspace-store entry; structural so older runtimes still type-check. */\ninterface KnowledgeEntry { path: string; kind: string; content?: string; bytes?: { size: number } }\n\n/** One knowledge file a turn carries; `text` is null when it is too large or not readable here. */\nexport interface TurnKnowledgeFile {\n path: string\n size: number\n text: string | null\n}\n\nexport interface TurnKnowledgeBudget {\n /** Files at most this many bytes have their text included. Default 8 000. */\n fileBytes?: number\n /** Total text bytes across files. Default 16 000. */\n textBytes?: number\n /** Most files listed. Default 60. */\n maxFiles?: number\n}\n\nconst DEFAULT_FILE_BYTES = 8_000\nconst DEFAULT_TEXT_BYTES = 16_000\nconst DEFAULT_MAX_FILES = 60\n\n/** Apply the byte budget in path order: small files keep their text until the total is spent. */\nexport function budgetTurnKnowledge(files: readonly TurnKnowledgeFile[], budget: TurnKnowledgeBudget = {}): TurnKnowledgeFile[] {\n const fileBytes = budget.fileBytes ?? DEFAULT_FILE_BYTES\n let remaining = budget.textBytes ?? DEFAULT_TEXT_BYTES\n return [...files].sort((a, b) => a.path.localeCompare(b.path)).slice(0, budget.maxFiles ?? DEFAULT_MAX_FILES)\n .map(file => {\n const fits = file.text !== null && file.size <= fileBytes && file.size <= remaining\n if (fits) remaining -= file.size\n return { path: file.path, size: file.size, text: fits ? file.text : null }\n })\n}\n\n/**\n * The prompt lines for a turn's knowledge. `readTool` names the tool that\n * opens a listed file whose text is not shown; without one, such a file is\n * listed by name only.\n */\nexport function turnKnowledgeInstructions(files: readonly TurnKnowledgeFile[], options: { readTool?: string } = {}): string[] {\n const read = options.readTool\n return [\n 'Answer questions about this business or its work (hours, times, policies, codes, passwords, prices, contacts, amenities, procedures) only from the knowledge in these instructions, the knowledge files below, or a tool result. Never give a typical or assumed value, and do not say something is absent unless a source says so.' +\n (read ? ` When a listed file without its text may cover the question, read it with ${read} before answering.` : '') +\n ' When nothing covers it, say you do not have that information and offer to ask the owner.',\n ...files.map(file => file.text !== null ? `Knowledge file ${file.path}:\\n${file.text}`\n : `Knowledge file ${file.path} (${file.size} bytes, text not shown)${read ? `: read it with ${read} when the question may be covered by it.` : '.'}`),\n ]\n}\n\n/** A workspace store's knowledge files (kind `file` under `prefix`) as turn knowledge, within the budget. */\nexport async function workspaceKnowledgeForTurn(\n store: { list(workspaceId: string, prefix: string): Promise<readonly KnowledgeEntry[]> },\n workspaceId: string,\n options: TurnKnowledgeBudget & { prefix?: string } = {},\n): Promise<TurnKnowledgeFile[]> {\n const entries = await store.list(workspaceId, options.prefix ?? '/files/')\n return budgetTurnKnowledge(entries.filter(entry => entry.kind === 'file').map(entry => ({\n path: entry.path,\n size: entry.content !== undefined ? new TextEncoder().encode(entry.content).byteLength : entry.bytes?.size ?? 0,\n text: entry.content ?? null,\n })), options)\n}\n","/**\n * One conversational turn answered by a model through the Tangle Router, with\n * the app's own tools executed in-process — no sandbox in the path.\n *\n * This is the default runtime for conversational turns in an agent app: the\n * product supplies the principal's tools, the profile prompt and the\n * conversation; the engine streams words as the model writes them, runs tool\n * calls through the bounded `streamAppToolLoop`, and returns one outcome.\n * Long, file or code work belongs to the sandbox, reached through a tool the\n * product adds to `tools`.\n *\n * Every failure is an outcome, never a throw. A durable turn owner retries\n * thrown errors, and a retry after a tool ran would repeat that tool's effect\n * (\"never re-run a turn automatically\", docs/agent-app-lessons.md). The only\n * automatic repeat is one model call that failed before any word or tool.\n */\nimport { streamAppToolLoop, type LoopEvent, type LoopMessage, type LoopToolCall, type ToolLoopStopReason } from './loop'\nimport { DEFAULT_TANGLE_ROUTER_BASE_URL } from './model'\nimport { createOpenAICompatStreamTurn } from './openai-stream'\nimport { turnKnowledgeInstructions, type TurnKnowledgeFile } from './turn-knowledge'\nexport { budgetTurnKnowledge, turnKnowledgeInstructions, workspaceKnowledgeForTurn, type TurnKnowledgeBudget, type TurnKnowledgeFile } from './turn-knowledge'\n\n/** A tool the turn may call. Structurally an `McpToolDefinition` whose env is already bound. */\nexport interface RouterTurnTool {\n name: string\n description: string\n /** JSON Schema for the arguments object. */\n inputSchema: Record<string, unknown>\n run(args: Record<string, unknown>): Promise<unknown>\n}\n\n/** What the turn is doing, in the order it happens, for a live view. */\nexport type RouterTurnEvent =\n | { type: 'text'; segment: number; delta: string }\n | { type: 'tool'; callId: string; toolName: string; status: 'running'; input: Record<string, unknown>; startedAt: number }\n | { type: 'tool'; callId: string; toolName: string; status: 'completed'; output: unknown; startedAt: number; endedAt: number }\n | { type: 'tool'; callId: string; toolName: string; status: 'error'; error: { code: string; message: string }; startedAt: number; endedAt: number }\n | { type: 'usage'; promptTokens: number; completionTokens: number }\n\nexport interface RouterTurnFailure {\n /** `model_http_<status>`, `model_unavailable`, `turn_<stopReason>` or `router_unconfigured`. */\n code: string\n status?: number\n message: string\n}\n\nexport interface RouterTurnOutcome {\n /** Every text segment the model wrote, joined by blank lines. */\n text: string\n /** The model the router reports having served, when it said. */\n servedModel: string | null\n toolCalls: Array<{ callId: string; toolName: string; ok: boolean }>\n /** Token use summed over every model call in the turn, as the router reported it. */\n usage: { promptTokens: number; completionTokens: number; modelCalls: number }\n failure?: RouterTurnFailure\n}\n\nexport interface RouterTurnOptions {\n apiKey: string\n model: string\n /** Defaults to the Tangle Router. */\n baseUrl?: string\n systemPrompt: string\n userMessage: string\n /** Earlier turns. Plain text messages, or OpenAI function-calling history (an assistant message\n * carrying `tool_calls` and the `tool` messages answering them) so the model sees what it did. */\n history?: Array<{ role: 'user' | 'assistant'; content: string } | LoopMessage>\n tools?: RouterTurnTool[]\n /** Wall-clock budget in ms. Default 90 s. A caller whose retry window is shorter passes less. */\n budgetMs?: number\n /** Runaway backstop on model turns. Default 12. */\n maxToolTurns?: number\n maxTokens?: number\n /** Sent as `x-tangle-trace-id` so the router's generation joins the app's trace. */\n traceId?: string\n fetchImpl?: typeof fetch\n onEvent?: (event: RouterTurnEvent) => void\n /** Map a thrown tool error to what the model reads. Default: an error carrying string `code`\n * (and numeric `status`) is reported with its message; anything else is a generic failure. */\n toolError?: (error: unknown) => { code: string; message: string; status?: number } | null\n /** Called for a tool failure the default mapping hides from the model, for the app's logs. */\n onToolFailure?: (toolName: string, error: unknown) => void\n}\n\nconst DEFAULT_BUDGET_MS = 90_000\nconst TOOL_RESULT_LIMIT = 12_000\n\n/** OpenAI-compatible function names allow only `[A-Za-z0-9_-]{1,64}`; app tool names often use dots. */\nexport function routerFunctionName(name: string): string {\n return name.replace(/[^A-Za-z0-9_-]/g, '_').slice(0, 64)\n}\n\n/**\n * The lean system prompt for a Router turn: the profile's system prompt and\n * instructions, the turn's knowledge files, then caller context, with tool names rewritten to the function\n * names the model actually calls.\n */\nexport function composeRouterTurnPrompt(\n profile: { prompt?: { systemPrompt?: string; instructions?: readonly string[] } },\n options: {\n context?: readonly string[]\n toolNames?: readonly string[]\n /** Knowledge files every turn carries; see {@link turnKnowledgeInstructions}. */\n knowledge?: { files: readonly TurnKnowledgeFile[]; readTool?: string }\n } = {},\n): string {\n const knowledge = options.knowledge ? turnKnowledgeInstructions(options.knowledge.files, { readTool: options.knowledge.readTool }) : []\n const text = [profile.prompt?.systemPrompt ?? '', ...(profile.prompt?.instructions ?? []), ...knowledge, ...(options.context ?? [])]\n .filter(part => part.trim()).join('\\n\\n')\n return [...(options.toolNames ?? [])].sort((a, b) => b.length - a.length)\n .reduce((out, name) => out.split(name).join(routerFunctionName(name)), text)\n}\n\nfunction defaultToolError(error: unknown): { code: string; message: string; status?: number } | null {\n const value = error as { code?: unknown; status?: unknown; message?: unknown; issues?: unknown }\n if (Array.isArray(value?.issues)) {\n return { code: 'invalid_arguments', message: JSON.stringify(value.issues).slice(0, 600) }\n }\n if (typeof value?.code === 'string' && typeof value.message === 'string') {\n return { code: value.code, message: value.message, ...(typeof value.status === 'number' ? { status: value.status } : {}) }\n }\n return null\n}\n\nfunction renderResult(outcome: { ok: true; result: unknown } | { ok: false; code: string; message: string }): string {\n if (!outcome.ok) return `Error (${outcome.code}): ${outcome.message}`\n let text: string\n try { text = typeof outcome.result === 'string' ? outcome.result : JSON.stringify(outcome.result ?? null) }\n catch { text = String(outcome.result) }\n return text.length > TOOL_RESULT_LIMIT ? `${text.slice(0, TOOL_RESULT_LIMIT)}…` : text\n}\n\nexport async function runRouterTurn(options: RouterTurnOptions): Promise<RouterTurnOutcome> {\n if (!options.apiKey) {\n return { text: '', servedModel: null, toolCalls: [], usage: { promptTokens: 0, completionTokens: 0, modelCalls: 0 },\n failure: { code: 'router_unconfigured', message: 'The model credential is not configured.' } }\n }\n const emit = options.onEvent ?? (() => {})\n const byFunction = new Map<string, RouterTurnTool>()\n for (const tool of options.tools ?? []) {\n const fn = routerFunctionName(tool.name)\n if (!byFunction.has(fn)) byFunction.set(fn, tool)\n }\n let servedModel: string | null = null\n const streamTurn = createOpenAICompatStreamTurn({\n baseUrl: options.baseUrl ?? DEFAULT_TANGLE_ROUTER_BASE_URL,\n apiKey: options.apiKey,\n model: options.model,\n tools: [...byFunction.entries()].map(([name, tool]) => ({\n type: 'function', function: { name, description: tool.description, parameters: tool.inputSchema },\n })),\n ...(options.maxTokens ? { extraBody: { max_tokens: options.maxTokens } } : {}),\n ...(options.traceId ? { headers: { 'x-tangle-trace-id': options.traceId } } : {}),\n ...(options.fetchImpl ? { fetchImpl: options.fetchImpl } : {}),\n onServedModel: served => { servedModel = served.servedModel },\n })\n const segments: string[] = []\n const usage = { promptTokens: 0, completionTokens: 0, modelCalls: 0 }\n const toolCalls: RouterTurnOutcome['toolCalls'] = []\n const started = new Map<string, number>()\n let segmentOpen = false\n let toolsRan = 0\n const deadline = Date.now() + (options.budgetMs ?? DEFAULT_BUDGET_MS)\n const callIdOf = (id: string | undefined, toolName: string) => id ?? `${toolName}-${started.size}`\n\n const run = async (): Promise<ToolLoopStopReason> => {\n for await (const step of streamAppToolLoop<LoopEvent>({\n systemPrompt: options.systemPrompt,\n userMessage: options.userMessage,\n priorMessages: (options.history ?? []) as LoopMessage[],\n streamTurn,\n extractText: event => event.type === 'text' ? event.text : '',\n extractToolCall: event => event.type === 'tool_call' ? event.call : null,\n isExecutableTool: name => byFunction.has(name),\n deadlineMs: deadline,\n maxToolTurns: options.maxToolTurns ?? 12,\n renderResult: (_label, outcome) => renderResult(outcome),\n executeToolCall: async (call: LoopToolCall) => {\n const tool = byFunction.get(call.toolName)\n if (!tool) return { ok: false, code: 'unknown_tool', message: `No tool named ${call.toolName}` }\n toolsRan++\n try {\n return { ok: true, result: await tool.run(call.args) }\n } catch (error) {\n const mapped = (options.toolError ?? defaultToolError)(error)\n if (mapped) return { ok: false, ...mapped }\n options.onToolFailure?.(tool.name, error)\n return { ok: false, code: 'tool_failed', message: 'The tool failed; tell the user what could not be completed.' }\n }\n },\n })) {\n if (step.kind === 'event') {\n const event = step.event\n if (event.type === 'text' && event.text) {\n if (!segmentOpen) { segments.push(''); segmentOpen = true }\n segments[segments.length - 1] += event.text\n emit({ type: 'text', segment: segments.length, delta: event.text })\n } else if (event.type === 'usage') {\n usage.promptTokens += event.usage.promptTokens\n usage.completionTokens += event.usage.completionTokens\n usage.modelCalls++\n emit({ type: 'usage', ...event.usage })\n } else if (event.type === 'tool_call') {\n segmentOpen = false\n const tool = byFunction.get(event.call.toolName)\n const callId = callIdOf(event.call.toolCallId, event.call.toolName)\n started.set(callId, Date.now())\n emit({ type: 'tool', callId, toolName: tool?.name ?? event.call.toolName, status: 'running',\n input: event.call.args, startedAt: started.get(callId)! })\n }\n } else if (step.kind === 'tool_result') {\n const tool = byFunction.get(step.toolName)\n const callId = callIdOf(step.toolCallId, step.toolName)\n const startedAt = started.get(callId) ?? Date.now()\n const toolName = tool?.name ?? step.toolName\n toolCalls.push({ callId, toolName, ok: step.outcome.ok })\n emit(step.outcome.ok\n ? { type: 'tool', callId, toolName, status: 'completed', output: step.outcome.result, startedAt, endedAt: Date.now() }\n : { type: 'tool', callId, toolName, status: 'error', startedAt, endedAt: Date.now(),\n error: { code: step.outcome.code, message: step.outcome.message } })\n } else if (step.kind === 'capped') {\n return step.stopReason\n }\n }\n return 'completed'\n }\n\n const outcome = (failure?: RouterTurnFailure): RouterTurnOutcome => ({\n text: segments.map(part => part.trim()).filter(Boolean).join('\\n\\n'),\n servedModel, toolCalls, usage: { ...usage }, ...(failure ? { failure } : {}),\n })\n let stop: ToolLoopStopReason\n try {\n try {\n stop = await run()\n } catch (error) {\n // Safe to repeat only while nothing was said and no tool ran.\n if (toolsRan > 0 || segments.length > 0) throw error\n stop = await run()\n }\n } catch (error) {\n const status = (error as { status?: unknown }).status\n return outcome(typeof status === 'number'\n ? { code: `model_http_${status}`, status, message: 'The model service did not answer.' }\n : { code: 'model_unavailable', message: 'The model service did not answer.' })\n }\n if (stop !== 'completed') return outcome({ code: `turn_${stop}`, message: 'The reply was stopped before it finished.' })\n // A model can end its turn with neither a word nor a tool call (gemini-2.5-flash did on 8 of\n // 53 \"remember\" turns, 2026-10-11). Nothing was said and nothing ran, so one repeat is safe;\n // an answer still blank is a typed failure, never a successful empty reply.\n if (!segments.some(part => part.trim())) {\n if (toolsRan === 0) {\n try { stop = await run() } catch { stop = 'completed' }\n if (stop !== 'completed') return outcome({ code: `turn_${stop}`, message: 'The reply was stopped before it finished.' })\n }\n if (!segments.some(part => part.trim())) {\n return outcome({ code: 'model_empty', message: 'The model finished without writing a reply.' })\n }\n }\n return outcome()\n}\n"],"mappings":";;;;;;;;AA2BA;AAAA,EACiB;AAAA,EACG;AAAA,OACb;;;AC8CP,gBAAuB,aAAa,QAAoE;AACtG,QAAM,QAAQ,oBAAI,IAA6B;AAC/C,MAAI;AACJ,mBAAiB,SAAS,QAAQ;AAGhC,QAAI,MAAM,OAAO,iBAAiB,QAAQ,MAAM,OAAO,qBAAqB,MAAM;AAChF,cAAQ;AAAA,QACN,cAAc,MAAM,MAAM,iBAAiB;AAAA,QAC3C,kBAAkB,MAAM,MAAM,qBAAqB;AAAA,MACrD;AAAA,IACF;AACA,UAAM,SAAS,MAAM,UAAU,CAAC;AAChC,QAAI,CAAC,OAAQ;AACb,UAAM,UAAU,OAAO,OAAO;AAC9B,QAAI,QAAS,OAAM,EAAE,MAAM,QAAQ,MAAM,QAAQ;AACjD,UAAM,YAAY,OAAO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