@tangle-network/agent-app 0.63.18 → 0.63.19
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent-profiles/d1.js +2 -2
- package/dist/agent-profiles/index.js +2 -2
- package/dist/agent-profiles/switch.d.ts +1 -1
- package/dist/agent-profiles/switch.js +1 -1
- package/dist/app-auth/index.js.map +1 -1
- package/dist/chat-routes/hybrid-producer.d.ts +1 -1
- package/dist/chat-routes/index.js +11 -11
- package/dist/chat-routes/model-failover-stream.d.ts +1 -1
- package/dist/chat-routes/turn-prefetch.d.ts +1 -1
- package/dist/{chunk-Z4RD5UF7.js → chunk-2PCNHHN2.js} +2 -2
- package/dist/{chunk-I6BZVIRH.js → chunk-3CI35I4X.js} +1 -1
- package/dist/chunk-3CI35I4X.js.map +1 -0
- package/dist/{chunk-ISP6ZH3G.js → chunk-3Q3UEWKK.js} +1 -1
- package/dist/chunk-3Q3UEWKK.js.map +1 -0
- package/dist/{chunk-VDYEVCQQ.js → chunk-5WSSH3X5.js} +2 -2
- package/dist/chunk-5WSSH3X5.js.map +1 -0
- package/dist/{chunk-NUWSPR5O.js → chunk-G3LZITCA.js} +2 -2
- package/dist/{chunk-IX6UVHXY.js → chunk-JKECSYDB.js} +2 -2
- package/dist/{chunk-6GX3UHQW.js → chunk-K3A2YAIX.js} +6 -6
- package/dist/chunk-K3A2YAIX.js.map +1 -0
- package/dist/{chunk-5GSZGTPJ.js → chunk-KA6LD4OI.js} +3 -3
- package/dist/{chunk-A3BJDXPX.js → chunk-LMIP4OVR.js} +5 -5
- package/dist/chunk-LMIP4OVR.js.map +1 -0
- package/dist/{chunk-MT6ZTQGD.js → chunk-N5RWYR5N.js} +1 -1
- package/dist/chunk-N5RWYR5N.js.map +1 -0
- package/dist/{chunk-7VTGB4DM.js → chunk-OSMMEMDH.js} +1 -1
- package/dist/chunk-OSMMEMDH.js.map +1 -0
- package/dist/{chunk-5FAKBTCK.js → chunk-OYFA7BAK.js} +1 -1
- package/dist/chunk-OYFA7BAK.js.map +1 -0
- package/dist/{chunk-7EDNPQHW.js → chunk-OZDMIYES.js} +1 -1
- package/dist/chunk-OZDMIYES.js.map +1 -0
- package/dist/{chunk-ZLX4BA27.js → chunk-QUT3T2IN.js} +1 -1
- package/dist/chunk-QUT3T2IN.js.map +1 -0
- package/dist/{chunk-PK65B6HP.js → chunk-UJYEBQMS.js} +1 -1
- package/dist/{chunk-PK65B6HP.js.map → chunk-UJYEBQMS.js.map} +1 -1
- package/dist/{chunk-5UQJ7F3P.js → chunk-UULUBF5J.js} +1 -1
- package/dist/chunk-UULUBF5J.js.map +1 -0
- package/dist/{chunk-LRYY3OX7.js → chunk-VEPII3YP.js} +4 -4
- package/dist/chunk-VEPII3YP.js.map +1 -0
- package/dist/{chunk-AVBNS64P.js → chunk-W6G2HF6M.js} +1 -1
- package/dist/chunk-W6G2HF6M.js.map +1 -0
- package/dist/{chunk-4GINUJPF.js → chunk-WRCMVBUJ.js} +1 -1
- package/dist/{chunk-4GINUJPF.js.map → chunk-WRCMVBUJ.js.map} +1 -1
- package/dist/{chunk-E3AOUTIR.js → chunk-XGFGSZS5.js} +2 -2
- package/dist/chunk-XGFGSZS5.js.map +1 -0
- package/dist/{chunk-EKXG4JSN.js → chunk-YRWUJKW5.js} +2 -2
- package/dist/chunk-YRWUJKW5.js.map +1 -0
- package/dist/journeys/cli.js +1 -1
- package/dist/journeys/index.js +1 -1
- package/dist/journeys/index.js.map +1 -1
- package/dist/journeys/score.d.ts +1 -1
- package/dist/journeys/scoreboard.d.ts +1 -2
- package/dist/journeys/send.d.ts +1 -2
- package/dist/launch-invariants/auth-lookup-cache.d.ts +1 -1
- package/dist/launch-invariants/catalog.d.ts +3 -3
- package/dist/launch-invariants/cli.js +3 -3
- package/dist/launch-invariants/index.d.ts +1 -1
- package/dist/launch-invariants/index.js +3 -3
- package/dist/launch-invariants/index.js.map +1 -1
- package/dist/launch-invariants/limit-alarms.d.ts +1 -1
- package/dist/launch-invariants/pasted-code.d.ts +1 -1
- package/dist/launch-invariants/schedule.d.ts +1 -1
- package/dist/launch-invariants/settlement.d.ts +2 -2
- package/dist/launch-invariants/sized-reads.d.ts +1 -1
- package/dist/launch-invariants/testing.js +3 -3
- package/dist/model-resolution/index.js +1 -1
- package/dist/platform/billable-turn-admission.d.ts +1 -1
- package/dist/platform/delegated-keys.d.ts +2 -2
- package/dist/platform/delegated-turn-keys.d.ts +1 -1
- package/dist/platform/index.js.map +1 -1
- package/dist/preflight/cli.js +1 -1
- package/dist/preflight/index.d.ts +1 -1
- package/dist/preflight/index.js +1 -1
- package/dist/preset-cloudflare/index.js +6 -6
- package/dist/public-consultation/index.js +9 -9
- package/dist/rollout/cli.js +1 -1
- package/dist/rollout/d1.js +1 -1
- package/dist/rollout/index.d.ts +1 -1
- package/dist/rollout/index.js +1 -1
- package/dist/runtime/index.js +3 -3
- package/dist/runtime/router-turn.d.ts +3 -3
- package/dist/runtime/router-turn.js +2 -2
- package/dist/runtime/turn-knowledge.d.ts +1 -1
- package/dist/sandbox/index.js +5 -5
- package/dist/sandbox/model.d.ts +1 -1
- package/dist/sandbox/prewarm-claim-d1.d.ts +1 -1
- package/dist/sandbox/prewarm.d.ts +2 -2
- package/dist/sandbox/reuse-state.d.ts +1 -1
- package/dist/sandbox/terminal-connection.d.ts +4 -4
- package/dist/sandbox/warm-lease.d.ts +2 -2
- package/dist/sandbox/warm-receipts.d.ts +1 -1
- package/dist/signoff/app-defaults.d.ts +1 -1
- package/dist/signoff/cli.js +2 -2
- package/dist/signoff/index.js +2 -2
- package/dist/signoff/surface-ladder.d.ts +2 -2
- package/dist/signoff/workspace-surface.d.ts +1 -1
- package/dist/stream/index.js +2 -2
- package/dist/stream/turn-buffer.d.ts +1 -1
- package/dist/turn-health/index.js +1 -1
- package/dist/turn-health/index.js.map +1 -1
- package/dist/turn-stream/adapters.d.ts +1 -1
- package/dist/turn-stream/core.d.ts +1 -1
- package/dist/turn-stream/index.js +2 -2
- package/dist/turn-trace/index.js +1 -1
- package/dist/turn-trace/otel.d.ts +1 -1
- package/dist/workspace-export/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-5FAKBTCK.js.map +0 -1
- package/dist/chunk-5UQJ7F3P.js.map +0 -1
- package/dist/chunk-6GX3UHQW.js.map +0 -1
- package/dist/chunk-7EDNPQHW.js.map +0 -1
- package/dist/chunk-7VTGB4DM.js.map +0 -1
- package/dist/chunk-A3BJDXPX.js.map +0 -1
- package/dist/chunk-AVBNS64P.js.map +0 -1
- package/dist/chunk-E3AOUTIR.js.map +0 -1
- package/dist/chunk-EKXG4JSN.js.map +0 -1
- package/dist/chunk-I6BZVIRH.js.map +0 -1
- package/dist/chunk-ISP6ZH3G.js.map +0 -1
- package/dist/chunk-LRYY3OX7.js.map +0 -1
- package/dist/chunk-MT6ZTQGD.js.map +0 -1
- package/dist/chunk-VDYEVCQQ.js.map +0 -1
- package/dist/chunk-ZLX4BA27.js.map +0 -1
- /package/dist/{chunk-Z4RD5UF7.js.map → chunk-2PCNHHN2.js.map} +0 -0
- /package/dist/{chunk-NUWSPR5O.js.map → chunk-G3LZITCA.js.map} +0 -0
- /package/dist/{chunk-IX6UVHXY.js.map → chunk-JKECSYDB.js.map} +0 -0
- /package/dist/{chunk-5GSZGTPJ.js.map → chunk-KA6LD4OI.js.map} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/journeys/journey.ts","../../src/journeys/artifacts.ts","../../src/journeys/page-reading.ts","../../src/journeys/send.ts"],"sourcesContent":["/**\n * One recorded journey through a running agent app: signed-in recorded\n * contexts, chapters, a person's pacing, desktop and phone screenshots,\n * measured chat turns, and a `finish()` that turns the recording into files\n * that are safe to copy off the host.\n *\n * const j = await startJourney('core-path') // reads journeys.config.mjs\n * const page = await j.open('founder', 'member') // recorded, already signed in\n * await j.step('Founder opens the workspace', () => page.goto('/app'), page)\n * await j.shot('home', page) // home-desktop.png + home-phone.png\n * const turn = await j.sendNew(page, 'Research …', { from: `/app/${ws}/chat/new` })\n * await j.finish() // mp4s, srt, highlights, scrubbed trace, timings\n *\n * Output, all safe to copy (finish() refuses otherwise):\n * <outDir>/<id>/video/<label>-full.mp4 <label>-highlights.mp4 <label>.srt <label>-trace.zip\n * <outDir>/<id>/<name>-desktop.png <name>-phone.png timings.json chapters.json turns/*.md\n * Raw webm and unscrubbed traces stay in <stateDir>/raw on the host.\n */\nimport { mkdirSync, writeFileSync } from 'node:fs'\nimport { hostname } from 'node:os'\nimport { join } from 'node:path'\nimport type { Browser, BrowserContext, Locator, Page } from 'playwright'\nimport { pruneJourneyArtifacts } from './artifacts.js'\nimport { loadJourneysConfig, resolveJourneysConfig, threadRouteIn, type JourneysConfig, type ResolvedJourneysConfig, type ThreadRoute } from './config.js'\nimport { promptHead, readChatPage } from './page-reading.js'\nimport { scoreTurn, turnLooksActive, TurnEvidence, type TranscriptSnapshot, type TurnOutcome } from './score.js'\nimport { assertNoSecrets, scrubTrace } from './scrub.js'\nimport { clickUntilSubmitted, composerText, createSubmissionTracker, settleText } from './send.js'\nimport { secretNeedles, storageStateFor } from './session.js'\nimport { postProcessVideo, type Chapter } from './video.js'\n\nexport const DESKTOP = { width: 1440, height: 900 }\nexport const PHONE = { width: 390, height: 844 }\nconst sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms))\nconst secs = (ms: number) => Math.round(ms / 100) / 10\n\n/** A visible pointer so a viewer can follow clicks in a headless recording. Hidden for screenshots. */\nconst CURSOR_SCRIPT = `(() => {\n const install = () => {\n if (document.getElementById('__journey_cursor') || !document.body) return\n const dot = document.createElement('div')\n dot.id = '__journey_cursor'\n dot.setAttribute('aria-hidden', 'true')\n Object.assign(dot.style, { position: 'fixed', zIndex: '2147483647', width: '24px', height: '24px',\n margin: '-12px 0 0 -12px', borderRadius: '50%', background: 'rgba(255,72,48,.28)',\n border: '2px solid rgba(255,72,48,.95)', pointerEvents: 'none', left: (window.__jx ?? -100) + 'px',\n top: (window.__jy ?? -100) + 'px', transition: 'transform .12s ease-out' })\n document.body.appendChild(dot)\n }\n addEventListener('mousemove', (e) => { window.__jx = e.clientX; window.__jy = e.clientY\n const d = document.getElementById('__journey_cursor'); if (d) { d.style.left = e.clientX + 'px'; d.style.top = e.clientY + 'px' } }, true)\n addEventListener('mousedown', () => { const d = document.getElementById('__journey_cursor'); if (d) d.style.transform = 'scale(.55)' }, true)\n addEventListener('mouseup', () => { const d = document.getElementById('__journey_cursor'); if (d) d.style.transform = 'scale(1)' }, true)\n // After hydration, so the framework never meets a node it did not render.\n addEventListener('load', () => setTimeout(install, 1500))\n setInterval(install, 2000)\n})()`\n\ninterface Recorded {\n label: string\n identity: string\n context: BrowserContext\n page: Page\n t0: number\n rawDir: string\n}\n\nexport interface TurnRecord {\n label: string\n prompt: string\n threadId: string | null\n sentAt: string\n /** Seconds from the Send press. */\n firstProgressS: number | null\n firstProgressText: string | null\n firstTextS: number | null\n /** Seconds from Send to the first failure evidence on the page, if any appeared. */\n firstFailureS: number | null\n completeS: number | null\n outcome: TurnOutcome\n /** Plain words for what went wrong, or null for a completed turn. */\n error: string | null\n /** Every piece of failure evidence the turn added. */\n failures: string[]\n /** Where evidence was read: after the turn's own prompt, or the whole transcript when the page did not show the prompt. */\n evidenceScope: 'after-prompt' | 'whole-transcript' | null\n replyChars: number\n /** Distinct status lines the transcript showed, with when they appeared. */\n stages: { s: number; text: string }[]\n /** Seconds from Send at which the journey pressed Stop, if it did. */\n stopPressedS: number | null\n replyFile: string | null\n}\n\nexport interface StepRecord {\n caption: string\n label: string | null\n startS: number\n durationS: number\n ok: boolean\n error?: string\n}\n\nexport interface SendOptions {\n caption?: string\n timeoutMs?: number\n /** Keystroke delay for the prompt. */\n delay?: number\n /** Press Stop at first text, or this many seconds after Send. */\n stopAfter?: 'first-text' | number\n}\n\n/** What the page shows right now, read in one evaluate. */\ninterface PageReading extends TranscriptSnapshot {\n status: string[]\n assistantChars: number\n transcriptChars: number\n stopVisible: boolean\n}\n\nexport class Journey {\n readonly outDir: string\n readonly rawDir: string\n readonly chapters: Chapter[] = []\n readonly steps: StepRecord[] = []\n readonly turns: TurnRecord[] = []\n private recorded: Recorded[] = []\n private phones = new Map<string, BrowserContext>()\n private screenshots = new Set<string>()\n private readonly startedAt = Date.now()\n\n constructor(readonly id: string, readonly config: ResolvedJourneysConfig, readonly browser: Browser, private readonly opts: { cursor: boolean }) {\n this.outDir = join(config.outDir, id)\n this.rawDir = join(config.stateDir, 'raw', `${id}-${new Date().toISOString().replace(/[:.]/g, '-')}`)\n mkdirSync(join(this.outDir, 'video'), { recursive: true })\n mkdirSync(join(this.outDir, 'turns'), { recursive: true })\n mkdirSync(this.rawDir, { recursive: true, mode: 0o700 })\n }\n\n /**\n * A recorded, traced 1440x900 context. A config identity starts signed in\n * from the cached session (no login form is ever recorded); `'anon'` starts\n * signed out, for public pages. Open at most two per journey.\n */\n async open(label: string, identity: string, opts: { fresh?: boolean } = {}): Promise<Page> {\n if (this.recorded.some((r) => r.label === label)) throw new Error(`a context labelled ${label} is already open`)\n if (!/^[a-z0-9][a-z0-9-]{0,30}$/.test(label)) throw new Error('context label: lowercase letters, digits and dashes')\n const storageState = identity === 'anon' ? undefined : (await storageStateFor(this.config, identity, opts)).path\n const rawDir = join(this.rawDir, label)\n const context = await this.browser.newContext({\n baseURL: this.config.baseUrl,\n storageState,\n viewport: DESKTOP,\n recordVideo: { dir: rawDir, size: DESKTOP },\n locale: 'en-US',\n timezoneId: 'America/Denver',\n })\n context.setDefaultTimeout(20_000)\n context.setDefaultNavigationTimeout(60_000)\n if (this.opts.cursor) await context.addInitScript(CURSOR_SCRIPT)\n if (process.env.JOURNEY_DEBUG_CLOCK === '1') {\n // Wall-clock seconds since recording start on every frame, for calibrating captions.\n await context.addInitScript((t0: number) => {\n setInterval(() => {\n let d = document.getElementById('__journey_clock')\n if (!d && document.body) {\n d = document.createElement('div')\n d.id = '__journey_clock'\n Object.assign(d.style, { position: 'fixed', left: '50%', top: '0', zIndex: '2147483647', font: 'bold 20px monospace', background: '#ff0', color: '#000', padding: '2px 6px', pointerEvents: 'none' })\n document.body.appendChild(d)\n }\n if (d) d.textContent = ((Date.now() - t0) / 1000).toFixed(1)\n }, 100)\n }, Date.now())\n }\n await context.tracing.start({ screenshots: true, snapshots: true, title: `${this.id} ${label}` })\n const page = await context.newPage()\n this.recorded.push({ label, identity, context, page, t0: Date.now(), rawDir })\n return page\n }\n\n private recordedFor(page?: Page): Recorded {\n const r = page ? this.recorded.find((x) => x.page === page) : this.recorded[0]\n if (!r) throw new Error('no recorded context for that page; call open() first')\n return r\n }\n\n /** A chapter at this instant: one plain line, shown in the caption bar and the .srt. */\n mark(caption: string, page?: Page): void {\n const label = page ? this.recordedFor(page).label : null\n this.chapters.push({ at: Date.now(), caption, label, kind: 'step' })\n console.log(`[${secs(Date.now() - this.startedAt).toFixed(1)}s] ${label ? `${label}: ` : ''}${caption}`)\n }\n\n /** A timed step with its own chapter. A failure is recorded, captioned, then rethrown. */\n async step<T>(caption: string, work: () => Promise<T>, page?: Page): Promise<T> {\n this.mark(caption, page)\n const start = Date.now()\n const entry: StepRecord = { caption, label: page ? this.recordedFor(page).label : null, startS: secs(start - this.startedAt), durationS: 0, ok: true }\n this.steps.push(entry)\n try {\n return await work()\n } catch (error) {\n entry.ok = false\n entry.error = String((error as Error)?.message ?? error).slice(0, 400)\n this.mark(`Step failed: ${caption}`, page)\n throw error\n } finally {\n entry.durationS = secs(Date.now() - start)\n }\n }\n\n /** A waiting span: real speed in the full video, sped up and labelled in the highlights. */\n async wait<T>(caption: string, work: () => Promise<T>, page?: Page): Promise<T> {\n const label = page ? this.recordedFor(page).label : null\n const chapter: Chapter = { at: Date.now(), caption, label, kind: 'wait', until: Date.now() }\n this.chapters.push(chapter)\n console.log(`[${secs(Date.now() - this.startedAt).toFixed(1)}s] ${label ? `${label}: ` : ''}(wait) ${caption}`)\n try {\n return await work()\n } finally {\n chapter.until = Date.now()\n }\n }\n\n pause(ms = 700): Promise<void> {\n return sleep(ms)\n }\n\n /** Move the visible pointer there, pause, click, pause. */\n async click(target: Locator, opts: { pauseAfter?: number } = {}): Promise<void> {\n await target.scrollIntoViewIfNeeded()\n const box = await target.boundingBox()\n if (box) await target.page().mouse.move(box.x + box.width / 2, box.y + box.height / 2, { steps: 14 })\n await sleep(250)\n await target.click()\n await sleep(opts.pauseAfter ?? 600)\n }\n\n /** Type at a readable pace into an input or textarea. */\n async type(target: Locator, text: string, opts: { delay?: number } = {}): Promise<void> {\n await this.click(target, { pauseAfter: 200 })\n const delay = opts.delay ?? 28\n await target.pressSequentially(text, { delay, timeout: 30_000 + text.length * (delay + 60) })\n await sleep(400)\n }\n\n /** The composer's message input. */\n composerInput(page: Page): Locator {\n return page.locator(this.config.chat.composer).getByRole('textbox', { name: this.config.chat.inputName })\n }\n\n private composerButton(page: Page, name: string): Locator {\n return page.locator(this.config.chat.composer).getByRole('button', { name, exact: true })\n }\n\n /**\n * Type into the chat composer at a readable pace. A line break is typed as\n * Shift+Enter, because Enter sends. Retries fast when hydration dropped\n * keystrokes. Never `fill()` a rich-text composer.\n */\n async typePrompt(page: Page, prompt: string, opts: { delay?: number } = {}): Promise<void> {\n const box = this.composerInput(page)\n await box.waitFor({ state: 'visible', timeout: 30_000 })\n await sleep(1_200)\n const delay = opts.delay ?? (prompt.length > 400 ? 8 : 22)\n const want = prompt.replace(/\\s+/g, ' ').trim().slice(0, 80)\n for (let attempt = 0; attempt < 4; attempt += 1) {\n await this.click(box, { pauseAfter: 150 })\n await box.press('ControlOrMeta+a')\n await box.press('Backspace')\n const lines = prompt.split('\\n')\n for (let i = 0; i < lines.length; i += 1) {\n if (i > 0) await box.press('Shift+Enter')\n // Sized by length: a loaded host types slower than the context's 20 s default allows.\n const line = lines[i]!\n if (line) await box.pressSequentially(line, { delay: attempt === 0 ? delay : 0, timeout: 30_000 + line.length * (delay + 60) })\n }\n const text = (await composerText(box).catch(() => '')).replace(/\\s+/g, ' ').trim()\n if (text.includes(want)) return\n await sleep(1_000)\n }\n throw new Error('the composer never held the prompt')\n }\n\n /**\n * Which parts of the chat contract this page shows, without sending\n * anything. Run it on a second app before trusting turn timings there.\n */\n async checkChatContract(page: Page): Promise<Record<'transcript' | 'composer' | 'input' | 'send', boolean>> {\n const visible = (l: Locator) => l.first().isVisible().catch(() => false)\n return {\n transcript: await visible(page.locator(this.config.chat.transcript)),\n composer: await visible(page.locator(this.config.chat.composer)),\n input: await visible(this.composerInput(page)),\n send: await visible(this.composerButton(page, this.config.chat.sendName)),\n }\n }\n\n /**\n * Desktop screenshot of the recorded page, then the same URL in a phone\n * context (390x844, same identity). Look at both before judging the screen.\n */\n async shot(name: string, page?: Page, opts: { phone?: boolean; fullPage?: boolean; phoneUrl?: string } = {}): Promise<{ desktop: string; phone?: string }> {\n const r = this.recordedFor(page)\n const slug = name.replace(/[^a-z0-9-]+/gi, '-').toLowerCase()\n const desktop = join(this.outDir, `${slug}-desktop.png`)\n const cursor = (display: string) => r.page.evaluate((d) => { const c = document.getElementById('__journey_cursor'); if (c) c.style.display = d }, display).catch(() => {})\n await cursor('none')\n await r.page.screenshot({ path: desktop, fullPage: opts.fullPage ?? false })\n this.screenshots.add(desktop)\n await cursor('')\n if (opts.phone === false) return { desktop }\n const phonePath = join(this.outDir, `${slug}-phone.png`)\n let ctx = this.phones.get(r.identity)\n if (!ctx) {\n const storageState = r.identity === 'anon' ? undefined : (await storageStateFor(this.config, r.identity)).path\n ctx = await this.browser.newContext({ baseURL: this.config.baseUrl, storageState, viewport: PHONE, deviceScaleFactor: 2, isMobile: true, hasTouch: true, locale: 'en-US', timezoneId: 'America/Denver' })\n this.phones.set(r.identity, ctx)\n }\n const phone = await ctx.newPage()\n try {\n await phone.goto(opts.phoneUrl ?? r.page.url(), { waitUntil: 'load' })\n await phone.waitForLoadState('networkidle', { timeout: 8_000 }).catch(() => {})\n await sleep(1_500)\n await phone.screenshot({ path: phonePath, fullPage: opts.fullPage ?? false })\n this.screenshots.add(phonePath)\n } finally {\n await phone.close()\n }\n return { desktop, phone: phonePath }\n }\n\n private budgetTurn(): void {\n if (this.turns.length >= this.config.maxTurns) {\n throw new Error(`this journey already sent ${this.turns.length} chat turns, its budget (maxTurns ${this.config.maxTurns})`)\n }\n }\n\n /**\n * Start a new thread: open `from` when given, type the prompt, press Send\n * like a person (again only while the page has not submitted; never deletes\n * a duplicate), wait for the thread, then measure the turn.\n */\n async sendNew(page: Page, prompt: string, opts: SendOptions & { from?: string } = {}): Promise<TurnRecord> {\n this.budgetTurn()\n if (opts.from && !page.url().startsWith(new URL(opts.from, this.config.baseUrl).href)) await page.goto(opts.from)\n await this.typePrompt(page, prompt, { delay: opts.delay })\n const send = this.composerButton(page, this.config.chat.sendName)\n await send.waitFor({ state: 'visible' })\n const box = await send.boundingBox()\n if (box) await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2, { steps: 14 })\n await sleep(400)\n const before = await this.read(page, prompt)\n const evidence = new TurnEvidence(this.patterns(), prompt)\n evidence.begin(before)\n const tracker = createSubmissionTracker(page.url(), this.config.chat.sendPaths)\n const count = (request: { method(): string; url(): string }) => tracker.observe(request.method(), request.url())\n page.on('request', count)\n this.mark(opts.caption ?? `Sends: \"${oneLine(prompt, 90)}\"`, page)\n const sentAt = Date.now()\n const onThread = () => threadRouteIn(page.url(), this.config) !== null\n try {\n await clickUntilSubmitted({\n landed: () => tracker.count > 0 || onThread(),\n ready: () => send.click({ trial: true, timeout: 5_000 }),\n click: () => send.click({ timeout: 5_000 }),\n wait: () => page.waitForRequest((r) => tracker.matches(r.method(), r.url()), { timeout: 1_000 }).then(() => undefined).catch(() => undefined),\n attempts: 15,\n })\n if (this.config.chat.threadPath) await page.waitForURL((url) => threadRouteIn(url.href, this.config) !== null, { timeout: 45_000 })\n } catch (error) {\n return this.notSent(page, prompt, sentAt, String((error as Error).message).slice(0, 300))\n } finally {\n page.off('request', count)\n }\n if (tracker.count > 1) console.warn(`the composer submitted ${tracker.count} times; a duplicate thread may exist (left in place)`)\n return this.measureTurn(page, prompt, sentAt, evidence, before, 0, opts)\n }\n\n /** A follow-up in the open thread: type, one Send press, measure. */\n async sendInThread(page: Page, prompt: string, opts: SendOptions = {}): Promise<TurnRecord> {\n this.budgetTurn()\n await this.typePrompt(page, prompt, { delay: opts.delay })\n const send = this.composerButton(page, this.config.chat.sendName)\n const before = await this.read(page, prompt)\n const evidence = new TurnEvidence(this.patterns(), prompt)\n evidence.begin(before)\n const tracker = createSubmissionTracker(page.url(), this.config.chat.sendPaths)\n const posted = page.waitForRequest((r) => tracker.matches(r.method(), r.url()), { timeout: 30_000 })\n this.mark(opts.caption ?? `Follows up: \"${oneLine(prompt, 90)}\"`, page)\n const sentAt = Date.now()\n await this.click(send, { pauseAfter: 0 })\n const sent = await posted.then(() => true).catch(() => false)\n if (!sent) return this.notSent(page, prompt, sentAt, 'no chat request within 30 s of pressing Send')\n return this.measureTurn(page, prompt, sentAt, evidence, before, Math.max(0, before.assistantChars), opts)\n }\n\n private patterns() {\n return { failure: this.config.chat.failureText, stopped: this.config.chat.stoppedText }\n }\n\n private blankTurn(page: Page, prompt: string, sentAt: number): TurnRecord {\n return {\n label: this.recordedFor(page).label, prompt, threadId: threadRouteIn(page.url(), this.config)?.threadId ?? null,\n sentAt: new Date(sentAt).toISOString(), firstProgressS: null, firstProgressText: null, firstTextS: null, firstFailureS: null, completeS: null,\n outcome: 'timeout', error: null, failures: [], evidenceScope: null, replyChars: 0, stages: [], stopPressedS: null, replyFile: null,\n }\n }\n\n private notSent(page: Page, prompt: string, sentAt: number, why: string): TurnRecord {\n const t = { ...this.blankTurn(page, prompt, sentAt), ...scoreTurn({ notSent: why, timedOut: false, evidence: { failures: [], stopped: [], retryAppeared: false }, replyChars: 0, stopPressed: false }) }\n this.turns.push(t)\n this.mark(`Turn not sent: ${oneLine(why, 90)}`, page)\n return t\n }\n\n /** One read of the transcript, composer and failure marks; with a prompt, the evidence that follows it. */\n private async read(page: Page, prompt: string | null = null): Promise<PageReading> {\n const c = this.config.chat\n const { assistant, ...reading } = await page.evaluate(readChatPage, {\n transcript: c.transcript, status: c.status, failureNodes: c.failureNodes, retrySource: c.retryName.source, retryFlags: c.retryName.flags,\n assistant: c.assistant, composer: c.composer, stopName: c.stopName, promptHead: prompt === null ? null : promptHead(prompt),\n })\n return { ...reading, assistantChars: assistant }\n }\n\n private async runningTurns(page: Page, route: ThreadRoute | null): Promise<string[] | null> {\n if (!route || !this.config.chat.runningTurns) return null\n const res = await page.request.get(this.config.chat.runningTurns(route))\n if (!res.ok()) throw new Error(`running turns answered ${res.status()}`)\n const body = (await res.json()) as { running?: unknown }\n if (!Array.isArray(body.running)) throw new Error('running turns returned no `running` array')\n return body.running.map(String)\n }\n\n /**\n * Time to first visible progress (a new status line or reply text), first\n * reply text, and the turn's end, polled every 300 ms. Failure evidence is\n * read after the turn's own prompt when the page shows it. The turn has ended\n * when, for two reads in a row, {@link turnLooksActive} is false and, where\n * the app lists running turns, the server lists none. Status lines already\n * on the page before Send are not progress. The outcome comes from\n * {@link scoreTurn}.\n */\n private async measureTurn(page: Page, prompt: string, sentAt: number, evidence: TurnEvidence, before: PageReading, baselineChars: number, opts: SendOptions): Promise<TurnRecord> {\n const t = this.blankTurn(page, prompt, sentAt)\n this.turns.push(t)\n const route = threadRouteIn(page.url(), this.config)\n t.threadId = route?.threadId ?? null\n const timeoutMs = opts.timeoutMs ?? 15 * 60_000\n const since = () => secs(Date.now() - sentAt)\n const standingStatus = new Set(before.status)\n // Without an assistant selector, reply text is transcript growth from the\n // first read after Send (the person's own message is on the page by then).\n let growthBase: number | null = null\n let growth = 0\n let sawActive = false\n let quiet = 0\n let lastServerCheck = 0\n let serverRunning: string[] | null = null\n let lastStage = ''\n let lastStatus = ''\n let statusChangedAt = Date.now()\n let finished = false\n await this.wait('Waiting for the agent', async () => {\n while (Date.now() - sentAt < timeoutMs) {\n const s = await this.read(page, prompt).catch(() => null)\n if (s) {\n t.evidenceScope = s.anchored ? 'after-prompt' : 'whole-transcript'\n const shown = evidence.observe(s)\n if (shown.length) {\n t.firstFailureS ??= since()\n this.mark(`Failure shown after ${since()} s: ${oneLine(shown[0]!, 90)}`, page)\n }\n const status = s.status.filter((line) => !standingStatus.has(line))\n growthBase ??= s.transcriptChars\n const chars = s.assistantChars >= 0 ? s.assistantChars - baselineChars : s.transcriptChars - growthBase - status.join(' ').length\n growth = Math.max(growth, chars)\n const stage = status.join(' | ').replace(/\\b\\d+(\\.\\d+)?\\s?s\\b/g, '').trim()\n if (stage && stage !== lastStage) {\n t.stages.push({ s: since(), text: status.join(' | ').slice(0, 160) })\n lastStage = stage\n }\n // Raw text, timers included: a ticking \"Preparing your workspace… 31s\" is changing.\n if (status.join(' | ') !== lastStatus) {\n lastStatus = status.join(' | ')\n statusChangedAt = Date.now()\n }\n if (t.firstProgressS === null && (status.length || chars > 0)) {\n t.firstProgressS = since()\n t.firstProgressText = status[0] ?? 'reply text'\n this.mark(`First visible progress after ${t.firstProgressS} s: ${oneLine(t.firstProgressText, 70)}`, page)\n }\n if (t.firstTextS === null && chars > 0) {\n t.firstTextS = since()\n this.mark(`First text after ${t.firstTextS} s`, page)\n }\n const stopDue = opts.stopAfter === 'first-text' ? t.firstTextS !== null : typeof opts.stopAfter === 'number' && since() >= opts.stopAfter\n if (t.stopPressedS === null && stopDue && s.stopVisible) {\n t.stopPressedS = since()\n this.mark(`Presses Stop after ${t.stopPressedS} s`, page)\n await this.click(this.composerButton(page, this.config.chat.stopName), { pauseAfter: 200 }).catch((e) => console.warn(`Stop press failed: ${e}`))\n }\n if (status.length > 0) sawActive = true\n const active = turnLooksActive({ stopVisible: s.stopVisible, statusLines: status.length, msSinceStatusChanged: Date.now() - statusChangedAt })\n quiet = active ? 0 : quiet + 1\n }\n if (route && this.config.chat.runningTurns && Date.now() - lastServerCheck > 2_000) {\n lastServerCheck = Date.now()\n // A failed read never implies the turn ended.\n serverRunning = await this.runningTurns(page, route).catch(() => serverRunning)\n if (serverRunning?.length) sawActive = true\n }\n const started = sawActive || t.firstTextS !== null || Date.now() - sentAt > 45_000\n const serverDone = !this.config.chat.runningTurns || !route || serverRunning?.length === 0\n if (started && quiet >= 2 && serverDone) {\n finished = true\n return\n }\n await sleep(300)\n }\n }, page)\n t.completeS = finished ? since() : null\n // Render lag only: the turn has ended, so wait for the transcript to stop changing before judging it.\n await settleText(() => this.read(page, prompt).then((r) => `${r.transcriptChars}:${r.failureNodes.length}:${r.retryButtons}`))\n const last = await this.read(page, prompt)\n t.evidenceScope = last.anchored ? 'after-prompt' : 'whole-transcript'\n evidence.observe(last)\n const finalText = this.config.chat.assistant ? await this.replyText(page) : ''\n t.replyChars = this.config.chat.assistant ? Math.max(0, finalText.length - baselineChars) : Math.max(0, growth)\n Object.assign(t, scoreTurn({ timedOut: !finished, evidence: evidence.added(), replyChars: t.replyChars, stopPressed: t.stopPressedS !== null }))\n const n = this.turns.length\n t.replyFile = join('turns', `${String(n).padStart(2, '0')}-${t.label}.md`)\n const reply = this.config.chat.assistant ? finalText.slice(baselineChars).trim() : '(this app configures no assistant selector; read the reply in the video or the trace)'\n const failures = t.failures.length ? `\\n\\n## Failure evidence\\n\\n${t.failures.map((f) => `- ${f}`).join('\\n')}` : ''\n writeFileSync(join(this.outDir, t.replyFile), `# Turn ${n} (${t.label})\\n\\n## Prompt\\n\\n${prompt}\\n\\n## Reply (${t.outcome})\\n\\n${reply}${failures}\\n`)\n this.mark(\n t.outcome === 'completed'\n ? `Turn complete after ${t.completeS} s (${t.replyChars} chars)`\n : `Turn ${t.outcome.toUpperCase()} after ${t.completeS ?? since()} s${t.error ? `: ${oneLine(t.error, 80)}` : ''}`,\n page,\n )\n return t\n }\n\n private async replyText(page: Page): Promise<string> {\n const sel = this.config.chat.assistant\n if (!sel) return ''\n return settleText(async () => (await page.locator(sel).allInnerTexts()).join('\\n').trim())\n }\n\n /**\n * Close everything, then per context: a captioned full .mp4, a highlights cut\n * (at most 178 s, long waits sped up and labelled), an .srt and a scrubbed\n * trace.zip; plus timings.json and chapters.json. Refuses (throws) when any\n * output file still holds a password or cookie value.\n */\n async finish(opts: { speedup2x?: boolean } = {}): Promise<{ outDir: string; files: string[] }> {\n for (const ctx of this.phones.values()) await ctx.close().catch(() => {})\n const files: string[] = []\n // Stop every recording first, so one context's video does not run on through another's processing.\n const stopped: { r: Recorded; rawTrace: string; webm: string | null; endedAt: number }[] = []\n for (const r of this.recorded) {\n const endedAt = Date.now()\n const rawTrace = join(r.rawDir, 'trace.raw.zip')\n await r.context.tracing.stop({ path: rawTrace }).catch((e) => console.warn(`tracing.stop failed for ${r.label}: ${e}`))\n const video = r.page.video()\n await r.context.close()\n stopped.push({ r, rawTrace, webm: video ? await video.path().catch(() => null) : null, endedAt })\n }\n const needles = secretNeedles(this.config)\n for (const { r, rawTrace, webm, endedAt } of stopped) {\n if (webm) {\n files.push(...postProcessVideo({\n webm, workDir: r.rawDir, videoDir: join(this.outDir, 'video'), label: r.label, t0: r.t0,\n wallSeconds: (endedAt - r.t0) / 1000, chapters: this.chapters.filter((c) => c.label === null || c.label === r.label),\n speedup2x: opts.speedup2x ?? false,\n }))\n }\n try {\n const clean = join(this.outDir, 'video', `${r.label}-trace.zip`)\n const result = scrubTrace(rawTrace, clean, [...needles.hard, ...needles.soft])\n console.log(`trace ${r.label}: ${result.entries} entries, ${result.dropped} sensitive bodies dropped, ${result.rewritten} rewritten`)\n files.push(clean)\n } catch (error) {\n console.warn(`trace ${r.label} not written: ${(error as Error).message}`)\n }\n }\n writeFileSync(join(this.outDir, 'chapters.json'), JSON.stringify(this.chapters.map((c) => ({ ...c, at: new Date(c.at).toISOString(), until: c.until ? new Date(c.until).toISOString() : undefined, offsetS: secs(c.at - this.startedAt) })), null, 2))\n writeFileSync(join(this.outDir, 'timings.json'), JSON.stringify({ journey: this.id, app: this.config.app, base: this.config.baseUrl, startedAt: new Date(this.startedAt).toISOString(), wallS: secs(Date.now() - this.startedAt), steps: this.steps, turns: this.turns }, null, 2))\n await this.browser.close()\n assertNoSecrets(this.outDir, needles)\n pruneJourneyArtifacts(this.outDir, new Set([\n ...files,\n ...this.screenshots,\n ...this.turns.flatMap((turn) => turn.replyFile ? [join(this.outDir, turn.replyFile)] : []),\n ]))\n console.log(`\\n${this.id}: ${this.steps.length} steps, ${this.turns.length} turns, wall ${secs(Date.now() - this.startedAt)} s`)\n for (const t of this.turns) {\n console.log(` turn[${t.label}] ${t.outcome}: progress ${t.firstProgressS ?? '-'} s, first text ${t.firstTextS ?? '-'} s, end ${t.completeS ?? '-'} s, ${t.replyChars} chars${t.error ? ` | ${oneLine(t.error, 100)}` : ''}`)\n }\n const host = process.env.JOURNEYS_HOST_ALIAS ?? hostname()\n console.log(`output: ${this.outDir}\\ncopy it (run where you will watch it):\\n rsync -a ${host}:${this.outDir}/ \"<dest>/${this.id}/\"`)\n return { outDir: this.outDir, files }\n }\n}\n\nexport function oneLine(text: string, max: number): string {\n const s = text.replace(/\\s+/g, ' ').trim()\n return s.length > max ? `${s.slice(0, max - 1)}…` : s\n}\n\n/** Open a journey. Without `config`, reads `journeys.config.mjs` from the working directory. */\nexport async function startJourney(id: string, opts: { config?: JourneysConfig | ResolvedJourneysConfig; cursor?: boolean; headless?: boolean } = {}): Promise<Journey> {\n if (!/^[a-z0-9][a-z0-9-]{1,60}$/.test(id)) throw new Error('journey id: lowercase letters, digits and dashes')\n const config = opts.config ? resolveJourneysConfig(opts.config) : await loadJourneysConfig()\n let chromium\n try {\n chromium = (await import('playwright')).chromium\n } catch {\n throw new Error('journeys need the optional `playwright` peer: install playwright in the app that runs them')\n }\n const browser = await chromium.launch({ headless: opts.headless ?? true })\n return new Journey(id, config, browser, { cursor: opts.cursor ?? true })\n}\n","import { readdirSync, rmSync } from 'node:fs'\nimport { join, resolve } from 'node:path'\n\nconst groups = [\n {\n directory: '',\n owns: (name: string) => name.endsWith('-desktop.png') || name.endsWith('-phone.png'),\n },\n {\n directory: 'video',\n owns: (name: string) => name.endsWith('.mp4') || name.endsWith('.srt') || name.endsWith('-trace.zip'),\n },\n {\n directory: 'turns',\n owns: (name: string) => name.endsWith('.md'),\n },\n] as const\n\nexport function pruneJourneyArtifacts(outDir: string, retained: ReadonlySet<string>): void {\n const keep = new Set([...retained].map((file) => resolve(file)))\n for (const group of groups) {\n const directory = join(resolve(outDir), group.directory)\n for (const entry of readdirSync(directory, { withFileTypes: true })) {\n if ((!entry.isFile() && !entry.isSymbolicLink()) || !group.owns(entry.name)) continue\n const file = join(directory, entry.name)\n if (!keep.has(file)) rmSync(file)\n }\n }\n}\n","/**\n * The one read of a chat page a journey takes every 300 ms, run inside the page\n * by `page.evaluate`, so it must stay self-contained: DOM globals only, no\n * imports and no module-scope names.\n *\n * Failure evidence belongs to the turn whose prompt it follows. On 2026-10-11\n * GTM showed a live Stop as a grey notice, then, when the next message was\n * sent, re-rendered the stopped turn with its red \"You stopped this turn.\" card\n * and a Retry control, above the new message. Read from the whole transcript,\n * that card failed the follow-up, which had answered in 28.5 s. So when the\n * transcript shows the turn's own prompt, only failure marks, Retry controls\n * and lines after it count; when it does not, the whole transcript does.\n */\n\ninterface PageReadArgs {\n readonly transcript: string\n readonly status: string\n readonly failureNodes: string\n readonly retrySource: string\n readonly retryFlags: string\n readonly assistant: string | null\n readonly composer: string\n readonly stopName: string\n /** The turn's prompt as {@link promptHead} gives it; null reads the whole transcript. */\n readonly promptHead: string | null\n}\n\ninterface RawPageReading {\n /** Visible transcript lines (after the turn's prompt when `anchored`). */\n lines: string[]\n failureNodes: string[]\n retryButtons: number\n status: string[]\n /** Characters of assistant text on the page, or -1 with no assistant selector. */\n assistant: number\n transcriptChars: number\n stopVisible: boolean\n /** The turn's prompt was found, so the evidence fields hold only what follows it. */\n anchored: boolean\n}\n\n/** The text a transcript shows for a prompt: its first line, whitespace squashed, at most 48 characters. */\nexport function promptHead(prompt: string): string | null {\n const first = prompt.split('\\n').map((line) => line.replace(/\\s+/g, ' ').trim()).find(Boolean)\n return first ? first.slice(0, 48) : null\n}\n\nexport function readChatPage(c: PageReadArgs): RawPageReading {\n const squash = (s: string) => s.replace(/\\s+/g, ' ').trim()\n const clean = (e: Element) => squash(e.textContent ?? '')\n const region = document.querySelector<HTMLElement>(c.transcript)\n const composer = document.querySelector<HTMLElement>(c.composer)\n const assistantNodes = c.assistant ? Array.from(document.querySelectorAll<HTMLElement>(c.assistant)) : []\n const within = (sel: string) => (region ? Array.from(region.querySelectorAll(sel)) : [])\n\n // The last text node outside the composer and the assistant's own text that holds the prompt.\n let anchor: Node | null = null\n if (region && c.promptHead) {\n const walker = document.createTreeWalker(region, NodeFilter.SHOW_TEXT)\n for (let node = walker.nextNode(); node; node = walker.nextNode()) {\n if (!squash(node.nodeValue ?? '').includes(c.promptHead)) continue\n if (composer?.contains(node) || assistantNodes.some((a) => a.contains(node))) continue\n anchor = node\n }\n }\n const after = (e: Element) => anchor === null || (anchor.compareDocumentPosition(e) & Node.DOCUMENT_POSITION_FOLLOWING) !== 0\n\n const full = region?.innerText ?? ''\n let text = full\n const composerText = composer && region?.contains(composer) ? composer.innerText.trim() : ''\n if (composerText) {\n const at = text.lastIndexOf(composerText)\n if (at >= 0) text = text.slice(0, at) + text.slice(at + composerText.length)\n }\n let lines = text.split('\\n').map((l) => l.trim()).filter(Boolean)\n if (anchor && c.promptHead) {\n // The same rule for lines: the last one holding the prompt that is not the assistant's.\n const replyLines = new Set(assistantNodes.flatMap((a) => a.innerText.split('\\n').map(squash)))\n let last = -1\n for (let i = 0; i < lines.length; i += 1) {\n const line = squash(lines[i]!)\n if (line.includes(c.promptHead) && !replyLines.has(line)) last = i\n }\n lines = lines.slice(last + 1)\n }\n\n const status = within(c.status).map(clean).filter(Boolean)\n // textContent, not innerText: a failure's collapsed details (the code) count too.\n const failureNodes = within(c.failureNodes).filter(after).map(clean).filter(Boolean)\n const retry = new RegExp(c.retrySource, c.retryFlags)\n const retryButtons = within('button').filter((b) => after(b) && retry.test((b.getAttribute('aria-label') ?? b.textContent ?? '').trim())).length\n const assistant = c.assistant ? assistantNodes.map((e) => e.innerText).join('\\n').trim().length : -1\n const stopVisible = composer !== null && Array.from(composer.querySelectorAll('button')).some((b) =>\n (b.getAttribute('aria-label') ?? b.textContent ?? '').trim() === c.stopName && b.getClientRects().length > 0)\n return { lines, failureNodes, retryButtons, status, assistant, transcriptChars: full.trim().length, stopVisible, anchored: anchor !== null }\n}\n","/**\n * Pressing Send like a person, exactly as often as it takes and never once more.\n *\n * A new-chat composer can drop a press while its model selection is still\n * resolving, and its Send control is not disabled while that gate is shut, so\n * one press can be a silent no-op and a retry is necessary. A retry is also\n * dangerous: the press creates a thread, so a press after the page has already\n * submitted asks for a second one. Pure, so the rule is a unit test.\n */\n\n/** Paths a submission from `routePath` lands on: the route itself and its single-fetch `.data` form. */\nexport function routeSubmitPaths(routePath: string): string[] {\n const singleFetch = routePath.endsWith('/') ? `${routePath}_.data` : `${routePath}.data`\n return [routePath, singleFetch]\n}\n\nexport interface SubmissionTracker {\n /** Whether one request is a submission from the tracked page. */\n matches(method: string, url: string): boolean\n observe(method: string, url: string): void\n /** Submissions seen so far. Above zero means the turn is on its way. */\n readonly count: number\n}\n\n/**\n * Counts submissions from the page at `routeUrl`: a POST to that route (or its\n * `.data` form), or to one of `sendPaths`, on the same origin. A POST to the\n * same path on another origin is not this composer's.\n */\nexport function createSubmissionTracker(routeUrl: string, sendPaths: readonly RegExp[]): SubmissionTracker {\n if (!/^https?:\\/\\//i.test(routeUrl)) throw new Error(`createSubmissionTracker needs the page's full URL, got \"${routeUrl}\"`)\n const route = new URL(routeUrl)\n const exact = new Set(routeSubmitPaths(route.pathname))\n let count = 0\n const matches = (method: string, url: string): boolean => {\n if (method !== 'POST') return false\n let parsed: URL\n try {\n parsed = new URL(url, route.origin)\n } catch {\n return false\n }\n if (parsed.origin !== route.origin) return false\n return exact.has(parsed.pathname) || sendPaths.some((p) => p.test(parsed.pathname))\n }\n return {\n matches,\n observe(method, url) {\n if (matches(method, url)) count += 1\n },\n get count() {\n return count\n },\n }\n}\n\nexport interface SendDriveOps {\n /** True once a submission, or the navigation it causes, has been observed. */\n landed: () => boolean\n /** Wait until Send can take a press, without pressing it. */\n ready: () => Promise<void>\n click: () => Promise<void>\n /** Pause between presses, spent watching for the submission. */\n wait: () => Promise<void>\n attempts: number\n}\n\n/**\n * Press until the page submits. Each attempt waits for the control first and\n * takes its last look at `landed()` after that wait, so the press itself is the\n * only unguarded moment. A click failure is tolerated only once something has\n * landed: an accepted send tears the composer down mid-press.\n */\nexport async function clickUntilSubmitted(ops: SendDriveOps): Promise<void> {\n for (let attempt = 0; attempt < ops.attempts; attempt += 1) {\n if (ops.landed()) return\n try {\n await ops.ready()\n if (ops.landed()) return\n await ops.click()\n } catch (cause) {\n if (!ops.landed()) throw cause\n }\n if (ops.landed()) return\n await ops.wait()\n }\n if (ops.landed()) return\n throw new Error(`Send never submitted: the composer refused ${ops.attempts} presses`)\n}\n\n/**\n * Read until the value stops changing: six identical reads 500 ms apart. Every\n * caller has already seen the turn finish, so this covers render lag only.\n */\nexport async function settleText(\n read: () => Promise<string>,\n wait: (ms: number) => Promise<void> = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),\n timeoutMs = 20_000,\n): Promise<string> {\n const deadline = Date.now() + timeoutMs\n let previous: string | null = null\n let stable = 0\n for (;;) {\n const current = await read().catch(() => null)\n if (current === null) {\n stable = 0\n } else {\n stable = current === previous ? stable + 1 : 1\n previous = current\n if (stable >= 6) return current\n }\n if (Date.now() >= deadline) return previous ?? ''\n await wait(500)\n }\n}\n\n/**\n * The text a composer holds. A `<textarea>` or `<input>` (agent-app's own\n * ChatComposer) keeps typed text in `.value` and leaves `innerText` empty; a\n * contenteditable composer keeps it in `innerText`. Reading only `innerText`\n * failed every first chat turn on the default composer (Casework C1/C5,\n * 2026-10-12).\n */\nexport async function composerText(box: { evaluate<R>(fn: (el: Element) => R): Promise<R> }): Promise<string> {\n return box.evaluate((el) => {\n const field = el as Element & { value?: unknown; innerText?: string }\n return typeof field.value === 'string' ? field.value : (field.innerText ?? el.textContent ?? '')\n })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AS,sBAAsB,KAAK,MAAM,IAAI,MAAM,mBAAmB;AAC3F,MAAI;AACJ,MAAI;AACF,gBAAY,MAAM,OAAO,YAAY,GAAG;AAAA,EAC1C,QAAQ;AACN,UAAM,IAAI,MAAM,4FAA4F;AAAA,EAC9G;AACA,QAAM,UAAU,MAAM,SAAS,OAAO,EAAE,UAAU,KAAK,YAAY,KAAK,CAAC;AACzE,SAAO,IAAI,QAAQ,IAAI,QAAQ,SAAS,EAAE,QAAQ,KAAK,UAAU,KAAK,CAAC;AACzE;","names":["join","composerText","resolve","resolve","join"]}
|
|
1
|
+
{"version":3,"sources":["../../src/journeys/journey.ts","../../src/journeys/artifacts.ts","../../src/journeys/page-reading.ts","../../src/journeys/send.ts"],"sourcesContent":["/**\n * One recorded journey through a running agent app: signed-in recorded\n * contexts, chapters, a person's pacing, desktop and phone screenshots,\n * measured chat turns, and a `finish()` that turns the recording into files\n * that are safe to copy off the host.\n *\n * const j = await startJourney('core-path') // reads journeys.config.mjs\n * const page = await j.open('founder', 'member') // recorded, already signed in\n * await j.step('Founder opens the workspace', () => page.goto('/app'), page)\n * await j.shot('home', page) // home-desktop.png + home-phone.png\n * const turn = await j.sendNew(page, 'Research …', { from: `/app/${ws}/chat/new` })\n * await j.finish() // mp4s, srt, highlights, scrubbed trace, timings\n *\n * Output, all safe to copy (finish() refuses otherwise):\n * <outDir>/<id>/video/<label>-full.mp4 <label>-highlights.mp4 <label>.srt <label>-trace.zip\n * <outDir>/<id>/<name>-desktop.png <name>-phone.png timings.json chapters.json turns/*.md\n * Raw webm and unscrubbed traces stay in <stateDir>/raw on the host.\n */\nimport { mkdirSync, writeFileSync } from 'node:fs'\nimport { hostname } from 'node:os'\nimport { join } from 'node:path'\nimport type { Browser, BrowserContext, Locator, Page } from 'playwright'\nimport { pruneJourneyArtifacts } from './artifacts.js'\nimport { loadJourneysConfig, resolveJourneysConfig, threadRouteIn, type JourneysConfig, type ResolvedJourneysConfig, type ThreadRoute } from './config.js'\nimport { promptHead, readChatPage } from './page-reading.js'\nimport { scoreTurn, turnLooksActive, TurnEvidence, type TranscriptSnapshot, type TurnOutcome } from './score.js'\nimport { assertNoSecrets, scrubTrace } from './scrub.js'\nimport { clickUntilSubmitted, composerText, createSubmissionTracker, settleText } from './send.js'\nimport { secretNeedles, storageStateFor } from './session.js'\nimport { postProcessVideo, type Chapter } from './video.js'\n\nexport const DESKTOP = { width: 1440, height: 900 }\nexport const PHONE = { width: 390, height: 844 }\nconst sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms))\nconst secs = (ms: number) => Math.round(ms / 100) / 10\n\n/** A visible pointer so a viewer can follow clicks in a headless recording. Hidden for screenshots. */\nconst CURSOR_SCRIPT = `(() => {\n const install = () => {\n if (document.getElementById('__journey_cursor') || !document.body) return\n const dot = document.createElement('div')\n dot.id = '__journey_cursor'\n dot.setAttribute('aria-hidden', 'true')\n Object.assign(dot.style, { position: 'fixed', zIndex: '2147483647', width: '24px', height: '24px',\n margin: '-12px 0 0 -12px', borderRadius: '50%', background: 'rgba(255,72,48,.28)',\n border: '2px solid rgba(255,72,48,.95)', pointerEvents: 'none', left: (window.__jx ?? -100) + 'px',\n top: (window.__jy ?? -100) + 'px', transition: 'transform .12s ease-out' })\n document.body.appendChild(dot)\n }\n addEventListener('mousemove', (e) => { window.__jx = e.clientX; window.__jy = e.clientY\n const d = document.getElementById('__journey_cursor'); if (d) { d.style.left = e.clientX + 'px'; d.style.top = e.clientY + 'px' } }, true)\n addEventListener('mousedown', () => { const d = document.getElementById('__journey_cursor'); if (d) d.style.transform = 'scale(.55)' }, true)\n addEventListener('mouseup', () => { const d = document.getElementById('__journey_cursor'); if (d) d.style.transform = 'scale(1)' }, true)\n // After hydration, so the framework never meets a node it did not render.\n addEventListener('load', () => setTimeout(install, 1500))\n setInterval(install, 2000)\n})()`\n\ninterface Recorded {\n label: string\n identity: string\n context: BrowserContext\n page: Page\n t0: number\n rawDir: string\n}\n\nexport interface TurnRecord {\n label: string\n prompt: string\n threadId: string | null\n sentAt: string\n /** Seconds from the Send press. */\n firstProgressS: number | null\n firstProgressText: string | null\n firstTextS: number | null\n /** Seconds from Send to the first failure evidence on the page, if any appeared. */\n firstFailureS: number | null\n completeS: number | null\n outcome: TurnOutcome\n /** Plain words for what went wrong, or null for a completed turn. */\n error: string | null\n /** Every piece of failure evidence the turn added. */\n failures: string[]\n /** Where evidence was read: after the turn's own prompt, or the whole transcript when the page did not show the prompt. */\n evidenceScope: 'after-prompt' | 'whole-transcript' | null\n replyChars: number\n /** Distinct status lines the transcript showed, with when they appeared. */\n stages: { s: number; text: string }[]\n /** Seconds from Send at which the journey pressed Stop, if it did. */\n stopPressedS: number | null\n replyFile: string | null\n}\n\nexport interface StepRecord {\n caption: string\n label: string | null\n startS: number\n durationS: number\n ok: boolean\n error?: string\n}\n\nexport interface SendOptions {\n caption?: string\n timeoutMs?: number\n /** Keystroke delay for the prompt. */\n delay?: number\n /** Press Stop at first text, or this many seconds after Send. */\n stopAfter?: 'first-text' | number\n}\n\n/** What the page shows right now, read in one evaluate. */\ninterface PageReading extends TranscriptSnapshot {\n status: string[]\n assistantChars: number\n transcriptChars: number\n stopVisible: boolean\n}\n\nexport class Journey {\n readonly outDir: string\n readonly rawDir: string\n readonly chapters: Chapter[] = []\n readonly steps: StepRecord[] = []\n readonly turns: TurnRecord[] = []\n private recorded: Recorded[] = []\n private phones = new Map<string, BrowserContext>()\n private screenshots = new Set<string>()\n private readonly startedAt = Date.now()\n\n constructor(readonly id: string, readonly config: ResolvedJourneysConfig, readonly browser: Browser, private readonly opts: { cursor: boolean }) {\n this.outDir = join(config.outDir, id)\n this.rawDir = join(config.stateDir, 'raw', `${id}-${new Date().toISOString().replace(/[:.]/g, '-')}`)\n mkdirSync(join(this.outDir, 'video'), { recursive: true })\n mkdirSync(join(this.outDir, 'turns'), { recursive: true })\n mkdirSync(this.rawDir, { recursive: true, mode: 0o700 })\n }\n\n /**\n * A recorded, traced 1440x900 context. A config identity starts signed in\n * from the cached session (no login form is ever recorded); `'anon'` starts\n * signed out, for public pages. Open at most two per journey.\n */\n async open(label: string, identity: string, opts: { fresh?: boolean } = {}): Promise<Page> {\n if (this.recorded.some((r) => r.label === label)) throw new Error(`a context labelled ${label} is already open`)\n if (!/^[a-z0-9][a-z0-9-]{0,30}$/.test(label)) throw new Error('context label: lowercase letters, digits and dashes')\n const storageState = identity === 'anon' ? undefined : (await storageStateFor(this.config, identity, opts)).path\n const rawDir = join(this.rawDir, label)\n const context = await this.browser.newContext({\n baseURL: this.config.baseUrl,\n storageState,\n viewport: DESKTOP,\n recordVideo: { dir: rawDir, size: DESKTOP },\n locale: 'en-US',\n timezoneId: 'America/Denver',\n })\n context.setDefaultTimeout(20_000)\n context.setDefaultNavigationTimeout(60_000)\n if (this.opts.cursor) await context.addInitScript(CURSOR_SCRIPT)\n if (process.env.JOURNEY_DEBUG_CLOCK === '1') {\n // Wall-clock seconds since recording start on every frame, for calibrating captions.\n await context.addInitScript((t0: number) => {\n setInterval(() => {\n let d = document.getElementById('__journey_clock')\n if (!d && document.body) {\n d = document.createElement('div')\n d.id = '__journey_clock'\n Object.assign(d.style, { position: 'fixed', left: '50%', top: '0', zIndex: '2147483647', font: 'bold 20px monospace', background: '#ff0', color: '#000', padding: '2px 6px', pointerEvents: 'none' })\n document.body.appendChild(d)\n }\n if (d) d.textContent = ((Date.now() - t0) / 1000).toFixed(1)\n }, 100)\n }, Date.now())\n }\n await context.tracing.start({ screenshots: true, snapshots: true, title: `${this.id} ${label}` })\n const page = await context.newPage()\n this.recorded.push({ label, identity, context, page, t0: Date.now(), rawDir })\n return page\n }\n\n private recordedFor(page?: Page): Recorded {\n const r = page ? this.recorded.find((x) => x.page === page) : this.recorded[0]\n if (!r) throw new Error('no recorded context for that page; call open() first')\n return r\n }\n\n /** A chapter at this instant: one plain line, shown in the caption bar and the .srt. */\n mark(caption: string, page?: Page): void {\n const label = page ? this.recordedFor(page).label : null\n this.chapters.push({ at: Date.now(), caption, label, kind: 'step' })\n console.log(`[${secs(Date.now() - this.startedAt).toFixed(1)}s] ${label ? `${label}: ` : ''}${caption}`)\n }\n\n /** A timed step with its own chapter. A failure is recorded, captioned, then rethrown. */\n async step<T>(caption: string, work: () => Promise<T>, page?: Page): Promise<T> {\n this.mark(caption, page)\n const start = Date.now()\n const entry: StepRecord = { caption, label: page ? this.recordedFor(page).label : null, startS: secs(start - this.startedAt), durationS: 0, ok: true }\n this.steps.push(entry)\n try {\n return await work()\n } catch (error) {\n entry.ok = false\n entry.error = String((error as Error)?.message ?? error).slice(0, 400)\n this.mark(`Step failed: ${caption}`, page)\n throw error\n } finally {\n entry.durationS = secs(Date.now() - start)\n }\n }\n\n /** A waiting span: real speed in the full video, sped up and labelled in the highlights. */\n async wait<T>(caption: string, work: () => Promise<T>, page?: Page): Promise<T> {\n const label = page ? this.recordedFor(page).label : null\n const chapter: Chapter = { at: Date.now(), caption, label, kind: 'wait', until: Date.now() }\n this.chapters.push(chapter)\n console.log(`[${secs(Date.now() - this.startedAt).toFixed(1)}s] ${label ? `${label}: ` : ''}(wait) ${caption}`)\n try {\n return await work()\n } finally {\n chapter.until = Date.now()\n }\n }\n\n pause(ms = 700): Promise<void> {\n return sleep(ms)\n }\n\n /** Move the visible pointer there, pause, click, pause. */\n async click(target: Locator, opts: { pauseAfter?: number } = {}): Promise<void> {\n await target.scrollIntoViewIfNeeded()\n const box = await target.boundingBox()\n if (box) await target.page().mouse.move(box.x + box.width / 2, box.y + box.height / 2, { steps: 14 })\n await sleep(250)\n await target.click()\n await sleep(opts.pauseAfter ?? 600)\n }\n\n /** Type at a readable pace into an input or textarea. */\n async type(target: Locator, text: string, opts: { delay?: number } = {}): Promise<void> {\n await this.click(target, { pauseAfter: 200 })\n const delay = opts.delay ?? 28\n await target.pressSequentially(text, { delay, timeout: 30_000 + text.length * (delay + 60) })\n await sleep(400)\n }\n\n /** The composer's message input. */\n composerInput(page: Page): Locator {\n return page.locator(this.config.chat.composer).getByRole('textbox', { name: this.config.chat.inputName })\n }\n\n private composerButton(page: Page, name: string): Locator {\n return page.locator(this.config.chat.composer).getByRole('button', { name, exact: true })\n }\n\n /**\n * Type into the chat composer at a readable pace. A line break is typed as\n * Shift+Enter, because Enter sends. Retries fast when hydration dropped\n * keystrokes. Never `fill()` a rich-text composer.\n */\n async typePrompt(page: Page, prompt: string, opts: { delay?: number } = {}): Promise<void> {\n const box = this.composerInput(page)\n await box.waitFor({ state: 'visible', timeout: 30_000 })\n await sleep(1_200)\n const delay = opts.delay ?? (prompt.length > 400 ? 8 : 22)\n const want = prompt.replace(/\\s+/g, ' ').trim().slice(0, 80)\n for (let attempt = 0; attempt < 4; attempt += 1) {\n await this.click(box, { pauseAfter: 150 })\n await box.press('ControlOrMeta+a')\n await box.press('Backspace')\n const lines = prompt.split('\\n')\n for (let i = 0; i < lines.length; i += 1) {\n if (i > 0) await box.press('Shift+Enter')\n // Sized by length: a loaded host types slower than the context's 20 s default allows.\n const line = lines[i]!\n if (line) await box.pressSequentially(line, { delay: attempt === 0 ? delay : 0, timeout: 30_000 + line.length * (delay + 60) })\n }\n const text = (await composerText(box).catch(() => '')).replace(/\\s+/g, ' ').trim()\n if (text.includes(want)) return\n await sleep(1_000)\n }\n throw new Error('the composer never held the prompt')\n }\n\n /**\n * Which parts of the chat contract this page shows, without sending\n * anything. Run it on a second app before trusting turn timings there.\n */\n async checkChatContract(page: Page): Promise<Record<'transcript' | 'composer' | 'input' | 'send', boolean>> {\n const visible = (l: Locator) => l.first().isVisible().catch(() => false)\n return {\n transcript: await visible(page.locator(this.config.chat.transcript)),\n composer: await visible(page.locator(this.config.chat.composer)),\n input: await visible(this.composerInput(page)),\n send: await visible(this.composerButton(page, this.config.chat.sendName)),\n }\n }\n\n /**\n * Desktop screenshot of the recorded page, then the same URL in a phone\n * context (390x844, same identity). Look at both before judging the screen.\n */\n async shot(name: string, page?: Page, opts: { phone?: boolean; fullPage?: boolean; phoneUrl?: string } = {}): Promise<{ desktop: string; phone?: string }> {\n const r = this.recordedFor(page)\n const slug = name.replace(/[^a-z0-9-]+/gi, '-').toLowerCase()\n const desktop = join(this.outDir, `${slug}-desktop.png`)\n const cursor = (display: string) => r.page.evaluate((d) => { const c = document.getElementById('__journey_cursor'); if (c) c.style.display = d }, display).catch(() => {})\n await cursor('none')\n await r.page.screenshot({ path: desktop, fullPage: opts.fullPage ?? false })\n this.screenshots.add(desktop)\n await cursor('')\n if (opts.phone === false) return { desktop }\n const phonePath = join(this.outDir, `${slug}-phone.png`)\n let ctx = this.phones.get(r.identity)\n if (!ctx) {\n const storageState = r.identity === 'anon' ? undefined : (await storageStateFor(this.config, r.identity)).path\n ctx = await this.browser.newContext({ baseURL: this.config.baseUrl, storageState, viewport: PHONE, deviceScaleFactor: 2, isMobile: true, hasTouch: true, locale: 'en-US', timezoneId: 'America/Denver' })\n this.phones.set(r.identity, ctx)\n }\n const phone = await ctx.newPage()\n try {\n await phone.goto(opts.phoneUrl ?? r.page.url(), { waitUntil: 'load' })\n await phone.waitForLoadState('networkidle', { timeout: 8_000 }).catch(() => {})\n await sleep(1_500)\n await phone.screenshot({ path: phonePath, fullPage: opts.fullPage ?? false })\n this.screenshots.add(phonePath)\n } finally {\n await phone.close()\n }\n return { desktop, phone: phonePath }\n }\n\n private budgetTurn(): void {\n if (this.turns.length >= this.config.maxTurns) {\n throw new Error(`this journey already sent ${this.turns.length} chat turns, its budget (maxTurns ${this.config.maxTurns})`)\n }\n }\n\n /**\n * Start a new thread: open `from` when given, type the prompt, press Send\n * like a person (again only while the page has not submitted; never deletes\n * a duplicate), wait for the thread, then measure the turn.\n */\n async sendNew(page: Page, prompt: string, opts: SendOptions & { from?: string } = {}): Promise<TurnRecord> {\n this.budgetTurn()\n if (opts.from && !page.url().startsWith(new URL(opts.from, this.config.baseUrl).href)) await page.goto(opts.from)\n await this.typePrompt(page, prompt, { delay: opts.delay })\n const send = this.composerButton(page, this.config.chat.sendName)\n await send.waitFor({ state: 'visible' })\n const box = await send.boundingBox()\n if (box) await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2, { steps: 14 })\n await sleep(400)\n const before = await this.read(page, prompt)\n const evidence = new TurnEvidence(this.patterns(), prompt)\n evidence.begin(before)\n const tracker = createSubmissionTracker(page.url(), this.config.chat.sendPaths)\n const count = (request: { method(): string; url(): string }) => tracker.observe(request.method(), request.url())\n page.on('request', count)\n this.mark(opts.caption ?? `Sends: \"${oneLine(prompt, 90)}\"`, page)\n const sentAt = Date.now()\n const onThread = () => threadRouteIn(page.url(), this.config) !== null\n try {\n await clickUntilSubmitted({\n landed: () => tracker.count > 0 || onThread(),\n ready: () => send.click({ trial: true, timeout: 5_000 }),\n click: () => send.click({ timeout: 5_000 }),\n wait: () => page.waitForRequest((r) => tracker.matches(r.method(), r.url()), { timeout: 1_000 }).then(() => undefined).catch(() => undefined),\n attempts: 15,\n })\n if (this.config.chat.threadPath) await page.waitForURL((url) => threadRouteIn(url.href, this.config) !== null, { timeout: 45_000 })\n } catch (error) {\n return this.notSent(page, prompt, sentAt, String((error as Error).message).slice(0, 300))\n } finally {\n page.off('request', count)\n }\n if (tracker.count > 1) console.warn(`the composer submitted ${tracker.count} times; a duplicate thread may exist (left in place)`)\n return this.measureTurn(page, prompt, sentAt, evidence, before, 0, opts)\n }\n\n /** A follow-up in the open thread: type, one Send press, measure. */\n async sendInThread(page: Page, prompt: string, opts: SendOptions = {}): Promise<TurnRecord> {\n this.budgetTurn()\n await this.typePrompt(page, prompt, { delay: opts.delay })\n const send = this.composerButton(page, this.config.chat.sendName)\n const before = await this.read(page, prompt)\n const evidence = new TurnEvidence(this.patterns(), prompt)\n evidence.begin(before)\n const tracker = createSubmissionTracker(page.url(), this.config.chat.sendPaths)\n const posted = page.waitForRequest((r) => tracker.matches(r.method(), r.url()), { timeout: 30_000 })\n this.mark(opts.caption ?? `Follows up: \"${oneLine(prompt, 90)}\"`, page)\n const sentAt = Date.now()\n await this.click(send, { pauseAfter: 0 })\n const sent = await posted.then(() => true).catch(() => false)\n if (!sent) return this.notSent(page, prompt, sentAt, 'no chat request within 30 s of pressing Send')\n return this.measureTurn(page, prompt, sentAt, evidence, before, Math.max(0, before.assistantChars), opts)\n }\n\n private patterns() {\n return { failure: this.config.chat.failureText, stopped: this.config.chat.stoppedText }\n }\n\n private blankTurn(page: Page, prompt: string, sentAt: number): TurnRecord {\n return {\n label: this.recordedFor(page).label, prompt, threadId: threadRouteIn(page.url(), this.config)?.threadId ?? null,\n sentAt: new Date(sentAt).toISOString(), firstProgressS: null, firstProgressText: null, firstTextS: null, firstFailureS: null, completeS: null,\n outcome: 'timeout', error: null, failures: [], evidenceScope: null, replyChars: 0, stages: [], stopPressedS: null, replyFile: null,\n }\n }\n\n private notSent(page: Page, prompt: string, sentAt: number, why: string): TurnRecord {\n const t = { ...this.blankTurn(page, prompt, sentAt), ...scoreTurn({ notSent: why, timedOut: false, evidence: { failures: [], stopped: [], retryAppeared: false }, replyChars: 0, stopPressed: false }) }\n this.turns.push(t)\n this.mark(`Turn not sent: ${oneLine(why, 90)}`, page)\n return t\n }\n\n /** One read of the transcript, composer and failure marks; with a prompt, the evidence that follows it. */\n private async read(page: Page, prompt: string | null = null): Promise<PageReading> {\n const c = this.config.chat\n const { assistant, ...reading } = await page.evaluate(readChatPage, {\n transcript: c.transcript, status: c.status, failureNodes: c.failureNodes, retrySource: c.retryName.source, retryFlags: c.retryName.flags,\n assistant: c.assistant, composer: c.composer, stopName: c.stopName, promptHead: prompt === null ? null : promptHead(prompt),\n })\n return { ...reading, assistantChars: assistant }\n }\n\n private async runningTurns(page: Page, route: ThreadRoute | null): Promise<string[] | null> {\n if (!route || !this.config.chat.runningTurns) return null\n const res = await page.request.get(this.config.chat.runningTurns(route))\n if (!res.ok()) throw new Error(`running turns answered ${res.status()}`)\n const body = (await res.json()) as { running?: unknown }\n if (!Array.isArray(body.running)) throw new Error('running turns returned no `running` array')\n return body.running.map(String)\n }\n\n /**\n * Time to first visible progress (a new status line or reply text), first\n * reply text, and the turn's end, polled every 300 ms. Failure evidence is\n * read after the turn's own prompt when the page shows it. The turn has ended\n * when, for two reads in a row, {@link turnLooksActive} is false and, where\n * the app lists running turns, the server lists none. Status lines already\n * on the page before Send are not progress. The outcome comes from\n * {@link scoreTurn}.\n */\n private async measureTurn(page: Page, prompt: string, sentAt: number, evidence: TurnEvidence, before: PageReading, baselineChars: number, opts: SendOptions): Promise<TurnRecord> {\n const t = this.blankTurn(page, prompt, sentAt)\n this.turns.push(t)\n const route = threadRouteIn(page.url(), this.config)\n t.threadId = route?.threadId ?? null\n const timeoutMs = opts.timeoutMs ?? 15 * 60_000\n const since = () => secs(Date.now() - sentAt)\n const standingStatus = new Set(before.status)\n // Without an assistant selector, reply text is transcript growth from the\n // first read after Send (the person's own message is on the page by then).\n let growthBase: number | null = null\n let growth = 0\n let sawActive = false\n let quiet = 0\n let lastServerCheck = 0\n let serverRunning: string[] | null = null\n let lastStage = ''\n let lastStatus = ''\n let statusChangedAt = Date.now()\n let finished = false\n await this.wait('Waiting for the agent', async () => {\n while (Date.now() - sentAt < timeoutMs) {\n const s = await this.read(page, prompt).catch(() => null)\n if (s) {\n t.evidenceScope = s.anchored ? 'after-prompt' : 'whole-transcript'\n const shown = evidence.observe(s)\n if (shown.length) {\n t.firstFailureS ??= since()\n this.mark(`Failure shown after ${since()} s: ${oneLine(shown[0]!, 90)}`, page)\n }\n const status = s.status.filter((line) => !standingStatus.has(line))\n growthBase ??= s.transcriptChars\n const chars = s.assistantChars >= 0 ? s.assistantChars - baselineChars : s.transcriptChars - growthBase - status.join(' ').length\n growth = Math.max(growth, chars)\n const stage = status.join(' | ').replace(/\\b\\d+(\\.\\d+)?\\s?s\\b/g, '').trim()\n if (stage && stage !== lastStage) {\n t.stages.push({ s: since(), text: status.join(' | ').slice(0, 160) })\n lastStage = stage\n }\n // Raw text, timers included: a ticking \"Preparing your workspace… 31s\" is changing.\n if (status.join(' | ') !== lastStatus) {\n lastStatus = status.join(' | ')\n statusChangedAt = Date.now()\n }\n if (t.firstProgressS === null && (status.length || chars > 0)) {\n t.firstProgressS = since()\n t.firstProgressText = status[0] ?? 'reply text'\n this.mark(`First visible progress after ${t.firstProgressS} s: ${oneLine(t.firstProgressText, 70)}`, page)\n }\n if (t.firstTextS === null && chars > 0) {\n t.firstTextS = since()\n this.mark(`First text after ${t.firstTextS} s`, page)\n }\n const stopDue = opts.stopAfter === 'first-text' ? t.firstTextS !== null : typeof opts.stopAfter === 'number' && since() >= opts.stopAfter\n if (t.stopPressedS === null && stopDue && s.stopVisible) {\n t.stopPressedS = since()\n this.mark(`Presses Stop after ${t.stopPressedS} s`, page)\n await this.click(this.composerButton(page, this.config.chat.stopName), { pauseAfter: 200 }).catch((e) => console.warn(`Stop press failed: ${e}`))\n }\n if (status.length > 0) sawActive = true\n const active = turnLooksActive({ stopVisible: s.stopVisible, statusLines: status.length, msSinceStatusChanged: Date.now() - statusChangedAt })\n quiet = active ? 0 : quiet + 1\n }\n if (route && this.config.chat.runningTurns && Date.now() - lastServerCheck > 2_000) {\n lastServerCheck = Date.now()\n // A failed read never implies the turn ended.\n serverRunning = await this.runningTurns(page, route).catch(() => serverRunning)\n if (serverRunning?.length) sawActive = true\n }\n const started = sawActive || t.firstTextS !== null || Date.now() - sentAt > 45_000\n const serverDone = !this.config.chat.runningTurns || !route || serverRunning?.length === 0\n if (started && quiet >= 2 && serverDone) {\n finished = true\n return\n }\n await sleep(300)\n }\n }, page)\n t.completeS = finished ? since() : null\n // Render lag only: the turn has ended, so wait for the transcript to stop changing before judging it.\n await settleText(() => this.read(page, prompt).then((r) => `${r.transcriptChars}:${r.failureNodes.length}:${r.retryButtons}`))\n const last = await this.read(page, prompt)\n t.evidenceScope = last.anchored ? 'after-prompt' : 'whole-transcript'\n evidence.observe(last)\n const finalText = this.config.chat.assistant ? await this.replyText(page) : ''\n t.replyChars = this.config.chat.assistant ? Math.max(0, finalText.length - baselineChars) : Math.max(0, growth)\n Object.assign(t, scoreTurn({ timedOut: !finished, evidence: evidence.added(), replyChars: t.replyChars, stopPressed: t.stopPressedS !== null }))\n const n = this.turns.length\n t.replyFile = join('turns', `${String(n).padStart(2, '0')}-${t.label}.md`)\n const reply = this.config.chat.assistant ? finalText.slice(baselineChars).trim() : '(this app configures no assistant selector; read the reply in the video or the trace)'\n const failures = t.failures.length ? `\\n\\n## Failure evidence\\n\\n${t.failures.map((f) => `- ${f}`).join('\\n')}` : ''\n writeFileSync(join(this.outDir, t.replyFile), `# Turn ${n} (${t.label})\\n\\n## Prompt\\n\\n${prompt}\\n\\n## Reply (${t.outcome})\\n\\n${reply}${failures}\\n`)\n this.mark(\n t.outcome === 'completed'\n ? `Turn complete after ${t.completeS} s (${t.replyChars} chars)`\n : `Turn ${t.outcome.toUpperCase()} after ${t.completeS ?? since()} s${t.error ? `: ${oneLine(t.error, 80)}` : ''}`,\n page,\n )\n return t\n }\n\n private async replyText(page: Page): Promise<string> {\n const sel = this.config.chat.assistant\n if (!sel) return ''\n return settleText(async () => (await page.locator(sel).allInnerTexts()).join('\\n').trim())\n }\n\n /**\n * Close everything, then per context: a captioned full .mp4, a highlights cut\n * (at most 178 s, long waits sped up and labelled), an .srt and a scrubbed\n * trace.zip; plus timings.json and chapters.json. Refuses (throws) when any\n * output file still holds a password or cookie value.\n */\n async finish(opts: { speedup2x?: boolean } = {}): Promise<{ outDir: string; files: string[] }> {\n for (const ctx of this.phones.values()) await ctx.close().catch(() => {})\n const files: string[] = []\n // Stop every recording first, so one context's video does not run on through another's processing.\n const stopped: { r: Recorded; rawTrace: string; webm: string | null; endedAt: number }[] = []\n for (const r of this.recorded) {\n const endedAt = Date.now()\n const rawTrace = join(r.rawDir, 'trace.raw.zip')\n await r.context.tracing.stop({ path: rawTrace }).catch((e) => console.warn(`tracing.stop failed for ${r.label}: ${e}`))\n const video = r.page.video()\n await r.context.close()\n stopped.push({ r, rawTrace, webm: video ? await video.path().catch(() => null) : null, endedAt })\n }\n const needles = secretNeedles(this.config)\n for (const { r, rawTrace, webm, endedAt } of stopped) {\n if (webm) {\n files.push(...postProcessVideo({\n webm, workDir: r.rawDir, videoDir: join(this.outDir, 'video'), label: r.label, t0: r.t0,\n wallSeconds: (endedAt - r.t0) / 1000, chapters: this.chapters.filter((c) => c.label === null || c.label === r.label),\n speedup2x: opts.speedup2x ?? false,\n }))\n }\n try {\n const clean = join(this.outDir, 'video', `${r.label}-trace.zip`)\n const result = scrubTrace(rawTrace, clean, [...needles.hard, ...needles.soft])\n console.log(`trace ${r.label}: ${result.entries} entries, ${result.dropped} sensitive bodies dropped, ${result.rewritten} rewritten`)\n files.push(clean)\n } catch (error) {\n console.warn(`trace ${r.label} not written: ${(error as Error).message}`)\n }\n }\n writeFileSync(join(this.outDir, 'chapters.json'), JSON.stringify(this.chapters.map((c) => ({ ...c, at: new Date(c.at).toISOString(), until: c.until ? new Date(c.until).toISOString() : undefined, offsetS: secs(c.at - this.startedAt) })), null, 2))\n writeFileSync(join(this.outDir, 'timings.json'), JSON.stringify({ journey: this.id, app: this.config.app, base: this.config.baseUrl, startedAt: new Date(this.startedAt).toISOString(), wallS: secs(Date.now() - this.startedAt), steps: this.steps, turns: this.turns }, null, 2))\n await this.browser.close()\n assertNoSecrets(this.outDir, needles)\n pruneJourneyArtifacts(this.outDir, new Set([\n ...files,\n ...this.screenshots,\n ...this.turns.flatMap((turn) => turn.replyFile ? [join(this.outDir, turn.replyFile)] : []),\n ]))\n console.log(`\\n${this.id}: ${this.steps.length} steps, ${this.turns.length} turns, wall ${secs(Date.now() - this.startedAt)} s`)\n for (const t of this.turns) {\n console.log(` turn[${t.label}] ${t.outcome}: progress ${t.firstProgressS ?? '-'} s, first text ${t.firstTextS ?? '-'} s, end ${t.completeS ?? '-'} s, ${t.replyChars} chars${t.error ? ` | ${oneLine(t.error, 100)}` : ''}`)\n }\n const host = process.env.JOURNEYS_HOST_ALIAS ?? hostname()\n console.log(`output: ${this.outDir}\\ncopy it (run where you will watch it):\\n rsync -a ${host}:${this.outDir}/ \"<dest>/${this.id}/\"`)\n return { outDir: this.outDir, files }\n }\n}\n\nexport function oneLine(text: string, max: number): string {\n const s = text.replace(/\\s+/g, ' ').trim()\n return s.length > max ? `${s.slice(0, max - 1)}…` : s\n}\n\n/** Open a journey. Without `config`, reads `journeys.config.mjs` from the working directory. */\nexport async function startJourney(id: string, opts: { config?: JourneysConfig | ResolvedJourneysConfig; cursor?: boolean; headless?: boolean } = {}): Promise<Journey> {\n if (!/^[a-z0-9][a-z0-9-]{1,60}$/.test(id)) throw new Error('journey id: lowercase letters, digits and dashes')\n const config = opts.config ? resolveJourneysConfig(opts.config) : await loadJourneysConfig()\n let chromium\n try {\n chromium = (await import('playwright')).chromium\n } catch {\n throw new Error('journeys need the optional `playwright` peer: install playwright in the app that runs them')\n }\n const browser = await chromium.launch({ headless: opts.headless ?? true })\n return new Journey(id, config, browser, { cursor: opts.cursor ?? true })\n}\n","import { readdirSync, rmSync } from 'node:fs'\nimport { join, resolve } from 'node:path'\n\nconst groups = [\n {\n directory: '',\n owns: (name: string) => name.endsWith('-desktop.png') || name.endsWith('-phone.png'),\n },\n {\n directory: 'video',\n owns: (name: string) => name.endsWith('.mp4') || name.endsWith('.srt') || name.endsWith('-trace.zip'),\n },\n {\n directory: 'turns',\n owns: (name: string) => name.endsWith('.md'),\n },\n] as const\n\nexport function pruneJourneyArtifacts(outDir: string, retained: ReadonlySet<string>): void {\n const keep = new Set([...retained].map((file) => resolve(file)))\n for (const group of groups) {\n const directory = join(resolve(outDir), group.directory)\n for (const entry of readdirSync(directory, { withFileTypes: true })) {\n if ((!entry.isFile() && !entry.isSymbolicLink()) || !group.owns(entry.name)) continue\n const file = join(directory, entry.name)\n if (!keep.has(file)) rmSync(file)\n }\n }\n}\n","/**\n * The one read of a chat page a journey takes every 300 ms, run inside the page\n * by `page.evaluate`, so it must stay self-contained: DOM globals only, no\n * imports and no module-scope names.\n *\n * Failure evidence belongs to the turn whose prompt it follows. On 2026-10-11\n * GTM showed a live Stop as a grey notice, then, when the next message was\n * sent, re-rendered the stopped turn with its red \"You stopped this turn.\" card\n * and a Retry control, above the new message. Read from the whole transcript,\n * that card failed the follow-up, which had answered in 28.5 s. So when the\n * transcript shows the turn's own prompt, only failure marks, Retry controls\n * and lines after it count; when it does not, the whole transcript does.\n */\n\ninterface PageReadArgs {\n readonly transcript: string\n readonly status: string\n readonly failureNodes: string\n readonly retrySource: string\n readonly retryFlags: string\n readonly assistant: string | null\n readonly composer: string\n readonly stopName: string\n /** The turn's prompt as {@link promptHead} gives it; null reads the whole transcript. */\n readonly promptHead: string | null\n}\n\ninterface RawPageReading {\n /** Visible transcript lines (after the turn's prompt when `anchored`). */\n lines: string[]\n failureNodes: string[]\n retryButtons: number\n status: string[]\n /** Characters of assistant text on the page, or -1 with no assistant selector. */\n assistant: number\n transcriptChars: number\n stopVisible: boolean\n /** The turn's prompt was found, so the evidence fields hold only what follows it. */\n anchored: boolean\n}\n\n/** The text a transcript shows for a prompt: its first line, whitespace squashed, at most 48 characters. */\nexport function promptHead(prompt: string): string | null {\n const first = prompt.split('\\n').map((line) => line.replace(/\\s+/g, ' ').trim()).find(Boolean)\n return first ? first.slice(0, 48) : null\n}\n\nexport function readChatPage(c: PageReadArgs): RawPageReading {\n const squash = (s: string) => s.replace(/\\s+/g, ' ').trim()\n const clean = (e: Element) => squash(e.textContent ?? '')\n const region = document.querySelector<HTMLElement>(c.transcript)\n const composer = document.querySelector<HTMLElement>(c.composer)\n const assistantNodes = c.assistant ? Array.from(document.querySelectorAll<HTMLElement>(c.assistant)) : []\n const within = (sel: string) => (region ? Array.from(region.querySelectorAll(sel)) : [])\n\n // The last text node outside the composer and the assistant's own text that holds the prompt.\n let anchor: Node | null = null\n if (region && c.promptHead) {\n const walker = document.createTreeWalker(region, NodeFilter.SHOW_TEXT)\n for (let node = walker.nextNode(); node; node = walker.nextNode()) {\n if (!squash(node.nodeValue ?? '').includes(c.promptHead)) continue\n if (composer?.contains(node) || assistantNodes.some((a) => a.contains(node))) continue\n anchor = node\n }\n }\n const after = (e: Element) => anchor === null || (anchor.compareDocumentPosition(e) & Node.DOCUMENT_POSITION_FOLLOWING) !== 0\n\n const full = region?.innerText ?? ''\n let text = full\n const composerText = composer && region?.contains(composer) ? composer.innerText.trim() : ''\n if (composerText) {\n const at = text.lastIndexOf(composerText)\n if (at >= 0) text = text.slice(0, at) + text.slice(at + composerText.length)\n }\n let lines = text.split('\\n').map((l) => l.trim()).filter(Boolean)\n if (anchor && c.promptHead) {\n // The same rule for lines: the last one holding the prompt that is not the assistant's.\n const replyLines = new Set(assistantNodes.flatMap((a) => a.innerText.split('\\n').map(squash)))\n let last = -1\n for (let i = 0; i < lines.length; i += 1) {\n const line = squash(lines[i]!)\n if (line.includes(c.promptHead) && !replyLines.has(line)) last = i\n }\n lines = lines.slice(last + 1)\n }\n\n const status = within(c.status).map(clean).filter(Boolean)\n // textContent, not innerText: a failure's collapsed details (the code) count too.\n const failureNodes = within(c.failureNodes).filter(after).map(clean).filter(Boolean)\n const retry = new RegExp(c.retrySource, c.retryFlags)\n const retryButtons = within('button').filter((b) => after(b) && retry.test((b.getAttribute('aria-label') ?? b.textContent ?? '').trim())).length\n const assistant = c.assistant ? assistantNodes.map((e) => e.innerText).join('\\n').trim().length : -1\n const stopVisible = composer !== null && Array.from(composer.querySelectorAll('button')).some((b) =>\n (b.getAttribute('aria-label') ?? b.textContent ?? '').trim() === c.stopName && b.getClientRects().length > 0)\n return { lines, failureNodes, retryButtons, status, assistant, transcriptChars: full.trim().length, stopVisible, anchored: anchor !== null }\n}\n","/**\n * Pressing Send like a person, exactly as often as it takes and never once more.\n *\n * A new-chat composer can drop a press while its model selection is still\n * resolving, and its Send control is not disabled while that gate is shut, so\n * one press can be a silent no-op and a retry is necessary. A retry is also\n * dangerous: the press creates a thread, so a press after the page has already\n * submitted asks for a second one. Pure, so the rule is a unit test.\n */\n\n/** Paths a submission from `routePath` lands on: the route itself and its single-fetch `.data` form. */\nexport function routeSubmitPaths(routePath: string): string[] {\n const singleFetch = routePath.endsWith('/') ? `${routePath}_.data` : `${routePath}.data`\n return [routePath, singleFetch]\n}\n\nexport interface SubmissionTracker {\n /** Whether one request is a submission from the tracked page. */\n matches(method: string, url: string): boolean\n observe(method: string, url: string): void\n /** Submissions seen so far. Above zero means the turn is on its way. */\n readonly count: number\n}\n\n/**\n * Counts submissions from the page at `routeUrl`: a POST to that route (or its\n * `.data` form), or to one of `sendPaths`, on the same origin. A POST to the\n * same path on another origin is not this composer's.\n */\nexport function createSubmissionTracker(routeUrl: string, sendPaths: readonly RegExp[]): SubmissionTracker {\n if (!/^https?:\\/\\//i.test(routeUrl)) throw new Error(`createSubmissionTracker needs the page's full URL, got \"${routeUrl}\"`)\n const route = new URL(routeUrl)\n const exact = new Set(routeSubmitPaths(route.pathname))\n let count = 0\n const matches = (method: string, url: string): boolean => {\n if (method !== 'POST') return false\n let parsed: URL\n try {\n parsed = new URL(url, route.origin)\n } catch {\n return false\n }\n if (parsed.origin !== route.origin) return false\n return exact.has(parsed.pathname) || sendPaths.some((p) => p.test(parsed.pathname))\n }\n return {\n matches,\n observe(method, url) {\n if (matches(method, url)) count += 1\n },\n get count() {\n return count\n },\n }\n}\n\nexport interface SendDriveOps {\n /** True once a submission, or the navigation it causes, has been observed. */\n landed: () => boolean\n /** Wait until Send can take a press, without pressing it. */\n ready: () => Promise<void>\n click: () => Promise<void>\n /** Pause between presses, spent watching for the submission. */\n wait: () => Promise<void>\n attempts: number\n}\n\n/**\n * Press until the page submits. Each attempt waits for the control first and\n * takes its last look at `landed()` after that wait, so the press itself is the\n * only unguarded moment. A click failure is tolerated only once something has\n * landed: an accepted send tears the composer down mid-press.\n */\nexport async function clickUntilSubmitted(ops: SendDriveOps): Promise<void> {\n for (let attempt = 0; attempt < ops.attempts; attempt += 1) {\n if (ops.landed()) return\n try {\n await ops.ready()\n if (ops.landed()) return\n await ops.click()\n } catch (cause) {\n if (!ops.landed()) throw cause\n }\n if (ops.landed()) return\n await ops.wait()\n }\n if (ops.landed()) return\n throw new Error(`Send never submitted: the composer refused ${ops.attempts} presses`)\n}\n\n/**\n * Read until the value stops changing: six identical reads 500 ms apart. Every\n * caller has already seen the turn finish, so this covers render lag only.\n */\nexport async function settleText(\n read: () => Promise<string>,\n wait: (ms: number) => Promise<void> = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),\n timeoutMs = 20_000,\n): Promise<string> {\n const deadline = Date.now() + timeoutMs\n let previous: string | null = null\n let stable = 0\n for (;;) {\n const current = await read().catch(() => null)\n if (current === null) {\n stable = 0\n } else {\n stable = current === previous ? stable + 1 : 1\n previous = current\n if (stable >= 6) return current\n }\n if (Date.now() >= deadline) return previous ?? ''\n await wait(500)\n }\n}\n\n/**\n * The text a composer holds. A `<textarea>` or `<input>` (agent-app's own\n * ChatComposer) keeps typed text in `.value` and leaves `innerText` empty; a\n * contenteditable composer keeps it in `innerText`. Reading only `innerText`\n * failed every first chat turn on the default composer (Casework C1/C5).\n */\nexport async function composerText(box: { evaluate<R>(fn: (el: Element) => R): Promise<R> }): Promise<string> {\n return box.evaluate((el) => {\n const field = el as Element & { value?: unknown; innerText?: string }\n return typeof field.value === 'string' ? field.value : (field.innerText ?? el.textContent ?? '')\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkBA,SAAS,WAAW,qBAAqB;AACzC,SAAS,gBAAgB;AACzB,SAAS,QAAAA,aAAY;;;ACpBrB,SAAS,aAAa,cAAc;AACpC,SAAS,MAAM,eAAe;AAE9B,IAAM,SAAS;AAAA,EACb;AAAA,IACE,WAAW;AAAA,IACX,MAAM,CAAC,SAAiB,KAAK,SAAS,cAAc,KAAK,KAAK,SAAS,YAAY;AAAA,EACrF;AAAA,EACA;AAAA,IACE,WAAW;AAAA,IACX,MAAM,CAAC,SAAiB,KAAK,SAAS,MAAM,KAAK,KAAK,SAAS,MAAM,KAAK,KAAK,SAAS,YAAY;AAAA,EACtG;AAAA,EACA;AAAA,IACE,WAAW;AAAA,IACX,MAAM,CAAC,SAAiB,KAAK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OAAO,cAAc,EAAE,kBAAkB,GAAG,kBAAkB,EAAE,cAAc,GAAG,WAAW,EAAE,aAAa,GAAG,OAAO,EAAE,UAAU,SAAS,EAAE,QAAQ,MAAM,QAAQ,EAAE,OAAO,GAAG,CAAC,KAAK,EAAE,EAAE;AAAA,IAC9N;AACA,UAAM,OAAO,QAAQ,IAAI,uBAAuB,SAAS;AACzD,YAAQ,IAAI,WAAW,KAAK,MAAM;AAAA;AAAA,aAAwD,IAAI,IAAI,KAAK,MAAM,aAAa,KAAK,EAAE,IAAI;AACrI,WAAO,EAAE,QAAQ,KAAK,QAAQ,MAAM;AAAA,EACtC;AACF;AAEO,SAAS,QAAQ,MAAc,KAAqB;AACzD,QAAM,IAAI,KAAK,QAAQ,QAAQ,GAAG,EAAE,KAAK;AACzC,SAAO,EAAE,SAAS,MAAM,GAAG,EAAE,MAAM,GAAG,MAAM,CAAC,CAAC,WAAM;AACtD;AAGA,eAAsB,aAAa,IAAY,OAAmG,CAAC,GAAqB;AACtK,MAAI,CAAC,4BAA4B,KAAK,EAAE,EAAG,OAAM,IAAI,MAAM,kDAAkD;AAC7G,QAAM,SAAS,KAAK,SAAS,sBAAsB,KAAK,MAAM,IAAI,MAAM,mBAAmB;AAC3F,MAAI;AACJ,MAAI;AACF,gBAAY,MAAM,OAAO,YAAY,GAAG;AAAA,EAC1C,QAAQ;AACN,UAAM,IAAI,MAAM,4FAA4F;AAAA,EAC9G;AACA,QAAM,UAAU,MAAM,SAAS,OAAO,EAAE,UAAU,KAAK,YAAY,KAAK,CAAC;AACzE,SAAO,IAAI,QAAQ,IAAI,QAAQ,SAAS,EAAE,QAAQ,KAAK,UAAU,KAAK,CAAC;AACzE;","names":["join","composerText","resolve","resolve","join"]}
|
package/dist/journeys/score.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Whether a recorded chat turn worked, decided from what the person saw.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
4
|
+
* The GTM journey harness scored 6 of 6 failed turns "completed":
|
|
5
5
|
* it read failure only from `role="alert"` and from the tail of the assistant's
|
|
6
6
|
* markdown, and the red failure card a person saw carried neither. One caption
|
|
7
7
|
* read "Turn complete after 159.6 s" over "The agent stopped before finishing".
|
|
@@ -15,8 +15,7 @@
|
|
|
15
15
|
* and a field the run no longer has (an old blocker on a flow that now passes)
|
|
16
16
|
* is deleted. A document with no known version is created with `set`; the
|
|
17
17
|
* store refuses a `set` without a version on a document that already exists
|
|
18
|
-
* (version_mismatch, nothing written; checked against the board's store
|
|
19
|
-
* 2026-10-12), so a row a person wrote is never replaced.
|
|
18
|
+
* (version_mismatch, nothing written; checked against the board's store), so a row a person wrote is never replaced.
|
|
20
19
|
*
|
|
21
20
|
* Pure: the same summary and options give the same writes, in the same order.
|
|
22
21
|
*/
|
package/dist/journeys/send.d.ts
CHANGED
|
@@ -48,8 +48,7 @@ export declare function settleText(read: () => Promise<string>, wait?: (ms: numb
|
|
|
48
48
|
* The text a composer holds. A `<textarea>` or `<input>` (agent-app's own
|
|
49
49
|
* ChatComposer) keeps typed text in `.value` and leaves `innerText` empty; a
|
|
50
50
|
* contenteditable composer keeps it in `innerText`. Reading only `innerText`
|
|
51
|
-
* failed every first chat turn on the default composer (Casework C1/C5
|
|
52
|
-
* 2026-10-12).
|
|
51
|
+
* failed every first chat turn on the default composer (Casework C1/C5).
|
|
53
52
|
*/
|
|
54
53
|
export declare function composerText(box: {
|
|
55
54
|
evaluate<R>(fn: (el: Element) => R): Promise<R>;
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
* Every lookup reads the store first, so a revoked or expired credential is
|
|
6
6
|
* refused as soon as the store says so, and that answer drops its entry. When
|
|
7
7
|
* the store errors or stalls past the deadline, a valid result verified less
|
|
8
|
-
* than the TTL ago is served instead:
|
|
8
|
+
* than the TTL ago is served instead: an overloaded D1 failed
|
|
9
9
|
* API-key checks and session reads for requests whose credentials were valid
|
|
10
10
|
* moments before (GTM #1488). The TTL counts from the last successful store
|
|
11
11
|
* read and a served entry never renews it, so a credential revoked during an
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* The launch invariants every agent app holds, and the budgets they are held to.
|
|
3
3
|
*
|
|
4
|
-
* Each one is a failure GTM shipped to production
|
|
4
|
+
* Each one is a failure GTM shipped to production and fixed by
|
|
5
5
|
* hand. They are listed here once so every app checks the same rule with the
|
|
6
6
|
* same numbers, and `agent-app-invariants` reports each by its id.
|
|
7
7
|
*/
|
|
@@ -29,13 +29,13 @@ export declare const LAUNCH_BUDGETS: {
|
|
|
29
29
|
readonly d1RowsPerQuery: 250000;
|
|
30
30
|
/** A workspace box's disk: the Sandbox SDK's default tier (10 GB). */
|
|
31
31
|
readonly sandboxDiskBytes: number;
|
|
32
|
-
/** Platform snapshots per box; the cap GTM hit
|
|
32
|
+
/** Platform snapshots per box; the cap GTM hit. */
|
|
33
33
|
readonly snapshotCount: 25;
|
|
34
34
|
/** Operator key requests per minute. */
|
|
35
35
|
readonly keyRatePerMinute: 60;
|
|
36
36
|
/** Hours one resource's limit alarm waits before it repeats. */
|
|
37
37
|
readonly alarmRepeatHours: 6;
|
|
38
|
-
/** Cloudflare's gzip limit on a Worker's Total Upload on the paid plan, in KiB; Legal deployed 9,659 KiB (94%)
|
|
38
|
+
/** Cloudflare's gzip limit on a Worker's Total Upload on the paid plan, in KiB; Legal deployed 9,659 KiB (94%). */
|
|
39
39
|
readonly workerUploadGzipKiB: number;
|
|
40
40
|
/** Cloudflare's raw limit on a Worker's Total Upload, in KiB. */
|
|
41
41
|
readonly workerUploadRawKiB: number;
|
|
@@ -5,9 +5,9 @@ import {
|
|
|
5
5
|
formatConformanceReport,
|
|
6
6
|
readDeploymentFacts,
|
|
7
7
|
readVerdicts
|
|
8
|
-
} from "../chunk-
|
|
9
|
-
import "../chunk-
|
|
10
|
-
import "../chunk-
|
|
8
|
+
} from "../chunk-KA6LD4OI.js";
|
|
9
|
+
import "../chunk-5WSSH3X5.js";
|
|
10
|
+
import "../chunk-VEPII3YP.js";
|
|
11
11
|
import "../chunk-XOHE6SKU.js";
|
|
12
12
|
import "../chunk-JRCZHDRG.js";
|
|
13
13
|
import {
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* `/launch-invariants` — the rules every agent app holds before launch, and the
|
|
3
3
|
* runtime pieces that hold them.
|
|
4
4
|
*
|
|
5
|
-
* Each invariant is a failure GTM shipped
|
|
5
|
+
* Each invariant is a failure GTM shipped and fixed by hand
|
|
6
6
|
* (see {@link LAUNCH_INVARIANTS}). This subpath carries what runs in the
|
|
7
7
|
* Worker: sized reads, the scheduled dispatcher that gives each job its own
|
|
8
8
|
* invocation, the auth lookup cache that survives a D1 stall, and the 80%
|
|
@@ -5,7 +5,7 @@ import {
|
|
|
5
5
|
SIZED_READ_ROWS,
|
|
6
6
|
readInSizedBatches,
|
|
7
7
|
sizedBatches
|
|
8
|
-
} from "../chunk-
|
|
8
|
+
} from "../chunk-UULUBF5J.js";
|
|
9
9
|
import {
|
|
10
10
|
DEFAULT_LIMIT_BUDGETS,
|
|
11
11
|
LIMIT_RESOURCES,
|
|
@@ -21,13 +21,13 @@ import {
|
|
|
21
21
|
parseWranglerCrons,
|
|
22
22
|
slotsOf,
|
|
23
23
|
withD1LimitAlarms
|
|
24
|
-
} from "../chunk-
|
|
24
|
+
} from "../chunk-5WSSH3X5.js";
|
|
25
25
|
import {
|
|
26
26
|
LAUNCH_BUDGETS,
|
|
27
27
|
LAUNCH_INVARIANTS,
|
|
28
28
|
LAUNCH_INVARIANT_IDS,
|
|
29
29
|
describeVerdict
|
|
30
|
-
} from "../chunk-
|
|
30
|
+
} from "../chunk-VEPII3YP.js";
|
|
31
31
|
import "../chunk-XOHE6SKU.js";
|
|
32
32
|
import "../chunk-JRCZHDRG.js";
|
|
33
33
|
import {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/launch-invariants/auth-lookup-cache.ts","../../src/launch-invariants/settlement.ts"],"sourcesContent":["/**\n * The last valid result of each auth lookup (API key, key owner, browser\n * session), served only while the store cannot answer.\n *\n * Every lookup reads the store first, so a revoked or expired credential is\n * refused as soon as the store says so, and that answer drops its entry. When\n * the store errors or stalls past the deadline, a valid result verified less\n * than the TTL ago is served instead: on 2026-10-10 an overloaded D1 failed\n * API-key checks and session reads for requests whose credentials were valid\n * moments before (GTM #1488). The TTL counts from the last successful store\n * read and a served entry never renews it, so a credential revoked during an\n * outage lives at most the TTL past its last verification. Entries are per\n * isolate; revoking or rotating a key must also drop its entry here.\n *\n * The cache serves the verified value itself, never a copy: GTM keyed a\n * WeakMap on the verified key object, a copy missed it, and operator requests\n * answered 401 (GTM #1492).\n */\n\n/** Longest a verified result may be served while the store cannot answer. A larger configured TTL is capped here. */\nexport const AUTH_LOOKUP_TTL_MS = 60_000\n/** A store read slower than this is treated as unavailable; a healthy D1 lookup answers in tens of milliseconds. */\nexport const AUTH_LOOKUP_DEADLINE_MS = 2_500\nconst MAX_ENTRIES = 2_000\n\n/** The store answered that the credential is not valid; never answered from the cache. */\nexport class AuthLookupRefused extends Error {}\n\ninterface Entry<V> {\n value: V\n until: number\n}\n\nexport interface AuthLookupOptions<V> {\n /** When the credential itself expires (Unix ms); the entry never outlives it. */\n expiresAt?: (value: V) => number | null | undefined\n}\n\nexport interface AuthLookupCache<V> {\n /**\n * Read through the store. `read` resolves the valid value or null, or throws\n * {@link AuthLookupRefused} (or a `Response`) when the store refuses; any\n * other failure, or no answer by the deadline, falls back to a fresh entry.\n * `key` must not be the secret: use {@link credentialCacheKey}.\n */\n lookup(key: string, read: () => Promise<V | null>, options?: AuthLookupOptions<V>): Promise<V | null>\n /** Drop every entry whose value matches, as when a key is revoked or rotated. */\n invalidate(matches: (value: V) => boolean): void\n /** Drop one entry by its key. */\n forget(key: string): void\n clear(): void\n /** The keys held, for a check that no secret is stored. */\n keys(): string[]\n}\n\nexport interface AuthLookupCacheOptions {\n /** Names the lookup in the warning logged when a cached result is served. */\n label: string\n /** Capped at {@link AUTH_LOOKUP_TTL_MS}. */\n ttlMs?: number\n deadlineMs?: number\n now?: () => number\n warn?: (message: string, detail: Record<string, unknown>) => void\n}\n\nexport function createAuthLookupCache<V>(options: AuthLookupCacheOptions): AuthLookupCache<V> {\n const ttlMs = Math.min(options.ttlMs ?? AUTH_LOOKUP_TTL_MS, AUTH_LOOKUP_TTL_MS)\n const deadlineMs = options.deadlineMs ?? AUTH_LOOKUP_DEADLINE_MS\n const now = options.now ?? (() => Date.now())\n const warn = options.warn ?? ((message, detail) => console.warn(message, detail))\n const entries = new Map<string, Entry<V>>()\n\n return {\n async lookup(key, read, lookupOptions) {\n let value: V | null\n try {\n value = await withDeadline(read(), deadlineMs)\n } catch (error) {\n if (error instanceof AuthLookupRefused || error instanceof Response) {\n entries.delete(key)\n throw error\n }\n const entry = entries.get(key)\n if (entry && now() < entry.until) {\n warn(`[auth-cache] ${options.label}: served the last valid result while the store was unavailable`, {\n error: error instanceof Error ? error.message : String(error),\n remainingMs: entry.until - now(),\n })\n return entry.value\n }\n entries.delete(key)\n throw error\n }\n if (value === null) {\n entries.delete(key)\n return null\n }\n const expiresAt = lookupOptions?.expiresAt?.(value)\n const until = Math.min(now() + ttlMs, typeof expiresAt === 'number' && expiresAt > 0 ? expiresAt : Number.POSITIVE_INFINITY)\n entries.delete(key)\n entries.set(key, { value, until })\n if (entries.size > MAX_ENTRIES) entries.delete(entries.keys().next().value!)\n return value\n },\n invalidate(matches) {\n for (const [key, entry] of entries) if (matches(entry.value)) entries.delete(key)\n },\n forget(key) {\n entries.delete(key)\n },\n clear() {\n entries.clear()\n },\n keys() {\n return [...entries.keys()]\n },\n }\n}\n\n/** A credential's cache key: its SHA-256 in hex, so the cache never holds the secret. */\nexport async function credentialCacheKey(secret: string): Promise<string> {\n const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(secret))\n return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, '0')).join('')\n}\n\nfunction withDeadline<T>(promise: Promise<T>, ms: number): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined\n const deadline = new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(new Error(`auth lookup did not answer within ${ms} ms`)), ms)\n })\n return Promise.race([promise, deadline]).finally(() => clearTimeout(timer))\n}\n","/**\n * Honest turn settlement, checked over a product's turn records.\n *\n * A turn ends in exactly one terminal state: an answer, a typed failure the\n * person can Retry, or a Stop the person chose, counted on its own. It gets\n * there within 15 minutes of its owner stopping. A failure belongs to the time\n * the turn was requested, not the time it was noticed, and how late it was\n * noticed is measured. A run that completed with a tool call the Sandbox\n * aborted stopped mid-work, so it is a failure.\n *\n * On 2026-10-10 GTM held turns in five places (turn status, admissions,\n * Workflows, Sandbox sessions and the sidecar tracker) and they disagreed:\n * 51 stream rows stayed `running` after their producers died, failure notices\n * arrived 8–11 hours late, and completions with aborted tools counted as\n * answers. {@link checkTurnSettlement} reads one normalized record per turn,\n * however the product derives it, and names every turn that breaks the rule.\n */\nimport { LAUNCH_BUDGETS, type InvariantVerdict } from './catalog.js'\n\nexport type TurnTerminalState = 'answered' | 'failed' | 'stopped'\n\n/** One turn as its product records it, normalized. Times are Unix ms. */\nexport interface SettledTurnRecord {\n turnId: string\n /** When the request was accepted (the user message was saved). */\n requestedAt: number\n /** Every terminal state recorded for the turn, in order; exactly one is honest. */\n terminals: ReadonlyArray<{\n state: TurnTerminalState\n /** When the terminal state was recorded. */\n at: number\n /** A typed failure code, for `failed`. */\n code?: string\n /** Whether the person is offered Retry, for `failed`. */\n retryable?: boolean\n /** The time the failure is reported under; it must be the request time. */\n attributedTo?: number\n }>\n /** When the turn's owner stopped: for a leased stream, when its lease expired. Null while an owner holds it. */\n ownerEndedAt: number | null\n /** A completed run in which the Sandbox aborted a tool call. */\n abortedToolCall?: boolean\n}\n\nexport interface TurnSettlementCounts {\n turns: number\n answered: number\n failed: number\n stopped: number\n open: number\n /** Most minutes between an owner stopping and its turn's terminal state. */\n maxDetectionLagMinutes: number\n}\n\n/**\n * Check turn records against honest settlement at `now`.\n * A turn still open whose owner has not stopped is fine; one whose owner stopped\n * more than {@link LAUNCH_BUDGETS.settleWithinMs} ago is not.\n */\nexport function checkTurnSettlement(\n turns: readonly SettledTurnRecord[],\n options: { now: number; settleWithinMs?: number; subject?: string },\n): InvariantVerdict {\n const within = options.settleWithinMs ?? LAUNCH_BUDGETS.settleWithinMs\n const findings: string[] = []\n const counts: TurnSettlementCounts = { turns: turns.length, answered: 0, failed: 0, stopped: 0, open: 0, maxDetectionLagMinutes: 0 }\n for (const turn of turns) {\n const label = `turn ${turn.turnId}`\n if (turn.terminals.length > 1) {\n findings.push(`${label} has ${turn.terminals.length} terminal states (${turn.terminals.map((terminal) => terminal.state).join(' then ')}); a turn ends once`)\n }\n const terminal = turn.terminals[0]\n if (!terminal) {\n counts.open += 1\n if (turn.ownerEndedAt !== null && options.now - turn.ownerEndedAt > within) {\n findings.push(`${label} is still open ${minutes(options.now - turn.ownerEndedAt)} min after its owner stopped; the most is ${minutes(within)}`)\n }\n continue\n }\n counts[terminal.state] += 1\n if (turn.ownerEndedAt !== null) {\n const lag = terminal.at - turn.ownerEndedAt\n counts.maxDetectionLagMinutes = Math.max(counts.maxDetectionLagMinutes, minutes(lag))\n if (lag > within) findings.push(`${label} was settled ${minutes(lag)} min after its owner stopped; the most is ${minutes(within)}`)\n }\n if (terminal.state === 'answered' && turn.abortedToolCall) {\n findings.push(`${label} is counted as an answer, but the Sandbox aborted a tool call in it; it stopped mid-work and is a failure`)\n }\n if (terminal.state === 'failed') {\n if (!terminal.code) findings.push(`${label} failed without a typed failure code`)\n if (terminal.retryable !== true) findings.push(`${label} failed without offering Retry`)\n if (terminal.attributedTo !== undefined && terminal.attributedTo !== turn.requestedAt) {\n findings.push(`${label}'s failure is reported at ${new Date(terminal.attributedTo).toISOString()}, not its request time ${new Date(turn.requestedAt).toISOString()}`)\n }\n }\n if (terminal.state === 'stopped' && terminal.code && /fail|error/i.test(terminal.code)) {\n findings.push(`${label} was stopped by the person but carries failure code ${terminal.code}; a Stop is counted on its own`)\n }\n }\n return {\n invariant: 'honest-settlement',\n subject: options.subject ?? 'turns',\n pass: findings.length === 0,\n details: findings.length ? findings : [\n `${counts.turns} turns: ${counts.answered} answered, ${counts.failed} failed with Retry, ${counts.stopped} stopped, ${counts.open} held by a live owner`,\n `longest detection lag ${counts.maxDetectionLagMinutes} min`,\n ],\n data: { ...counts },\n }\n}\n\nfunction minutes(ms: number): number {\n return Math.round((ms / 60_000) * 10) / 10\n}\n\n/**\n * The failure shapes GTM shipped on 2026-10-10, as scenarios a product seeds\n * into its own storage, settles with its own scheduled jobs, and reads back as\n * {@link SettledTurnRecord}s. `expect` is the one honest terminal state.\n */\nexport interface SettlementScenario {\n id: string\n /** What happened to the turn, for the product's seed step. */\n story: string\n /** Minutes before the check's `now` that the request was accepted. */\n requestedMinutesAgo: number\n /**\n * Minutes before `now` that the owner stopped (for a stream, its lease\n * expired), or null for a live owner. Every scenario that stopped did so 12\n * minutes ago, so an app that settles within 15 minutes has settled it by `now`.\n */\n ownerEndedMinutesAgo: number | null\n expect: TurnTerminalState | 'open'\n}\n\nexport const SETTLEMENT_SCENARIOS: readonly SettlementScenario[] = [\n {\n id: 'orphaned-stream',\n story: 'The Worker streaming the turn died; its stream row is still running, no admission or Workflow holds it, and its 5-minute lease expired 12 minutes ago.',\n requestedMinutesAgo: 30,\n ownerEndedMinutesAgo: 12,\n expect: 'failed',\n },\n {\n id: 'abandoned-before-admission',\n story: 'The user message was saved 12 minutes ago, then the request died before any completion owner admitted the turn: no reply, no stream, no admission.',\n requestedMinutesAgo: 12,\n ownerEndedMinutesAgo: 12,\n expect: 'failed',\n },\n {\n id: 'runtime-restarted',\n story: 'The admitted run\\'s runtime restarted mid-turn 12 minutes ago: the session still reports running while its execution ledger failed the run (terminal event interrupted-done).',\n requestedMinutesAgo: 40,\n ownerEndedMinutesAgo: 12,\n expect: 'failed',\n },\n {\n id: 'completed-with-aborted-tool',\n story: 'The run reported completed 12 minutes ago, but a tool part ended with \"Tool execution aborted\".',\n requestedMinutesAgo: 20,\n ownerEndedMinutesAgo: 12,\n expect: 'failed',\n },\n {\n id: 'user-stop',\n story: 'The person pressed Stop 12 minutes ago while the turn ran.',\n requestedMinutesAgo: 20,\n ownerEndedMinutesAgo: 12,\n expect: 'stopped',\n },\n {\n id: 'answered',\n story: 'The turn answered normally 12 minutes ago.',\n requestedMinutesAgo: 20,\n ownerEndedMinutesAgo: 12,\n expect: 'answered',\n },\n {\n id: 'live-long-turn',\n story: 'A long turn is still running under an owner that renews its lease.',\n requestedMinutesAgo: 90,\n ownerEndedMinutesAgo: null,\n expect: 'open',\n },\n]\n\n/**\n * Check a product's settlement of {@link SETTLEMENT_SCENARIOS}: each scenario's\n * record ends in its expected state, and all of them settle honestly. The\n * product seeds each scenario at `now`, runs its own recovery and settlement\n * jobs at `now`, and reads the records back keyed by scenario id.\n */\nexport function checkSettlementScenarios(\n records: Readonly<Record<string, SettledTurnRecord | undefined>>,\n options: { now: number; scenarios?: readonly SettlementScenario[] },\n): InvariantVerdict {\n const scenarios = options.scenarios ?? SETTLEMENT_SCENARIOS\n const findings: string[] = []\n const present: SettledTurnRecord[] = []\n for (const scenario of scenarios) {\n const record = records[scenario.id]\n if (!record) {\n findings.push(`scenario ${scenario.id}: no turn record was read back`)\n continue\n }\n present.push(record)\n const state = record.terminals[0]?.state ?? 'open'\n if (state !== scenario.expect) findings.push(`scenario ${scenario.id}: ended ${state}, expected ${scenario.expect} (${scenario.story})`)\n }\n const honest = checkTurnSettlement(present, { now: options.now, subject: 'settlement scenarios' })\n if (!honest.pass) findings.push(...honest.details)\n return {\n invariant: 'honest-settlement',\n subject: 'settlement scenarios',\n pass: findings.length === 0,\n details: findings.length ? findings : [`${scenarios.length} failure scenarios settle to their honest state`, ...honest.details],\n data: honest.data,\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoBO,IAAM,qBAAqB;AAE3B,IA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AA,IACtB,QAAQ;AAAA,EACV;AAAA,EACA;AAAA,IACE,IAAI;AAAA,IACJ,OAAO;AAAA,IACP,qBAAqB;AAAA,IACrB,sBAAsB;AAAA,IACtB,QAAQ;AAAA,EACV;AACF;AAQO,SAAS,yBACd,SACA,SACkB;AAClB,QAAM,YAAY,QAAQ,aAAa;AACvC,QAAM,WAAqB,CAAC;AAC5B,QAAM,UAA+B,CAAC;AACtC,aAAW,YAAY,WAAW;AAChC,UAAM,SAAS,QAAQ,SAAS,EAAE;AAClC,QAAI,CAAC,QAAQ;AACX,eAAS,KAAK,YAAY,SAAS,EAAE,gCAAgC;AACrE;AAAA,IACF;AACA,YAAQ,KAAK,MAAM;AACnB,UAAM,QAAQ,OAAO,UAAU,CAAC,GAAG,SAAS;AAC5C,QAAI,UAAU,SAAS,OAAQ,UAAS,KAAK,YAAY,SAAS,EAAE,WAAW,KAAK,cAAc,SAAS,MAAM,KAAK,SAAS,KAAK,GAAG;AAAA,EACzI;AACA,QAAM,SAAS,oBAAoB,SAAS,EAAE,KAAK,QAAQ,KAAK,SAAS,uBAAuB,CAAC;AACjG,MAAI,CAAC,OAAO,KAAM,UAAS,KAAK,GAAG,OAAO,OAAO;AACjD,SAAO;AAAA,IACL,WAAW;AAAA,IACX,SAAS;AAAA,IACT,MAAM,SAAS,WAAW;AAAA,IAC1B,SAAS,SAAS,SAAS,WAAW,CAAC,GAAG,UAAU,MAAM,mDAAmD,GAAG,OAAO,OAAO;AAAA,IAC9H,MAAM,OAAO;AAAA,EACf;AACF;","names":["terminal"]}
|
|
1
|
+
{"version":3,"sources":["../../src/launch-invariants/auth-lookup-cache.ts","../../src/launch-invariants/settlement.ts"],"sourcesContent":["/**\n * The last valid result of each auth lookup (API key, key owner, browser\n * session), served only while the store cannot answer.\n *\n * Every lookup reads the store first, so a revoked or expired credential is\n * refused as soon as the store says so, and that answer drops its entry. When\n * the store errors or stalls past the deadline, a valid result verified less\n * than the TTL ago is served instead: an overloaded D1 failed\n * API-key checks and session reads for requests whose credentials were valid\n * moments before (GTM #1488). The TTL counts from the last successful store\n * read and a served entry never renews it, so a credential revoked during an\n * outage lives at most the TTL past its last verification. Entries are per\n * isolate; revoking or rotating a key must also drop its entry here.\n *\n * The cache serves the verified value itself, never a copy: GTM keyed a\n * WeakMap on the verified key object, a copy missed it, and operator requests\n * answered 401 (GTM #1492).\n */\n\n/** Longest a verified result may be served while the store cannot answer. A larger configured TTL is capped here. */\nexport const AUTH_LOOKUP_TTL_MS = 60_000\n/** A store read slower than this is treated as unavailable; a healthy D1 lookup answers in tens of milliseconds. */\nexport const AUTH_LOOKUP_DEADLINE_MS = 2_500\nconst MAX_ENTRIES = 2_000\n\n/** The store answered that the credential is not valid; never answered from the cache. */\nexport class AuthLookupRefused extends Error {}\n\ninterface Entry<V> {\n value: V\n until: number\n}\n\nexport interface AuthLookupOptions<V> {\n /** When the credential itself expires (Unix ms); the entry never outlives it. */\n expiresAt?: (value: V) => number | null | undefined\n}\n\nexport interface AuthLookupCache<V> {\n /**\n * Read through the store. `read` resolves the valid value or null, or throws\n * {@link AuthLookupRefused} (or a `Response`) when the store refuses; any\n * other failure, or no answer by the deadline, falls back to a fresh entry.\n * `key` must not be the secret: use {@link credentialCacheKey}.\n */\n lookup(key: string, read: () => Promise<V | null>, options?: AuthLookupOptions<V>): Promise<V | null>\n /** Drop every entry whose value matches, as when a key is revoked or rotated. */\n invalidate(matches: (value: V) => boolean): void\n /** Drop one entry by its key. */\n forget(key: string): void\n clear(): void\n /** The keys held, for a check that no secret is stored. */\n keys(): string[]\n}\n\nexport interface AuthLookupCacheOptions {\n /** Names the lookup in the warning logged when a cached result is served. */\n label: string\n /** Capped at {@link AUTH_LOOKUP_TTL_MS}. */\n ttlMs?: number\n deadlineMs?: number\n now?: () => number\n warn?: (message: string, detail: Record<string, unknown>) => void\n}\n\nexport function createAuthLookupCache<V>(options: AuthLookupCacheOptions): AuthLookupCache<V> {\n const ttlMs = Math.min(options.ttlMs ?? AUTH_LOOKUP_TTL_MS, AUTH_LOOKUP_TTL_MS)\n const deadlineMs = options.deadlineMs ?? AUTH_LOOKUP_DEADLINE_MS\n const now = options.now ?? (() => Date.now())\n const warn = options.warn ?? ((message, detail) => console.warn(message, detail))\n const entries = new Map<string, Entry<V>>()\n\n return {\n async lookup(key, read, lookupOptions) {\n let value: V | null\n try {\n value = await withDeadline(read(), deadlineMs)\n } catch (error) {\n if (error instanceof AuthLookupRefused || error instanceof Response) {\n entries.delete(key)\n throw error\n }\n const entry = entries.get(key)\n if (entry && now() < entry.until) {\n warn(`[auth-cache] ${options.label}: served the last valid result while the store was unavailable`, {\n error: error instanceof Error ? error.message : String(error),\n remainingMs: entry.until - now(),\n })\n return entry.value\n }\n entries.delete(key)\n throw error\n }\n if (value === null) {\n entries.delete(key)\n return null\n }\n const expiresAt = lookupOptions?.expiresAt?.(value)\n const until = Math.min(now() + ttlMs, typeof expiresAt === 'number' && expiresAt > 0 ? expiresAt : Number.POSITIVE_INFINITY)\n entries.delete(key)\n entries.set(key, { value, until })\n if (entries.size > MAX_ENTRIES) entries.delete(entries.keys().next().value!)\n return value\n },\n invalidate(matches) {\n for (const [key, entry] of entries) if (matches(entry.value)) entries.delete(key)\n },\n forget(key) {\n entries.delete(key)\n },\n clear() {\n entries.clear()\n },\n keys() {\n return [...entries.keys()]\n },\n }\n}\n\n/** A credential's cache key: its SHA-256 in hex, so the cache never holds the secret. */\nexport async function credentialCacheKey(secret: string): Promise<string> {\n const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(secret))\n return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, '0')).join('')\n}\n\nfunction withDeadline<T>(promise: Promise<T>, ms: number): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined\n const deadline = new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(new Error(`auth lookup did not answer within ${ms} ms`)), ms)\n })\n return Promise.race([promise, deadline]).finally(() => clearTimeout(timer))\n}\n","/**\n * Honest turn settlement, checked over a product's turn records.\n *\n * A turn ends in exactly one terminal state: an answer, a typed failure the\n * person can Retry, or a Stop the person chose, counted on its own. It gets\n * there within 15 minutes of its owner stopping. A failure belongs to the time\n * the turn was requested, not the time it was noticed, and how late it was\n * noticed is measured. A run that completed with a tool call the Sandbox\n * aborted stopped mid-work, so it is a failure.\n *\n * GTM held turns in five places (turn status, admissions,\n * Workflows, Sandbox sessions and the sidecar tracker) and they disagreed:\n * 51 stream rows stayed `running` after their producers died, failure notices\n * arrived 8–11 hours late, and completions with aborted tools counted as\n * answers. {@link checkTurnSettlement} reads one normalized record per turn,\n * however the product derives it, and names every turn that breaks the rule.\n */\nimport { LAUNCH_BUDGETS, type InvariantVerdict } from './catalog.js'\n\nexport type TurnTerminalState = 'answered' | 'failed' | 'stopped'\n\n/** One turn as its product records it, normalized. Times are Unix ms. */\nexport interface SettledTurnRecord {\n turnId: string\n /** When the request was accepted (the user message was saved). */\n requestedAt: number\n /** Every terminal state recorded for the turn, in order; exactly one is honest. */\n terminals: ReadonlyArray<{\n state: TurnTerminalState\n /** When the terminal state was recorded. */\n at: number\n /** A typed failure code, for `failed`. */\n code?: string\n /** Whether the person is offered Retry, for `failed`. */\n retryable?: boolean\n /** The time the failure is reported under; it must be the request time. */\n attributedTo?: number\n }>\n /** When the turn's owner stopped: for a leased stream, when its lease expired. Null while an owner holds it. */\n ownerEndedAt: number | null\n /** A completed run in which the Sandbox aborted a tool call. */\n abortedToolCall?: boolean\n}\n\nexport interface TurnSettlementCounts {\n turns: number\n answered: number\n failed: number\n stopped: number\n open: number\n /** Most minutes between an owner stopping and its turn's terminal state. */\n maxDetectionLagMinutes: number\n}\n\n/**\n * Check turn records against honest settlement at `now`.\n * A turn still open whose owner has not stopped is fine; one whose owner stopped\n * more than {@link LAUNCH_BUDGETS.settleWithinMs} ago is not.\n */\nexport function checkTurnSettlement(\n turns: readonly SettledTurnRecord[],\n options: { now: number; settleWithinMs?: number; subject?: string },\n): InvariantVerdict {\n const within = options.settleWithinMs ?? LAUNCH_BUDGETS.settleWithinMs\n const findings: string[] = []\n const counts: TurnSettlementCounts = { turns: turns.length, answered: 0, failed: 0, stopped: 0, open: 0, maxDetectionLagMinutes: 0 }\n for (const turn of turns) {\n const label = `turn ${turn.turnId}`\n if (turn.terminals.length > 1) {\n findings.push(`${label} has ${turn.terminals.length} terminal states (${turn.terminals.map((terminal) => terminal.state).join(' then ')}); a turn ends once`)\n }\n const terminal = turn.terminals[0]\n if (!terminal) {\n counts.open += 1\n if (turn.ownerEndedAt !== null && options.now - turn.ownerEndedAt > within) {\n findings.push(`${label} is still open ${minutes(options.now - turn.ownerEndedAt)} min after its owner stopped; the most is ${minutes(within)}`)\n }\n continue\n }\n counts[terminal.state] += 1\n if (turn.ownerEndedAt !== null) {\n const lag = terminal.at - turn.ownerEndedAt\n counts.maxDetectionLagMinutes = Math.max(counts.maxDetectionLagMinutes, minutes(lag))\n if (lag > within) findings.push(`${label} was settled ${minutes(lag)} min after its owner stopped; the most is ${minutes(within)}`)\n }\n if (terminal.state === 'answered' && turn.abortedToolCall) {\n findings.push(`${label} is counted as an answer, but the Sandbox aborted a tool call in it; it stopped mid-work and is a failure`)\n }\n if (terminal.state === 'failed') {\n if (!terminal.code) findings.push(`${label} failed without a typed failure code`)\n if (terminal.retryable !== true) findings.push(`${label} failed without offering Retry`)\n if (terminal.attributedTo !== undefined && terminal.attributedTo !== turn.requestedAt) {\n findings.push(`${label}'s failure is reported at ${new Date(terminal.attributedTo).toISOString()}, not its request time ${new Date(turn.requestedAt).toISOString()}`)\n }\n }\n if (terminal.state === 'stopped' && terminal.code && /fail|error/i.test(terminal.code)) {\n findings.push(`${label} was stopped by the person but carries failure code ${terminal.code}; a Stop is counted on its own`)\n }\n }\n return {\n invariant: 'honest-settlement',\n subject: options.subject ?? 'turns',\n pass: findings.length === 0,\n details: findings.length ? findings : [\n `${counts.turns} turns: ${counts.answered} answered, ${counts.failed} failed with Retry, ${counts.stopped} stopped, ${counts.open} held by a live owner`,\n `longest detection lag ${counts.maxDetectionLagMinutes} min`,\n ],\n data: { ...counts },\n }\n}\n\nfunction minutes(ms: number): number {\n return Math.round((ms / 60_000) * 10) / 10\n}\n\n/**\n * The failure shapes GTM shipped, as scenarios a product seeds\n * into its own storage, settles with its own scheduled jobs, and reads back as\n * {@link SettledTurnRecord}s. `expect` is the one honest terminal state.\n */\nexport interface SettlementScenario {\n id: string\n /** What happened to the turn, for the product's seed step. */\n story: string\n /** Minutes before the check's `now` that the request was accepted. */\n requestedMinutesAgo: number\n /**\n * Minutes before `now` that the owner stopped (for a stream, its lease\n * expired), or null for a live owner. Every scenario that stopped did so 12\n * minutes ago, so an app that settles within 15 minutes has settled it by `now`.\n */\n ownerEndedMinutesAgo: number | null\n expect: TurnTerminalState | 'open'\n}\n\nexport const SETTLEMENT_SCENARIOS: readonly SettlementScenario[] = [\n {\n id: 'orphaned-stream',\n story: 'The Worker streaming the turn died; its stream row is still running, no admission or Workflow holds it, and its 5-minute lease expired 12 minutes ago.',\n requestedMinutesAgo: 30,\n ownerEndedMinutesAgo: 12,\n expect: 'failed',\n },\n {\n id: 'abandoned-before-admission',\n story: 'The user message was saved 12 minutes ago, then the request died before any completion owner admitted the turn: no reply, no stream, no admission.',\n requestedMinutesAgo: 12,\n ownerEndedMinutesAgo: 12,\n expect: 'failed',\n },\n {\n id: 'runtime-restarted',\n story: 'The admitted run\\'s runtime restarted mid-turn 12 minutes ago: the session still reports running while its execution ledger failed the run (terminal event interrupted-done).',\n requestedMinutesAgo: 40,\n ownerEndedMinutesAgo: 12,\n expect: 'failed',\n },\n {\n id: 'completed-with-aborted-tool',\n story: 'The run reported completed 12 minutes ago, but a tool part ended with \"Tool execution aborted\".',\n requestedMinutesAgo: 20,\n ownerEndedMinutesAgo: 12,\n expect: 'failed',\n },\n {\n id: 'user-stop',\n story: 'The person pressed Stop 12 minutes ago while the turn ran.',\n requestedMinutesAgo: 20,\n ownerEndedMinutesAgo: 12,\n expect: 'stopped',\n },\n {\n id: 'answered',\n story: 'The turn answered normally 12 minutes ago.',\n requestedMinutesAgo: 20,\n ownerEndedMinutesAgo: 12,\n expect: 'answered',\n },\n {\n id: 'live-long-turn',\n story: 'A long turn is still running under an owner that renews its lease.',\n requestedMinutesAgo: 90,\n ownerEndedMinutesAgo: null,\n expect: 'open',\n },\n]\n\n/**\n * Check a product's settlement of {@link SETTLEMENT_SCENARIOS}: each scenario's\n * record ends in its expected state, and all of them settle honestly. The\n * product seeds each scenario at `now`, runs its own recovery and settlement\n * jobs at `now`, and reads the records back keyed by scenario id.\n */\nexport function checkSettlementScenarios(\n records: Readonly<Record<string, SettledTurnRecord | undefined>>,\n options: { now: number; scenarios?: readonly SettlementScenario[] },\n): InvariantVerdict {\n const scenarios = options.scenarios ?? SETTLEMENT_SCENARIOS\n const findings: string[] = []\n const present: SettledTurnRecord[] = []\n for (const scenario of scenarios) {\n const record = records[scenario.id]\n if (!record) {\n findings.push(`scenario ${scenario.id}: no turn record was read back`)\n continue\n }\n present.push(record)\n const state = record.terminals[0]?.state ?? 'open'\n if (state !== scenario.expect) findings.push(`scenario ${scenario.id}: ended ${state}, expected ${scenario.expect} (${scenario.story})`)\n }\n const honest = checkTurnSettlement(present, { now: options.now, subject: 'settlement scenarios' })\n if (!honest.pass) findings.push(...honest.details)\n return {\n invariant: 'honest-settlement',\n subject: 'settlement scenarios',\n pass: findings.length === 0,\n details: findings.length ? findings : [`${scenarios.length} failure scenarios settle to their honest state`, ...honest.details],\n data: honest.data,\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoBO,IAAM,qBAAqB;AAE3B,IAAM,0BAA0B;AACvC,IAAM,cAAc;AAGb,IAAM,oBAAN,cAAgC,MAAM;AAAC;AAuCvC,SAAS,sBAAyB,SAAqD;AAC5F,QAAM,QAAQ,KAAK,IAAI,QAAQ,SAAS,oBAAoB,kBAAkB;AAC9E,QAAM,aAAa,QAAQ,cAAc;AACzC,QAAM,MAAM,QAAQ,QA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AAqB,CAAC;AAC5B,QAAM,UAA+B,CAAC;AACtC,aAAW,YAAY,WAAW;AAChC,UAAM,SAAS,QAAQ,SAAS,EAAE;AAClC,QAAI,CAAC,QAAQ;AACX,eAAS,KAAK,YAAY,SAAS,EAAE,gCAAgC;AACrE;AAAA,IACF;AACA,YAAQ,KAAK,MAAM;AACnB,UAAM,QAAQ,OAAO,UAAU,CAAC,GAAG,SAAS;AAC5C,QAAI,UAAU,SAAS,OAAQ,UAAS,KAAK,YAAY,SAAS,EAAE,WAAW,KAAK,cAAc,SAAS,MAAM,KAAK,SAAS,KAAK,GAAG;AAAA,EACzI;AACA,QAAM,SAAS,oBAAoB,SAAS,EAAE,KAAK,QAAQ,KAAK,SAAS,uBAAuB,CAAC;AACjG,MAAI,CAAC,OAAO,KAAM,UAAS,KAAK,GAAG,OAAO,OAAO;AACjD,SAAO;AAAA,IACL,WAAW;AAAA,IACX,SAAS;AAAA,IACT,MAAM,SAAS,WAAW;AAAA,IAC1B,SAAS,SAAS,SAAS,WAAW,CAAC,GAAG,UAAU,MAAM,mDAAmD,GAAG,OAAO,OAAO;AAAA,IAC9H,MAAM,OAAO;AAAA,EACf;AACF;","names":["terminal"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Alarms that fire at 80% of a platform limit, before the limit fails a customer.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
4
|
+
* GTM recorded 19 platform-limit events (Worker memory, D1,
|
|
5
5
|
* sandbox disk, snapshot count, key rate) and learned of each one after it had
|
|
6
6
|
* failed someone. Each resource here has a declared limit; an observation at
|
|
7
7
|
* or above 80% of it delivers a warning, and at or above the limit a critical
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* Pasted code reaches the chat.
|
|
3
3
|
*
|
|
4
4
|
* People paste commands, SQL and markup into a chat with an agent that runs
|
|
5
|
-
* code; that is the product.
|
|
5
|
+
* code; that is the product. A chat message containing
|
|
6
6
|
* `cat /etc/passwd` sent to gtm.tangle.tools got Cloudflare's 403 "Attention
|
|
7
7
|
* Required" page instead of the app's own answer: a managed WAF rule matched
|
|
8
8
|
* the text before the request reached the Worker. These samples are what a
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Scheduled jobs that cannot take each other down.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
4
|
+
* GTM's turn health ran out of memory while the hourly
|
|
5
5
|
* sweeps shared one scheduled run, and none of the eight queued after it ran.
|
|
6
6
|
* Here each scheduled invocation runs exactly one job. A cron can carry a
|
|
7
7
|
* minute list (`0,1,2 * * * *`) with one job per minute, so a Worker keeps a
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
* noticed is measured. A run that completed with a tool call the Sandbox
|
|
9
9
|
* aborted stopped mid-work, so it is a failure.
|
|
10
10
|
*
|
|
11
|
-
*
|
|
11
|
+
* GTM held turns in five places (turn status, admissions,
|
|
12
12
|
* Workflows, Sandbox sessions and the sidecar tracker) and they disagreed:
|
|
13
13
|
* 51 stream rows stayed `running` after their producers died, failure notices
|
|
14
14
|
* arrived 8–11 hours late, and completions with aborted tools counted as
|
|
@@ -59,7 +59,7 @@ export declare function checkTurnSettlement(turns: readonly SettledTurnRecord[],
|
|
|
59
59
|
subject?: string;
|
|
60
60
|
}): InvariantVerdict;
|
|
61
61
|
/**
|
|
62
|
-
* The failure shapes GTM shipped
|
|
62
|
+
* The failure shapes GTM shipped, as scenarios a product seeds
|
|
63
63
|
* into its own storage, settles with its own scheduled jobs, and reads back as
|
|
64
64
|
* {@link SettledTurnRecord}s. `expect` is the one honest terminal state.
|
|
65
65
|
*/
|