/** * Opt-in live MODEL evaluation of multi-step browser tasks. Not a unit test and not part of CI. * * A real model drives the production browser MCP entry (list_tools / call_tool) against a real * headless Chrome through the browser runtime, on local fixture pages served by this script. * A = the browser tool layer at --baseline-ref; C = the current working tree. * Every run gets fresh random answers, variants are interleaved, and every run is kept (no picking). * Reported per variant and task: pass rate, model turns, browser tool calls, cost, wall time. * * The model is driven by the local `claude` CLI in print mode with its own sign-in; this script * reads no credentials. Each run costs real usage, so it only starts with --live. * * Usage: * node --import tsx scripts/eval-browser-tasks.mjs --live --baseline-ref origin/main \ * [--model claude-sonnet-5-5] [--effort medium] [--repeats 3] [--only form,vault] [--variants A,C] [--parallel 3] * --effort is passed to the CLI as its reasoning effort; without it the CLI default applies. * --real-sites adds eight read tasks on public websites (GitHub, crates.io, PyPI, Hacker News search, * Tailscale docs, Apple support, Wikipedia). Their answers are fetched from the sites' public APIs and * pages right before the runs. They need the network, depend on what those sites serve that day and * can be refused by a site; treat a failure there as a reason to look, not as a regression by itself. * node --import tsx scripts/eval-browser-tasks.mjs --check * No model and no usage: drives batch and cdp through the MCP entry on the same real browser and * fixture pages, and fails if a result is wrong. Run it after touching either action. * node --import tsx scripts/eval-browser-tasks.mjs --serve * Only serves the fixture pages and prints their address, one run id, its prompts and answers, for trying * the sidebar and "My browser" by hand from a running Cindy. /__state?run= shows what the * pages recorded. * * Limits: the dedicated-browser runtime only (no sidebar, no "My browser"), fixture pages rather * than real sites, one harness (Claude Code print mode with only the browser tools). Results are * evidence for the changed paths, not a general success rate. */ import fs from 'node:fs/promises'; import { appendFileSync, readFileSync } from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import net from 'node:net'; import { createServer as createHttpServer } from 'node:http'; import { execFileSync, spawn } from 'node:child_process'; import { randomBytes, randomInt } from 'node:crypto'; import { parseArgs } from 'node:util'; import { fileURLToPath, pathToFileURL } from 'node:url'; const { values } = parseArgs({ options: { live: { type: 'boolean' }, mcp: { type: 'boolean' }, check: { type: 'boolean' }, serve: { type: 'boolean' }, 'baseline-ref': { type: 'string' }, model: { type: 'string', default: 'claude-sonnet-5-5' }, effort: { type: 'string' }, repeats: { type: 'string', default: '3' }, only: { type: 'string' }, variants: { type: 'string', default: 'A,C' }, parallel: { type: 'string', default: '3' }, 'real-sites': { type: 'boolean' }, variant: { type: 'string' }, 'runtime-dir': { type: 'string' }, trace: { type: 'string' }, 'cdp-port': { type: 'string' }, } }); const root = fileURLToPath(new URL('..', import.meta.url)); const browserDir = 'packages/lizi-mcps/src/browser'; // --------------------------------------------------------------------------------------------- // MCP child: one variant of the production browser MCP server over stdio, on its own headless Chrome. // --------------------------------------------------------------------------------------------- if (values.mcp) { process.env.XDT_BROWSER_RUNTIME_DIR = values['runtime-dir']; const { createServer } = await import('vite'); const { StdioServerTransport } = await import('@modelcontextprotocol/sdk/server/stdio.js'); const baseline = new Map(); if (values.variant === 'A') { const changed = execFileSync('git', ['diff', '--name-only', values['baseline-ref'], '--', browserDir], { cwd: root, encoding: 'utf8' }) .split('\n').filter(Boolean); for (const file of changed) { try { baseline.set(path.join(root, file), execFileSync('git', ['show', `${values['baseline-ref']}:${file}`], { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] })); } catch { /* New in the working tree: the baseline never imports it. */ } } } const vite = await createServer({ root, configFile: false, logLevel: 'silent', appType: 'custom', optimizeDeps: { noDiscovery: true, include: [], entries: [] }, server: { middlewareMode: true, watch: null, hmr: false, ws: false }, ssr: { noExternal: [/^@cindy\//, /^@jackwener\//] }, plugins: [{ name: 'evaluation-baseline-source', enforce: 'pre', load(id) { const [file, query] = id.split('?'); if (!baseline.has(file)) return undefined; return query === 'raw' ? `export default ${JSON.stringify(baseline.get(file))}` : baseline.get(file); } }], }); const { createBrowserMcpServer } = await vite.ssrLoadModule(`/${browserDir}/server.ts`); const { createBrowserControlRuntime } = await import(pathToFileURL(path.join(root, 'packages/browser-control-runtime/src/runtime.ts')).href); const runtime = createBrowserControlRuntime({ config: { browser: { enabled: true, headless: true, defaultProfile: 'eval', profiles: { eval: { cdpPort: Number(values['cdp-port']), color: '#00D9C5' } }, ssrfPolicy: { dangerouslyAllowPrivateNetwork: true } } }, logSink: () => {}, }); const traced = { call: async (request) => { const started = performance.now(); const result = await runtime.call(request); appendFileSync(values.trace, `${JSON.stringify({ action: request.action, kind: request.request?.kind, method: request.recipeCommand?.method, ok: result.ok, ms: Math.round(performance.now() - started) })}\n`); return result; } }; await runtime.call({ action: 'start' }); const server = createBrowserMcpServer({ getRuntime: () => traced, getBackendKind: () => 'external', resolveScreenshot: async (result) => { const data = result.data ?? {}; const buffer = typeof data.data === 'string' ? Buffer.from(data.data, 'base64') : await fs.readFile(data.path); return { buffer, mimeType: buffer[0] === 0xff ? 'image/jpeg' : 'image/png' }; }, }); let closing = false; const shutdown = async () => { if (closing) return; closing = true; await runtime.call({ action: 'stop' }).catch(() => {}); await vite.close().catch(() => {}); process.exit(0); }; process.stdin.on('end', shutdown); process.stdin.on('close', shutdown); process.on('SIGTERM', shutdown); process.on('SIGINT', shutdown); await server.connect(new StdioServerTransport()); await new Promise(() => {}); } // --------------------------------------------------------------------------------------------- // Driver // --------------------------------------------------------------------------------------------- const repeats = Number(values.repeats); const parallel = Number(values.parallel); if (!values.check && !values.serve && (!values.live || !values['baseline-ref'] || !Number.isInteger(repeats) || repeats < 1 || !Number.isInteger(parallel) || parallel < 1)) { throw new Error('Require --check, --serve, or --live with --baseline-ref and positive --repeats / --parallel'); } const variants = values.variants.split(','); if (variants.some((variant) => !['A', 'C'].includes(variant))) throw new Error('Invalid --variants'); const token = (prefix) => `${prefix}-${randomBytes(4).toString('hex').toUpperCase()}`; const page = (title, body) => `${title}

${title}

${body}`; const PRODUCTS = ['Alpha Lamp', 'Birch Stool', 'Cobalt Desk', 'Dune Rug', 'Echo Chair', 'Fern Planter', 'Garnet Shelf', 'Harbor Clock']; const PEOPLE = ['Abara', 'Bianchi', 'Castillo', 'Dvorak', 'Eriksen', 'Fontaine', 'Gupta', 'Haddad', 'Ivanov', 'Jensen', 'Kowalski', 'Lindqvist', 'Moreau', 'Nakamura', 'Okafor', 'Petrov', 'Quintero', 'Rossi', 'Sato', 'Tanaka', 'Usman', 'Varga', 'Weber', 'Xu', 'Yilmaz', 'Zhou']; /** Per-run answers and what the pages recorded; the checks read only this and the final reply. */ const runs = new Map(); function newRun() { const id = randomBytes(6).toString('hex'); const refundedIndex = 18 + randomInt(6); // page 4 of 5 const state = { id, form: { note: token('NOTE'), code: token('CONF'), submitted: null }, skus: Object.fromEntries(PRODUCTS.map((name) => [name, token('SKU')])), orders: Array.from({ length: 30 }, (_, index) => ({ id: token('ORD'), amount: `${randomInt(20, 900)}.${String(randomInt(100)).padStart(2, '0')}`, status: index === refundedIndex ? 'REFUNDED' : ['PAID', 'SHIPPED', 'PENDING'][index % 3] })), vault: token('VAULT'), badge: { employee: `E-${randomInt(10000, 99999)}`, pin: String(randomInt(1000, 9999)), code: token('BADGE'), submitted: null }, report: `${randomInt(10, 99)},${String(randomInt(1000)).padStart(3, '0')}`, settings: { receipt: token('RCPT'), saved: null }, support: token('SUP'), extensions: Object.fromEntries(PEOPLE.map((name) => [name, String(randomInt(2000, 9999))])), late: token('LOT'), spinner: token('DOCK'), manual: { days: randomInt(31, 400) }, status: token('BUILD'), }; runs.set(id, state); return state; } function readBody(req) { return new Promise((resolve) => { let data = ''; req.on('data', (chunk) => { data += chunk; }); req.on('end', () => resolve(data)); }); } async function handle(req, res, ports) { const url = new URL(req.url, 'http://fixture'); const state = runs.get(url.searchParams.get('run') ?? ''); const send = (body, type = 'text/html; charset=utf-8', status = 200) => { res.writeHead(status, { 'content-type': type, 'cache-control': 'no-store' }); res.end(body); }; if (!state) return send('unknown run', 'text/plain', 404); const q = `run=${state.id}`; if (values.serve && url.pathname === '/__state') return send(JSON.stringify(state), 'application/json'); switch (url.pathname) { case '/form': return send(page('Create account', `
Region${['EU', 'US', 'APAC'].map((region) => ``).join('')}
`)); case '/form/submit': { state.form.submitted = Object.fromEntries(new URLSearchParams(await readBody(req))); return send(page('Account created', `

Thanks, ${state.form.submitted.name ?? ''}. Your confirmation code is ${state.form.code}.

`)); } case '/catalog': return send(page('Catalog', ``)); case '/product': { const name = PRODUCTS[Number(url.searchParams.get('p'))]; if (!name) return send('no such product', 'text/plain', 404); return send(page(name, `
SKU
${state.skus[name]}
Stock
${randomInt(1, 60)} units

Back to catalog

`)); } case '/orders': return send(page('Orders', `
OrderAmountStatus

`)); case '/orders/data': { const pageNo = Math.max(1, Math.min(5, Number(url.searchParams.get('page')) || 1)); return send(JSON.stringify(state.orders.slice((pageNo - 1) * 6, pageNo * 6)), 'application/json'); } case '/vault': return send(page('Vault', `

The access code is shown after pressing the button in the panel below.

`)); case '/vault.js': return send(`customElements.define('vault-box', class extends HTMLElement { connectedCallback() { const root = this.attachShadow({ mode: 'closed' }); root.innerHTML = '

'; root.querySelector('button').addEventListener('click', async (event) => { if (!event.isTrusted) return; const reply = await fetch('/vault/code?${q}', { method: 'POST' }); root.querySelector('p').textContent = 'Access code: ' + await reply.text(); }); } });`, 'text/javascript'); case '/vault/code': return req.method === 'POST' ? send(state.vault, 'text/plain') : send('method not allowed', 'text/plain', 405); case '/badge': return send(page('Badge desk', `

Fill in the panel below to issue a visitor badge.

`)); case '/badge.js': return send(`customElements.define('badge-form', class extends HTMLElement { connectedCallback() { const root = this.attachShadow({ mode: 'closed' }); root.innerHTML = '

'; root.querySelector('button').addEventListener('click', async (event) => { if (!event.isTrusted) return; const body = { employee: root.querySelector('#employee').value, pin: root.querySelector('#pin').value }; const reply = await fetch('/badge/issue?${q}', { method: 'POST', body: JSON.stringify(body) }); root.querySelector('p').textContent = await reply.text(); }); } });`, 'text/javascript'); case '/badge/issue': { state.badge.submitted = JSON.parse(await readBody(req) || '{}'); const ok = state.badge.submitted.employee === state.badge.employee && state.badge.submitted.pin === state.badge.pin; return send(ok ? `Badge issued: ${state.badge.code}` : 'Rejected: employee ID or PIN does not match.', 'text/plain'); } case '/report': return send(page('Quarterly report', `

`)); case '/report/data': return setTimeout(() => send(state.report, 'text/plain'), 2500); case '/settings': return send(page('Workspace', `

`)); case '/settings/save': state.settings.saved = JSON.parse(await readBody(req) || '{}'); return send(state.settings.receipt, 'text/plain'); case '/embed': return send(page('Help center', `

Your support panel is embedded below.

`)); case '/panel': return send(page('Support panel', `

Support code: ${state.support}

`)); // Pages that are read, not operated. `late` is empty until its data arrives (a page rendered from // scripts, like crates.io); `spinner` shows a placeholder meanwhile (like a search page before its // results); `manual` is longer than one read returns; `status.json` is not HTML at all. case '/late': return send(page('Dispatch board', `
`)); case '/late/data': return send(JSON.stringify({ lot: state.late }), 'application/json'); case '/spinner': return send(page('Dock assignments', `

Loading assignments…

`)); case '/spinner/data': return send(JSON.stringify({ dock: state.spinner }), 'application/json'); case '/manual': { const filler = 'Operators confirm each handover in the shift log before leaving the floor. Deviations are reported to the duty lead, who decides whether the line pauses. Checklists are reviewed weekly and revised when a step no longer matches the equipment in use. '; const names = ['Scope', 'Roles', 'Access', 'Shifts', 'Handover', 'Labelling', 'Storage', 'Cleaning', 'Incidents', 'Audits', 'Training', 'Visitors', 'Equipment', 'Calibration', 'Waste', 'Alarms', 'Evacuation', 'First aid', 'Deliveries', 'Returns', 'Quarantine', 'Sampling', 'Records', 'Retention', 'Disposal', 'Suppliers', 'Complaints', 'Changes', 'Reviews', 'Contacts']; return send(page('Operations manual', names.map((name, index) => `

${index + 1}. ${name}

${filler.repeat(2)}${ name === 'Retention' ? `Shift logs and inspection records are retained for ${state.manual.days} days, then destroyed. ` : ''}${filler}

`).join(''))); } case '/status.json': return send(JSON.stringify({ service: 'dispatch', healthy: true, build: state.status, regions: ['eu', 'us', 'apac'] }, null, 2), 'application/json'); // A cross-site iframe that runs a worker: what a reCAPTCHA widget leaves behind on a real page. case '/desk': return send(page('Service desk', `

The desk widget is embedded below.

`)); case '/desk-panel': return send(page('Desk widget', `

starting

`)); case '/desk-worker.js': return send('postMessage(1);setInterval(()=>{},1000);', 'text/javascript'); case '/directory': return send(page('Staff directory', ` `)); case '/directory/search': { const needle = (url.searchParams.get('q') ?? '').toLowerCase(); return send(JSON.stringify(needle.length < 2 ? [] : PEOPLE.filter((name) => name.toLowerCase().includes(needle)).map((name) => ({ name, ext: state.extensions[name] }))), 'application/json'); } default: return send('not found', 'text/plain', 404); } } const listen = (server) => new Promise((resolve) => server.listen(0, '127.0.0.1', () => resolve(server.address().port))); const freePort = async () => { const probe = net.createServer(); const port = await listen(probe); await new Promise((resolve) => probe.close(resolve)); return port; }; const ports = {}; const servers = [createHttpServer((req, res) => handle(req, res, ports).catch(() => { res.statusCode = 500; res.end(); })), createHttpServer((req, res) => handle(req, res, ports).catch(() => { res.statusCode = 500; res.end(); }))]; ports.main = await listen(servers[0]); ports.frame = await listen(servers[1]); const base = `http://127.0.0.1:${ports.main}`; /** * Read tasks on public websites, only with --real-sites. The expected answers come from each site's own * public API or page, fetched now, so a task is never judged against a value that has since changed. A * task whose answer cannot be established is left out and named, rather than run and judged by guesswork. */ async function realSiteTasks() { if (!values['real-sites'] || values.check || values.serve || values.mcp) return []; const get = async (url, as = 'json') => { const response = await fetch(url, { headers: { 'User-Agent': 'cindy-browser-eval' }, signal: AbortSignal.timeout(20_000) }); if (!response.ok) throw new Error(`${response.status} for ${url}`); return as === 'json' ? response.json() : response.text(); }; const version = (tag) => (String(tag).match(/\d+(?:\.\d+)+/) ?? [String(tag)])[0]; const cells = (row) => [...row.matchAll(/]*>(.*?)<\/t[dh]>/gs)] .map((cell) => cell[1].replace(/<[^>]+>/g, ' ').replace(/ | /g, ' ').replace(/\s+/g, ' ').trim()); const repos = ['cli/cli', 'astral-sh/uv', 'denoland/deno', 'oven-sh/bun']; const candidates = [ { id: 'gh-releases', prompt: '用浏览器查这四个 GitHub 仓库各自最新 release 的版本号:cli/cli、astral-sh/uv、denoland/deno、oven-sh/bun(看各自的 /releases/latest 页面),列给我。', truth: async () => Promise.all(repos.map(async (name) => version((await get(`https://api.github.com/repos/${name}/releases/latest`)).tag_name))), check: (versions, final) => versions.every((item) => final.includes(item)) }, { id: 'gh-pr', prompt: '在 GitHub 的 cli/cli 仓库里,找出标题包含 attestation 的已合并 PR 中创建时间最早的一个,告诉我它的编号和标题。', truth: async () => String((await get('https://api.github.com/search/issues?q=repo:cli/cli+is:pr+is:merged+attestation+in:title&sort=created&order=asc&per_page=1')).items[0].number), check: (number, final) => new RegExp(`(^|\\D)${number}(\\D|$)`).test(final) }, { id: 'crates', prompt: '打开 https://crates.io/crates/serde ,告诉我 serde 当前的最新版本号。', truth: async () => (await get('https://crates.io/api/v1/crates/serde')).crate.max_stable_version, check: (latest, final) => final.includes(latest) }, { id: 'pypi', prompt: '打开 https://pypi.org/project/requests/ ,告诉我 requests 当前的最新版本号和它的发布日期。', truth: async () => (await get('https://pypi.org/pypi/requests/json')).info.version, check: (latest, final) => final.includes(latest) }, { id: 'hn', prompt: '用 Hacker News 搜索(https://hn.algolia.com)找到 Dropbox 当年发的帖子 "My YC app: Dropbox - Throw away your USB drive",告诉我发帖人的用户名和这个帖子的得分(points)。', truth: async () => (await get('https://hn.algolia.com/api/v1/items/8863')).author, check: (author, final) => final.toLowerCase().includes(String(author).toLowerCase()) }, { id: 'tailscale', prompt: '从 Tailscale 文档首页 https://tailscale.com/kb 出发,找到 tailscale up 命令的说明页,告诉我 --netfilter-mode 支持哪几个取值、默认值是什么。', truth: async () => { if (!(await get('https://tailscale.com/kb/1241/tailscale-up', 'text')).includes('nodivert')) throw new Error('the page no longer names nodivert'); return 'nodivert'; }, check: (value, final) => final.includes(value) }, { id: 'apple', prompt: '打开 https://support.apple.com/en-us/100100 (Apple security releases),告诉我表格里最新的一条(第一行)是哪个更新、发布日期是哪天。', truth: async () => { const row = [...(await get('https://support.apple.com/en-us/100100', 'text')).matchAll(/]*>(.*?)<\/tr>/gs)][1][1]; const versions = cells(row)[0].match(/\d+(?:\.\d+)+/g); if (!versions?.length) throw new Error('no version in the first row'); return versions; }, check: (versions, final) => versions.every((item) => final.includes(item)) }, { id: 'wiki', prompt: '打开 https://en.wikipedia.org/wiki/List_of_tallest_buildings ,在 "Tallest buildings in the world" 那张排名表里,排第 14 的建筑叫什么、有多高(米)?', truth: async () => { const rows = [...(await get('https://en.wikipedia.org/wiki/List_of_tallest_buildings', 'text')).matchAll(/]*>(.*?)<\/tr>/gs)].map((row) => cells(row[1])); const row = rows.find((item) => item[0] === '14' && /^[\d.,]+$/.test(item[2] ?? '')); if (!row) throw new Error('rank 14 not found'); return row[2]; }, check: (metres, final) => final.includes(metres) }, ]; const tasks = []; for (const candidate of candidates) { try { const truth = await candidate.truth(); tasks.push({ id: candidate.id, focus: 'real-site', prompt: () => candidate.prompt, check: (_state, final) => candidate.check(truth, final), truth }); } catch (error) { console.error(`real-site task ${candidate.id} left out: its answer could not be established (${error?.message ?? error})`); } } return tasks; } /** What each task asks and how it is judged. `sequence` marks the paths this change targets; the rest are controls. */ const TASKS = [ { id: 'form', focus: 'sequence', prompt: (s) => `打开 ${base}/form?run=${s.id} ,用下面的信息填表并提交:姓名 Ada Lovelace,邮箱 ada@example.test,套餐 Team,席位 7,地区 APAC,勾选订阅产品更新,备注填 ${s.form.note}。然后告诉我提交后页面显示的确认码。`, check: (s, final) => final.includes(s.form.code) && !!s.form.submitted && s.form.submitted.name === 'Ada Lovelace' && s.form.submitted.email === 'ada@example.test' && s.form.submitted.plan === 'Team' && s.form.submitted.seats === '7' && s.form.submitted.region === 'APAC' && s.form.submitted.newsletter === 'yes' && s.form.submitted.notes === s.form.note }, { id: 'catalog', focus: 'sequence', prompt: (s) => `打开 ${base}/catalog?run=${s.id} ,查出 Alpha Lamp、Cobalt Desk、Echo Chair、Garnet Shelf 这四件商品各自的 SKU(SKU 只在商品详情页上),列给我。`, check: (s, final) => ['Alpha Lamp', 'Cobalt Desk', 'Echo Chair', 'Garnet Shelf'].every((name) => final.includes(s.skus[name])) }, { id: 'orders', focus: 'sequence', prompt: (s) => `打开 ${base}/orders?run=${s.id} ,订单表分 5 页。找出状态是 REFUNDED 的那一单,告诉我订单号和金额。`, check: (s, final) => { const order = s.orders.find((item) => item.status === 'REFUNDED'); return final.includes(order.id) && final.includes(order.amount); } }, { id: 'report', focus: 'sequence', prompt: (s) => `打开 ${base}/report?run=${s.id} ,生成报告,告诉我报告里的 Total 是多少。`, check: (s, final) => final.includes(s.report) }, { id: 'settings', focus: 'sequence', prompt: (s) => `打开 ${base}/settings?run=${s.id} ,从 More 菜单进入通知设置:关掉 Email notifications,打开 Weekly digest,Frequency 改成 Monthly,保存。告诉我保存后显示的回执号。`, check: (s, final) => final.includes(s.settings.receipt) && !!s.settings.saved && s.settings.saved.email === false && s.settings.saved.digest === true && s.settings.saved.sms === false && s.settings.saved.frequency === 'Monthly' }, { id: 'vault', focus: 'escape-hatch', prompt: (s) => `打开 ${base}/vault?run=${s.id} ,按页面上的按钮显示访问码,告诉我访问码是多少。`, check: (s, final) => final.includes(s.vault) }, { id: 'badge', focus: 'escape-hatch', prompt: (s) => `打开 ${base}/badge?run=${s.id} ,在页面的面板里把 Employee ID 填成 ${s.badge.employee}、Door PIN 填成 ${s.badge.pin},点 Issue badge,告诉我页面显示的 badge 编号。`, check: (s, final) => final.includes(s.badge.code) && s.badge.submitted?.employee === s.badge.employee && s.badge.submitted?.pin === s.badge.pin }, { id: 'iframe', focus: 'control', prompt: (s) => `打开 ${base}/embed?run=${s.id} ,页面里嵌入的支持面板显示的支持码是多少?`, check: (s, final) => final.includes(s.support) }, { id: 'directory', focus: 'control', prompt: (s) => `打开 ${base}/directory?run=${s.id} ,在通讯录里搜索 Okafor,告诉我这个人的分机号。`, check: (s, final) => final.includes(s.extensions.Okafor) }, // Reading (2026-11-12): added after a comparison on real sites showed what the tasks above cannot, // because their pages are complete the moment they are opened. { id: 'late', focus: 'read', prompt: (s) => `打开 ${base}/late?run=${s.id} ,告诉我看板上显示的下一个出库批次号。`, check: (s, final) => final.includes(s.late) }, { id: 'spinner', focus: 'read', prompt: (s) => `打开 ${base}/spinner?run=${s.id} ,告诉我 7 号进货车被分配到哪个月台。`, check: (s, final) => final.includes(s.spinner) }, { id: 'manual', focus: 'read', prompt: (s) => `读 ${base}/manual?run=${s.id} 这份操作手册,告诉我“Retention”一节规定记录保留多少天。`, check: (s, final) => new RegExp(`(^|\\D)${s.manual.days}(\\D|$)`).test(final) }, { id: 'status', focus: 'read', prompt: (s) => `读 ${base}/status.json?run=${s.id} ,告诉我其中的 build 号。`, check: (s, final) => final.includes(s.status) }, ...await realSiteTasks(), ].filter((task) => !values.only || values.only.split(',').includes(task.id)); if (!TASKS.length) throw new Error('No tasks selected'); if (values.serve) { const state = newRun(); console.log(JSON.stringify({ base, run: state.id, pages: ['form', 'catalog', 'orders', 'report', 'settings', 'vault', 'badge', 'embed', 'directory', 'late', 'spinner', 'manual', 'status.json'] .map((name) => `${base}/${name}?run=${state.id}`), state: `${base}/__state?run=${state.id}`, prompts: Object.fromEntries(TASKS.map((task) => [task.id, task.prompt(state)])), answers: state }, null, 2)); await new Promise(() => {}); } const out = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-browser-task-eval-')); // --------------------------------------------------------------------------------------------- // --check: no model. The working tree's batch and cdp against the real browser and fixture pages. // --------------------------------------------------------------------------------------------- if (values.check) { const { Client } = await import('@modelcontextprotocol/sdk/client/index.js'); const { StdioClientTransport } = await import('@modelcontextprotocol/sdk/client/stdio.js'); const trace = path.join(out, 'runtime-trace.jsonl'); await fs.writeFile(trace, ''); const client = new Client({ name: 'browser-task-check', version: '1' }); await client.connect(new StdioClientTransport({ command: process.execPath, args: ['--import', import.meta.resolve('tsx'), fileURLToPath(import.meta.url), '--mcp', '--variant', 'C', '--runtime-dir', path.join(out, 'runtime'), '--trace', trace, '--cdp-port', String(await freePort())], stderr: 'inherit' })); const browser = async (args) => JSON.parse((await client.callTool({ name: 'call_tool', arguments: { name: 'browser', args } })).content[0].text); const state = newRun(); const failures = []; const expect = (name, ok, detail) => { console.log(`${ok ? 'ok ' : 'FAIL'} ${name}`); if (!ok) failures.push({ name, detail }); }; const nodeId = (listing, label) => Number(listing.split('\n').find((line) => line.includes(label))?.match(/^\[(\d+)\]/)?.[1]); const refOf = (snapshot, label) => snapshot.split('\n').find((line) => line.includes(label))?.match(/\[ref=([^\]]+)\]/)?.[1]; try { const listed = JSON.parse((await client.callTool({ name: 'list_tools', arguments: { category: 'browser' } })).content[0].text); expect('rules are tailored and carry no markers', !listed.rules['browser-workflow'].includes('