Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(browser): 支持按需学习配方与大结果补读

Dashc0f0ef9c3ecb
diff --git a/apps/desktop/src/main/browser-recipes/__tests__/writer.test.ts b/apps/desktop/src/main/browser-recipes/__tests__/writer.test.ts
index 687369aa14..773a89ba04 100644
--- a/apps/desktop/src/main/browser-recipes/__tests__/writer.test.ts
+++ b/apps/desktop/src/main/browser-recipes/__tests__/writer.test.ts
@@ -13,6 +13,7 @@ vi.mock('electron', () => ({
const { writeUserRecipe, resetSiteRecipe } = await import('../writer.js');
const { loadUserBrowserRecipes } = await import('../loader.js');
+const { browserExperienceStore } = await import('../experience.js');
let dir: string;
beforeEach(async () => {
@@ -28,6 +29,21 @@ async function readBack(_site: string) {
}
describe('writeUserRecipe / resetSiteRecipe', () => {
+ // New local experience persistence, unit: a fresh host sees repetition without
+ // storing script/input values, and the existing site reset removes it too.
+ it('persists bounded structural observations across host instances and resets with the site', async () => {
+ const first = browserExperienceStore(dir);
+ const input = { site: 'experience.test', actions: ['navigate', 'extract'] as ['navigate', 'extract'] };
+ await first.record(input);
+ const second = browserExperienceStore(dir);
+ expect(await second.record(input)).toMatchObject({ ...input, observations: 2 });
+ expect(await second.list(input.site)).toHaveLength(1);
+ const raw = JSON.parse(await fs.readFile(path.join(dir, input.site, 'experience.json'), 'utf8'));
+ expect(Object.keys(raw[0]).sort()).toEqual(['actions', 'observations', 'site', 'updatedAt']);
+ await expect(second.record({ ...input, site: '../escape' })).rejects.toBeTruthy();
+ await resetSiteRecipe(input.site, dir);
+ expect(await second.list(input.site)).toEqual([]);
+ });
it('writes a recipe that reads back as a valid L2 entry', async () => {
const res = await writeUserRecipe(
{ site: 'x.com', recipe: { id: 'x-search', steps: [{ action: 'navigate', url: 'https://x.com/' }] } },
diff --git a/apps/desktop/src/main/browser-recipes/experience.ts b/apps/desktop/src/main/browser-recipes/experience.ts
new file mode 100644
index 0000000000..d780570559
--- /dev/null
+++ b/apps/desktop/src/main/browser-recipes/experience.ts
@@ -0,0 +1,38 @@
+import path from 'node:path';
+import { BrowserExperienceSchema, type BrowserExperienceStore } from '@cindy/mcps';
+import { atomicWriteFileSync, readAtomicFileSync } from '../utils/atomicWriteFile.js';
+
+/** Bounded local observations, alongside recipes; resetSiteRecipe removes both. */
+export function browserExperienceStore(dir: string): BrowserExperienceStore {
+ const file = (site: string) =>
+ path.join(dir, BrowserExperienceSchema.shape.site.parse(site), 'experience.json');
+ const read = (site: string) => {
+ const raw = readAtomicFileSync(file(site));
+ if (!raw) return [];
+ const parsed = BrowserExperienceSchema.array().max(32).safeParse(JSON.parse(raw));
+ return parsed.success ? parsed.data.filter((item) => item.site === site) : [];
+ };
+ return {
+ async list(site) {
+ return read(site);
+ },
+ async record(input) {
+ const next = BrowserExperienceSchema.parse({
+ ...input,
+ observations: 1,
+ updatedAt: Date.now(),
+ });
+ const existing = read(next.site);
+ const key = next.actions.join('/');
+ const previous = existing.find((item) => item.actions.join('/') === key);
+ next.observations = Math.min((previous?.observations ?? 0) + 1, 1_000_000);
+ // No await in read-modify-write: desktop's shared event loop owns this
+ // advisory cache. A separate app process can lose a count, never a recipe.
+ const entries = [...existing.filter((item) => item.actions.join('/') !== key), next].slice(
+ -32,
+ );
+ atomicWriteFileSync(file(next.site), JSON.stringify(entries));
+ return next;
+ },
+ };
+}
diff --git a/apps/desktop/src/main/mcp-integrations/browser.ts b/apps/desktop/src/main/mcp-integrations/browser.ts
index 22b9c6a71a..4491b69f47 100644
--- a/apps/desktop/src/main/mcp-integrations/browser.ts
+++ b/apps/desktop/src/main/mcp-integrations/browser.ts
@@ -24,8 +24,9 @@ import { genericOAuthSecretIo } from '../secrets/providerSecretStore.js';
import { createRecipeFileBroker } from './browser-backend/rsb-webview-upload-policy.js';
import { artifactSessionRoot } from './browser-backend/rsb-webview-artifacts.js';
import { extractBrowserAvailability, type BrowserAvailability } from './browser-availability.js';
-import { loadUserBrowserRecipes, type UserRecipesResult } from '../browser-recipes/loader.js';
+import { loadUserBrowserRecipes, userRecipesDir, type UserRecipesResult } from '../browser-recipes/loader.js';
import { writeUserRecipe, type WriteUserRecipeResult } from '../browser-recipes/writer.js';
+import { browserExperienceStore } from '../browser-recipes/experience.js';
import {
BrowserBackendController,
BrowserBackendHealthService,
@@ -461,6 +462,7 @@ function browserRecipeSecretId(key: string): string {
}
export function getBrowserMcpDeps(): {
+ experienceStore: NonNullable<BrowserMcpDeps['experienceStore']>;
getRuntime(): BrowserControlRuntime;
resolveScreenshot: NonNullable<BrowserMcpDeps['resolveScreenshot']>;
compressInlineImage: NonNullable<BrowserMcpDeps['compressInlineImage']>;
@@ -475,6 +477,7 @@ export function getBrowserMcpDeps(): {
pageReadsRestricted(target: { profile?: string; targetId?: string }): Promise<boolean>;
} {
return {
+ experienceStore: browserExperienceStore(userRecipesDir()),
recipeFiles: async (sessionId) => {
const sessionRoots = sessionId ? await resolveSessionUploadRoots(sessionId) : [];
const roots = sessionId ? [
diff --git a/docs/dev-rules/credentials-and-local-storage.md b/docs/dev-rules/credentials-and-local-storage.md
index 7171897018..fd05bbea2f 100644
--- a/docs/dev-rules/credentials-and-local-storage.md
+++ b/docs/dev-rules/credentials-and-local-storage.md
@@ -198,7 +198,8 @@ refresh 与 relay 自救节流。在途 refresh 尚未返回时收到的恢复
| ----------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Codex 包内 shell 入口 | `<userData>/codex-package/<版本>/codex-path/codex`,打包版 macOS/Linux 在 `getMaker()` 选定实际运行的 Codex 后由主进程原子写入,转发到同包的 `bin/codex`;只更新带 Cindy 标记的旧脚本,不覆盖外来文件。随旧版本目录整体删除,不含凭证。实现见 `agent-binaries/codex-cli-launcher.ts` |
| Cindy 管理的持久数据 | Desktop 使用 `app.getPath('userData')`,共享 package 由宿主注入等价根目录 |
-| 浏览器用户配方 | `userData/browser-recipes/<site>/recipes/<id 的 SHA-256>.json`,每站多个流程,原子替换;兼容旧 `recipe.json`,新文件优先。只保存配方定义及 active/suspended 状态,不保存试跑的 inputs/页面返回值;禁止写入凭据,业务变动值用 inputs。试跑凭证与单轮修复预算只在 MCP 会话内存中,暂停状态跨重启保留。 |
+| 浏览器用户配方与经验 | `userData/browser-recipes/<site>/recipes/<id 的 SHA-256>.json`,每站多个流程,原子替换;兼容旧 `recipe.json`,新文件优先。只保存参数化定义及 candidate/active/suspended 状态、浏览器 profile 范围,不保存试跑 inputs/页面返回值;禁止写入凭据,业务变动值用 inputs。同站 `experience.json` 最多保存 32 种操作形状(动作枚举、次数、时间),不保存 URL 路径/查询、选择器、脚本或输入输出;删除站点目录一并重置。重复形状仅提示当前 Agent 判断,不触发后台模型。试跑凭证与单轮修复预算只在 MCP 会话内存,暂停状态跨重启保留。 |
+| 浏览器大结果补读 | MCP 工具会话内存中保留最近四份原始 JSON,每份最多 200 万字符;不落盘、不上传,关闭会话后释放。`readResult` 只能读当前会话生成的引用,沿用原页面代输入读取限制;切换后端、stop 或读取受保护页面时清除。超过上限明确截断,不能声称完整原文已保存。 |
| 本机应用 Agent 授权 | `owners/<owner-key>/local-agent/grants.json`,仅含令牌 SHA-256、自报应用资料、账号范围和按授权归属的原生恢复绑定,不存令牌明文、供应商凭据或消息。复用原子写入与恢复 helper;profile 根 `local-agent/host.lock` 复用跨进程锁,保证一个发现端点和写入者。开发连接码从当前服务内存按需生成,不新增公共实例登记或短码映射文件。临时输入与新授权的 Codex 运行历史在同一 owner 下的 `local-agent/clients/<grant-hash>/`;撤权同时关闭执行及工具入口,不允许跨授权恢复。协议与旧版兼容见 [本机应用接入](../local-agent-api.md) |
| 预创建 worktree 的取消标记 | `userData/worktree-cancelled-creations/<sessionId 的 SHA-256>`,空文件原子排他创建;不含路径、草稿或关联密钥。保留以拒绝重启后迟到的创建请求,不按超时删除。只在核实未被任务认领后写入。同路径加 `.lock` 是可释放的跨进程操作锁,复用既有锁协议;同一 profile、同一任务的创建登记与取消回收串行,拿不到锁不得确认回收完成。异步创建完成后、登记前再次核对取消标记 |
| Mobile 已取消创建的草稿 | 复用账号隔离的 durable outbox;持久创建流程先保存草稿、原项目目录和附件,再登记 reservation 和发送远端 worktree 创建;创建回包前暂停发件箱投递。回收确认后,`creation.cancelled` 与原项目目录先持久写入,再忘记回收账本。重建使用新远端 ID,`storageSessionId` 保持原 AsyncStorage 键和附件目录,通过单次记录写入提交;写入失败时原草稿仍可读。编辑页恢复目录时重新探测资格,不沿用旧 worktree 的资格或分支偏好 |
diff --git a/packages/browser-control-runtime/upstream/MAINTAINING.md b/packages/browser-control-runtime/upstream/MAINTAINING.md
index 8f4030d9f9..498f32a725 100644
--- a/packages/browser-control-runtime/upstream/MAINTAINING.md
+++ b/packages/browser-control-runtime/upstream/MAINTAINING.md
@@ -199,12 +199,21 @@ pnpm --filter @cindy/browser-control-runtime test # 契约 + SSRF guard
### 配方按使用维护与等待条件(2026-10-23)
-- `recipe` 支持 `site + recipeDraft` 内存试跑;`saveRecipe` 仅接受同一 MCP 会话已通过验证的相同内容。正常检查不请求模型,不定时后台刷新;失败交给当前任务模型观察、同 id 一轮修订,失败回普通操作。修复预算为会话内状态,MCP 会话重建后重新计数;暂停状态写进配方,跨重启保留。
+- `recipe` 支持 `site + recipeDraft` 内存试跑;`saveRecipe` 通常接受同一 MCP 会话已通过验证的相同内容与 profile。新只读流程可用 `deferValidation:true` 保存 candidate(不能覆盖已有 id),下一次真实任务显式执行且 guard/expect 全部通过后转为 active;状态写入失败保留本次执行成功,不能重放。active 不证明未测参数组合。正常检查不请求模型,不定时后台刷新;失败交给当前任务模型观察、同 id 一轮修订,失败回普通操作。修复预算为会话内状态,MCP 会话重建后重新计数;暂停状态写进配方,跨重启保留。
- 新保存配方的交互/读取步骤须有完整 URL 和可选唯一可见 CSS 元素/文本 `guard`;末步 `expect` 检查数量、必需顶层字段与业务值。extract 将 guard 与读取合成同一次 evaluate;写动作前独立 guard,不能把它当事务或幂等保证。工具不重放步骤,后置失败须先核对写入是否已成功。
- 本地每站 `recipes/<id 的 SHA-256>.json` 支持多个流程,原子替换复用 Desktop 工具;loader 兼容 `recipe.json`、新文件优先。旧配方保留执行兼容,实际失败后暂停;新建/修订必须经过新验证。失败不把候选覆盖到正式配方。跨任务并发修改同一配方仍是最后写入优先,不新增锁/版本管理系统。
- `wait.fn` 补丁在 `sync.mjs`:host 只编译函数,页面执行;传真实 function 给 `waitForFunction`,避免函数源码被当 truthy、重复 eval 被 Trusted Types 拦截。timeout 放第三参数。异步 predicate 明确拒绝,避免 Promise 假成功;evaluate 仍支持 async。
- 验证入口:`recipe-runner.test.ts`、`browserMcpServer.test.ts`、Desktop browser-recipes tests、`interaction-proxy-policy.test.ts`;真实只读对照 `scripts/browser-live-recipe-compare.mjs` 的 `guarded` 模式与 `--maintenance-checks=true`。宿主运行版不会因源码修改自动更新。
+### 经验缓存与按需学习(2026-10-27)
+
+- `open/navigate` 随结果返回最多三条站点配方候选,可用 `intent` 进行本地词匹配;匹配仅建议,不执行。域名按边界匹配,profile 不匹配或 suspended 不建议;同任务同站点/意图/目录版本不重复提示。目录内容变化后重新发现。`siteguide(site,intent)` 支持主动窄查询,旧完整目录接口保留。
+- `list_tools` 仅加载通用工作流,`recipeHelp` 才提供完整编写手册。当前 Agent 结合已完成步骤整理,不另起后台模型、不扫描完整聊天。重复形状观察仅留动作枚举和站点,第二次才提示考虑学习;这不是业务成功证明,不能自动猜参数或自动执行配方。
+- 流程由成功导航开始,按 tab/profile 分开,第一次成功 extract/evaluate 结束;错误、敏感页、配方执行和后端切换清除未完成观察。只作为廉价学习线索,不完整覆盖含多次读取或跨站导航的业务流程。持久结构观察与现有配方共用站点目录,具体边界见 credentials-and-local-storage.md。
+- 大结果超过 16 Ki 字符时给确定性结构样例,完整 JSON 保留当前会话最近四份(单份最多 200 万字符),通过 `readResult` 分段读;超上限沿用明确截断。摘要不授权猜测省略的事实或 ref。原文引用沿用来源页的代输入保护,过期必须只读补取,不能重放写操作。输出重复、空字段、HTML 只给 advisory。
+- 内置配方仍走现有随应用分发的 L1 目录,个人 L2 覆盖保留;不自动上传个人经验。`itch-search` 是公开网页人工验证后加入的通用例子。
+- 实现:L2 `experience.ts` / `result-cache.ts` / `tools.ts`,Desktop `browser-recipes/experience.ts`;回归使用真实 MCP 入口与既有 writer 测试。模型用量须与工具文本计量分开,不能把执行器没有新增模型调用说成整个任务零 token。
+
## 10. 相关文档
- `README.md` — runtime 包速览 + 安全说明(本目录上一级)。
diff --git a/packages/lizi-mcps/src/browser/browserMcpServer.test.ts b/packages/lizi-mcps/src/browser/browserMcpServer.test.ts
index ad9db0da97..2623425296 100644
--- a/packages/lizi-mcps/src/browser/browserMcpServer.test.ts
+++ b/packages/lizi-mcps/src/browser/browserMcpServer.test.ts
@@ -5,6 +5,7 @@ import { describe, expect, it } from 'vitest';
import { createBrowserMcpServer } from './server.js';
import { INLINE_IMAGE_TARGET_BYTES, type BrowserMcpDeps } from '../types.js';
+import type { Recipe } from './recipe-loader.js';
// `respond` lets a test script the result per call (e.g. a navigate that returns
// a swapped targetId); default echoes the request back as data.
@@ -42,6 +43,177 @@ async function makeHarness(
};
}
+// New behavior through the public MCP boundary (unit): automatic discovery,
+// structural repetition, candidate lifecycle and recoverable result summaries.
+// Existing tests covered explicit siteguide/validated saves, not these paths.
+describe('browser experience cache', () => {
+ async function invoke(h: Awaited<ReturnType<typeof makeHarness>>, args: Record<string, unknown>) {
+ const r = await h.client.callTool({ name: 'call_tool', arguments: { name: 'browser', args } });
+ return JSON.parse((r.content as Array<{ text: string }>)[0].text);
+ }
+ const draft: Recipe = { id: 'experience-search', access: 'read', match: ['experience.test'], description: 'Search books',
+ inputs: { query: { required: true } }, steps: [{ action: 'evaluate', fn: '() => ({title: "found"})',
+ guard: { url: 'https://experience.test/' }, expect: { requiredFields: ['title'] }, as: 'items' }], output: '{{items}}' };
+
+ it('suggests matching recipes with navigation once per catalog version, without executing them', async () => {
+ let version = 0;
+ const stored = { ...draft, validation: { site: 'experience.test', state: 'active' as const, profile: '' } };
+ const h = await makeHarness({ getUserRecipes: async () => ({ version: `experience-discovery-${version}`,
+ recipes: new Map([[stored.id, stored]]), siteGuides: new Map() }) }, () => ({ targetId: 'tab' }));
+ try {
+ const open = { action: 'navigate', url: 'https://experience.test/', intent: 'Search' };
+ expect((await invoke(h, open)).recipeSuggestions[0]).toMatchObject({ id: draft.id, access: 'read' });
+ expect((await invoke(h, open)).recipeSuggestions).toBeUndefined();
+ version++;
+ expect((await invoke(h, open)).recipeSuggestions).toHaveLength(1);
+ expect((await invoke(h, { ...open, url: 'https://experience.test.evil/' })).recipeSuggestions).toBeUndefined();
+ expect((await invoke(h, { ...open, profile: 'another-account' })).recipeSuggestions).toBeUndefined();
+ expect((await invoke(h, { ...open, intent: 'unrelated' })).recipeSuggestions).toBeUndefined();
+ expect(h.calls).toHaveLength(6);
+ expect(h.calls.every(req => (req as { action: string }).action === 'navigate')).toBe(true);
+ expect(h.calls[0]).not.toHaveProperty('intent');
+ } finally { await h.cleanup(); }
+ });
+
+ it('records only structural steps and hints on repetition; errors and protected pages do not learn', async () => {
+ const recorded: unknown[] = [];
+ let restricted = false;
+ let failed = false;
+ const h = await makeHarness({
+ experienceStore: { list: async () => [], record: async input => {
+ recorded.push(input); return { ...input, observations: recorded.length, updatedAt: 1 };
+ } },
+ pageReadsRestricted: async () => restricted,
+ }, () => ({ targetId: 'tab', result: failed ? { ok: false } : { title: 'private-result' } }));
+ try {
+ const read = { action: 'act', targetId: 'tab', request: { kind: 'evaluate', fn: '() => "private-script"' } };
+ for (let i = 0; i < 2; i++) {
+ await invoke(h, { action: 'navigate', url: 'https://experience.test/private-path?token=secret' });
+ await invoke(h, { action: 'act', targetId: 'tab', request: { kind: 'type', selector: '#private-selector', text: 'private-input' } });
+ const result = await invoke(h, read);
+ expect(Boolean(result.learningOpportunity)).toBe(i === 1);
+ }
+ expect(recorded).toEqual(Array.from({ length: 2 }, () => ({ site: 'experience.test', actions: ['navigate', 'type', 'evaluate'] })));
+ await invoke(h, { action: 'navigate', url: 'https://experience.test/' });
+ failed = true;
+ await invoke(h, read);
+ failed = false;
+ await invoke(h, read);
+ expect(recorded).toHaveLength(2);
+ restricted = true;
+ await invoke(h, { action: 'navigate', url: 'https://experience.test/' });
+ await invoke(h, read);
+ expect(recorded).toHaveLength(2);
+ } finally { await h.cleanup(); }
+ });
+
+ it('persists a read candidate without replay and promotes it on a later real invocation', async () => {
+ let stored: Recipe | undefined;
+ let version = 0;
+ const deps: Partial<BrowserMcpDeps> = {
+ getUserRecipes: async () => ({ version: `experience-candidate-${version}`, recipes: new Map(stored ? [[stored.id, stored]] : []), siteGuides: new Map() }),
+ saveUserRecipe: async ({ recipe }) => { stored = recipe; version++; return { ok: true }; },
+ };
+ const h = await makeHarness(deps);
+ try {
+ expect(await invoke(h, { action: 'saveRecipe', site: 'experience.test', recipeDraft: draft, deferValidation: true })).toMatchObject({ ok: true, state: 'candidate' });
+ expect(h.calls).toHaveLength(0);
+ expect(stored?.validation?.state).toBe('candidate');
+ expect((await invoke(h, { action: 'saveRecipe', site: 'experience.test', recipeDraft: draft, deferValidation: true })).ok).toBe(false);
+ expect((await invoke(h, { action: 'saveRecipe', site: 'experience.test', recipeDraft: { ...draft, id: 'write', access: 'write' }, deferValidation: true })).ok).toBe(false);
+ } finally { await h.cleanup(); }
+ const next = await makeHarness(deps, (_req, i) => ({ result: i === 0 ? true : { title: 'found' } }));
+ try {
+ expect((await invoke(next, { action: 'recipe', recipeId: draft.id, profile: 'other', inputs: { query: 'book' } })).ok).toBe(false);
+ expect((await invoke(next, { action: 'recipe', recipeId: draft.id })).ok).toBe(false);
+ expect(next.calls).toHaveLength(0);
+ expect((await invoke(next, { action: 'recipe', recipeId: draft.id, inputs: { query: 'book' } })).output).toEqual({ title: 'found' });
+ expect(next.calls).toHaveLength(2);
+ expect(stored?.validation?.state).toBe('active');
+ } finally { await next.cleanup(); }
+ });
+
+ it.each(['guard', 'save'] as const)('keeps candidate %s failures honest without replay', async failure => {
+ let stored: Recipe = { ...draft, validation: { site: 'experience.test', state: 'candidate', profile: '' } };
+ const h = await makeHarness({
+ getUserRecipes: async () => ({ version: `experience-failure-${failure}`, recipes: new Map([[stored.id, stored]]), siteGuides: new Map() }),
+ saveUserRecipe: async ({ recipe }) => { if (failure === 'save') throw new Error('disk full'); stored = recipe; return { ok: true }; },
+ }, (_req, i) => ({ result: i === 0 ? failure !== 'guard' : { title: 'found' } }));
+ try {
+ const result = await invoke(h, { action: 'recipe', recipeId: draft.id, inputs: { query: 'book' } });
+ if (failure === 'guard') {
+ expect(result.ok).toBe(false);
+ expect(stored.validation?.state).toBe('suspended');
+ expect((await invoke(h, { action: 'recipe', recipeId: draft.id, inputs: { query: 'book' } })).ok).toBe(false);
+ expect(h.calls).toHaveLength(1);
+ } else {
+ expect(result.ok).toBe(true);
+ expect(result.maintenanceMessage).toContain('保存失败');
+ expect(stored.validation?.state).toBe('candidate');
+ expect(h.calls).toHaveLength(2);
+ }
+ } finally { await h.cleanup(); }
+ });
+
+ it('reconstructs a large result byte-for-byte without replay, and blocks cached reads after secret handoff', async () => {
+ let restricted = false;
+ const original = { ok: true, action: 'act' as const, data: { targetId: 'tab', result: Array.from({ length: 200 }, (_, i) => ({ title: `item-${i}`, body: '引号"\\'.repeat(40) })) } };
+ const h = await makeHarness({ getRuntime: () => ({ call: async () => original }), pageReadsRestricted: async () => restricted });
+ try {
+ const result = await invoke(h, { action: 'act', targetId: 'tab', request: { kind: 'evaluate', fn: '() => []' } });
+ expect(JSON.stringify(result).length).toBeLessThan(10_000);
+ const id = result.fullResult.id;
+ let offset: number | null = 0;
+ let text = '';
+ while (offset !== null) {
+ const chunk = await invoke(h, { action: 'readResult', resultId: id, offset, maxChars: 12_000 });
+ text += chunk.text; offset = chunk.nextOffset;
+ }
+ expect(JSON.parse(text)).toEqual(original);
+ const other = await makeHarness({ getRuntime: () => ({ call: async () => original }) });
+ try {
+ await invoke(other, { action: 'act', request: { kind: 'evaluate', fn: '() => []' } });
+ // A stale reference must not silently resolve to a new session's first result.
+ expect((await invoke(other, { action: 'readResult', resultId: id })).ok).toBe(false);
+ } finally { await other.cleanup(); }
+ restricted = true;
+ expect((await invoke(h, { action: 'readResult', resultId: id })).ok).toBe(false);
+ restricted = false;
+ expect((await invoke(h, { action: 'readResult', resultId: id })).ok).toBe(false);
+ } finally { await h.cleanup(); }
+ });
+
+ it('evicts old originals and preserves success with advisory warnings or failed experience storage', async () => {
+ let big = true;
+ const h = await makeHarness({
+ experienceStore: { list: async () => [], record: async () => { throw new Error('disk full'); } },
+ }, () => ({ targetId: 'tab', result: big ? 'x'.repeat(17_000) : [{ title: '', body: '<div>raw</div>' }, { title: '', body: '<div>raw</div>' }] }));
+ try {
+ const read = { action: 'act', targetId: 'tab', request: { kind: 'evaluate', fn: '() => []' } };
+ const first = await invoke(h, read);
+ for (let i = 0; i < 4; i++) await invoke(h, read);
+ expect((await invoke(h, { action: 'readResult', resultId: first.fullResult.id })).ok).toBe(false);
+ big = false;
+ await invoke(h, { action: 'navigate', url: 'https://experience.test/' });
+ const result = await invoke(h, read);
+ expect(result.ok).toBe(true);
+ expect(result.advisory).toEqual(expect.arrayContaining(['duplicate_records', 'empty_fields', 'markup']));
+ expect(result.learningOpportunity).toBeUndefined();
+ } finally { await h.cleanup(); }
+ });
+
+ it('reports successful oversized actions honestly when the full result exceeds the retention budget', async () => {
+ const h = await makeHarness({}, () => ({ blob: 'x'.repeat(2_000_001) }));
+ try {
+ const result = await invoke(h, { action: 'act', request: { kind: 'evaluate', fn: '() => []' } });
+ expect(result).toMatchObject({ ok: true, action: 'act', truncated: true });
+ expect(result.fullResult).toBeUndefined();
+ expect(JSON.stringify(result).length).toBeLessThanOrEqual(200_000);
+ expect(h.calls).toHaveLength(1);
+ } finally { await h.cleanup(); }
+ });
+});
+
describe('createBrowserMcpServer', () => {
// Historical form replay spent a second model call on every post-click read.
// Unit tier, production MCP entry: preserve successful mutations on read errors,
@@ -222,10 +394,13 @@ describe('createBrowserMcpServer', () => {
};
expect(parsed.ok).toBe(true);
// the `browser` tool references the rule keys…
- expect(parsed.tools.find((t) => t.name === 'browser')?.rules).toEqual(['browser-workflow', 'recipe-author']);
+ expect(parsed.tools.find((t) => t.name === 'browser')?.rules).toEqual(['browser-workflow']);
// …and each full markdown body is bundled once at the top level.
expect(parsed.rules?.['browser-workflow']).toContain('snapshot');
- expect(parsed.rules?.['recipe-author']).toContain('saveRecipe');
+ expect(parsed.rules?.['recipe-author']).toBeUndefined();
+ const help = await h.client.callTool({ name: 'call_tool', arguments: { name: 'browser', args: { action: 'recipeHelp' } } });
+ expect(JSON.parse((help.content as Array<{ text: string }>)[0].text).rules).toContain('saveRecipe');
+ expect(h.calls).toHaveLength(0);
await h.cleanup();
});
@@ -887,11 +1062,14 @@ describe('createBrowserMcpServer', () => {
});
const parsed = JSON.parse((result.content as Array<{ text: string }>)[0].text) as {
truncated?: boolean;
- bytes?: number;
- limit?: number;
+ fullResult: { id: string; chars: number };
};
expect(parsed.truncated).toBe(true);
- expect(parsed.bytes ?? 0).toBeGreaterThan(parsed.limit ?? 0);
+ expect(parsed.fullResult.chars).toBeGreaterThan(300_000);
+ const read = await h.client.callTool({ name: 'call_tool', arguments: { name: 'browser', args: { action: 'readResult', resultId: parsed.fullResult.id, offset: 0, maxChars: 1000 } } });
+ const original = JSON.parse((read.content as Array<{ text: string }>)[0].text);
+ expect(original.text).toContain('"blob":"xxxx');
+ expect(original.nextOffset).toBe(1000);
await h.cleanup();
});
diff --git a/packages/lizi-mcps/src/browser/cindy-recipes/itch.io/itch-search.recipe.json b/packages/lizi-mcps/src/browser/cindy-recipes/itch.io/itch-search.recipe.json
new file mode 100644
index 0000000000..a162e57900
--- /dev/null
+++ b/packages/lizi-mcps/src/browser/cindy-recipes/itch.io/itch-search.recipe.json
@@ -0,0 +1,26 @@
+{
+ "id": "itch-search",
+ "match": ["itch.io"],
+ "description": "搜索 itch.io 游戏和项目,返回标题、作者和链接;支持确认后的空结果。Search games and projects.",
+ "access": "read",
+ "inputs": {
+ "query": { "required": true, "type": "string", "description": "搜索词" },
+ "limit": { "required": true, "type": "number", "description": "返回数量,1–20 整数" }
+ },
+ "steps": [
+ { "action": "navigate", "url": "https://itch.io/search?q={{query|url}}" },
+ {
+ "action": "wait",
+ "fn": "() => document.querySelector('.search_header') && (document.querySelector('.game_cell_data') || document.body.innerText.includes('No results found'))",
+ "timeoutMs": 10000
+ },
+ {
+ "action": "evaluate",
+ "guard": { "url": "https://itch.io/search?q={{query|url}}", "selector": ".search_header" },
+ "fn": "() => { const query='{{query|js}}', limit=Number('{{limit|js}}'); if(!Number.isInteger(limit)||limit<1||limit>20)throw new Error('limit must be an integer from 1 to 20'); const rows=[...document.querySelectorAll('.game_cell_data')].slice(0,limit).map(c=>({title:c.querySelector('.game_title > a.title')?.textContent.trim(),url:c.querySelector('.game_title > a.title')?.href,author:c.querySelector('.game_author')?.textContent.trim()})); const empty=rows.length===0 && document.body.innerText.includes('No results found'); return {query,rows,count:rows.length,empty,matched:new URL(location.href).searchParams.get('q')===query && document.querySelector('.search_header h2')?.textContent===`Search results for '${query}'` && (empty || (rows.length>0 && rows.every(r=>r.title&&r.url&&r.author)))}; }",
+ "as": "result",
+ "expect": { "equals": { "matched": true } }
+ }
+ ],
+ "output": "{{result}}"
+}
diff --git a/packages/lizi-mcps/src/browser/cindy-recipes/itch.io/siteguide.json b/packages/lizi-mcps/src/browser/cindy-recipes/itch.io/siteguide.json
new file mode 100644
index 0000000000..bccfe8db54
--- /dev/null
+++ b/packages/lizi-mcps/src/browser/cindy-recipes/itch.io/siteguide.json
@@ -0,0 +1,7 @@
+{
+ "site": "itch.io",
+ "auth": "公开搜索,无需登录。",
+ "recipes": ["itch-search"],
+ "notes": "仅返回当前搜索页前 1–20 个项目,不支持分页。空结果必须由页面确认。",
+ "source": "Cindy"
+}
diff --git a/packages/lizi-mcps/src/browser/experience.ts b/packages/lizi-mcps/src/browser/experience.ts
new file mode 100644
index 0000000000..1286a4d68a
--- /dev/null
+++ b/packages/lizi-mcps/src/browser/experience.ts
@@ -0,0 +1,99 @@
+import { z } from 'zod';
+import type { MergedRecipe } from './recipe-loader.js';
+
+/** Persist only execution shape and counters, never URLs, selectors, scripts or values. */
+export const BrowserExperienceSchema = z.object({
+ site: z.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9.-]{0,252}$/),
+ actions: z
+ .array(z.enum(['navigate', 'click', 'type', 'select', 'press', 'wait', 'extract', 'evaluate']))
+ .min(2)
+ .max(32),
+ observations: z.number().int().positive(),
+ updatedAt: z.number().finite(),
+});
+export type BrowserExperience = z.infer<typeof BrowserExperienceSchema>;
+export type ExperienceAction = BrowserExperience['actions'][number];
+
+export interface BrowserExperienceStore {
+ record(input: Pick<BrowserExperience, 'site' | 'actions'>): Promise<BrowserExperience>;
+ list(site: string): Promise<BrowserExperience[]>;
+}
+
+/** A bounded per-task trace; navigation starts a flow, the first successful read ends it. */
+export class BrowserExperienceRecorder {
+ private readonly flows = new Map<string, { site: string; actions: ExperienceAction[] }>();
+
+ clear(target?: string): void {
+ if (target === undefined) this.flows.clear();
+ else this.flows.delete(target);
+ }
+
+ start(target: string, url: string): void {
+ this.clear(target);
+ try {
+ const parsed = new URL(url);
+ if (!['http:', 'https:'].includes(parsed.protocol) || parsed.username || parsed.password)
+ return;
+ if (!BrowserExperienceSchema.shape.site.safeParse(parsed.hostname).success) return;
+ if (this.flows.size >= 32) this.flows.delete(this.flows.keys().next().value!);
+ this.flows.set(target, { site: parsed.hostname, actions: ['navigate'] });
+ } catch {
+ /* Not an observable web flow. */
+ }
+ }
+
+ step(
+ target: string,
+ action: ExperienceAction,
+ ): Pick<BrowserExperience, 'site' | 'actions'> | undefined {
+ const flow = this.flows.get(target);
+ if (!flow) return;
+ if (flow.actions.length >= 32) {
+ this.clear(target);
+ return;
+ }
+ flow.actions.push(action);
+ if (action !== 'extract' && action !== 'evaluate') return;
+ this.clear(target);
+ return flow;
+ }
+}
+
+/** Host matching is boundary-aware. A match only suggests a recipe, never executes it. */
+export function suggestRecipes(
+ recipes: Map<string, MergedRecipe>,
+ site: string,
+ intent = '',
+ profile = '',
+) {
+ const terms = intent
+ .toLowerCase()
+ .split(/[^\p{L}\p{N}]+/u)
+ .filter(Boolean);
+ return [...recipes.values()]
+ .filter(({ recipe }) => {
+ if (recipe.validation?.state === 'suspended') return false;
+ if (recipe.validation?.profile !== undefined && recipe.validation.profile !== profile)
+ return false;
+ return [recipe.validation?.site, ...(recipe.match ?? [])].some((host) => {
+ if (!host) return false;
+ const normalized = host.toLowerCase().replace(/^www\./, '');
+ return site === normalized || site.endsWith(`.${normalized}`);
+ });
+ })
+ .map((entry) => {
+ const haystack = `${entry.recipe.id} ${entry.recipe.description ?? ''}`.toLowerCase();
+ return { ...entry, score: terms.filter((term) => haystack.includes(term)).length };
+ })
+ .sort((a, b) => b.score - a.score || a.recipe.id.localeCompare(b.recipe.id))
+ .filter((entry) => !terms.length || entry.score > 0)
+ .slice(0, 3)
+ .map(({ recipe, provenance }) => ({
+ id: recipe.id,
+ description: recipe.description?.slice(0, 240),
+ access: recipe.access ?? 'unspecified',
+ state: recipe.validation?.state ?? 'active',
+ provenance,
+ inputs: recipe.inputs,
+ }));
+}
diff --git a/packages/lizi-mcps/src/browser/index.ts b/packages/lizi-mcps/src/browser/index.ts
index 578b119541..6a2699b31a 100644
--- a/packages/lizi-mcps/src/browser/index.ts
+++ b/packages/lizi-mcps/src/browser/index.ts
@@ -7,3 +7,4 @@ export * from './tools.js';
// user-recipe layer (parseRecipes/parseSiteGuides) without deep-importing.
// loadRecipes()'s import.meta.glob only runs when called, so this is import-safe.
export * from './recipe-loader.js';
+export * from './experience.js';
diff --git a/packages/lizi-mcps/src/browser/prompts/rules/browser-workflow.md b/packages/lizi-mcps/src/browser/prompts/rules/browser-workflow.md
index e71c7d4d76..c27267d8a5 100644
--- a/packages/lizi-mcps/src/browser/prompts/rules/browser-workflow.md
+++ b/packages/lizi-mcps/src/browser/prompts/rules/browser-workflow.md
@@ -63,7 +63,7 @@
7. 任务完成后,可用不带 `proxyServer` 的 `{action:"start"}` 明确恢复普通直连模式。代理 A 切代理 B、代理切直连都会重启浏览器;重复同一代理则保持当前进程。
#### Token 效率(按"最省 → 兜底"的顺序选路)
-1. **先查有没有现成配方**:操作某个站之前,**先 `action: "siteguide"`**——带 `site`(站点 host)看该站内置指南 / 配方;**不确定有哪些站时,`siteguide` 不带 `site` 会列出全部内置站点 + 可用配方目录**(`sites:[{site,recipes,auth}]`)。命中且未 suspended 的配方就 `action: "recipe"`(`recipeId`+`inputs`)组合执行并检查结果,优先于手动 snapshot/extract。注意 `siteguide` 是我们内置的站点指南,**不是去抓网站自己的 `/sitemap.xml`**——不要为此去 navigate / curl `sitemap.xml`。
+1. **优先复用配方**: `open/navigate` 会随结果给出最多三个本地 `recipeSuggestions`,可带简短 `intent` 收窄;同任务相同站点/意图且目录未变不重复提示,不另起模型请求。自行判断业务、账号与参数是否适用,再显式 `recipe(recipeId,inputs)`;候选会在本次真实执行通过校验后转为 active。已知 id 直接复用,无须先导航或查目录。缺少合适候选时可用 `siteguide` + `site` 看完整站点指南,不要默认加载全部目录;`siteguide` 不是网站的 sitemap.xml。
2. **数据型页面优先读接口,别扒 DOM**:很多列表 / 详情背后是 JSON API,读接口比扒渲染后的 DOM 又稳又省。
- ① `action: "requests"`(带**具体** `filter`,如 `/api/quotes`;别用太宽的 `api`,会撞 `fonts.googleapis.com` 之类)看页面发了哪些 XHR/fetch、拿到接口 URL。这是读**已发生**请求的清单。
- ② 读 body:**GET 接口最稳的姿势是直接 `navigate` 到该 URL**,再用 `extract`(`fields:{ data:"body" }`)或 snapshot 读返回的 JSON。
@@ -72,6 +72,10 @@
4. **要精确字段 / 干净 JSON 才用 `extract`**:snapshot 不够精准(要取某属性、按子选择器拆字段)时,用 `action: "extract"` 一次性提结构化记录(`from` + `multiple` 提列表)。**关键:`fields` 的简写 string 是纯 CSS 选择器(取 textContent);取属性用 `{selector,attr}`,取链接用 `{selector,type:"href"}`——别把属性拼进选择器(`"h3 a@title"` 非法)、别写自然语言。** 不确定选择器就先 scoped snapshot 看结构再写。
5. **慎用 screenshot**:只有需要视觉确认(布局 / 图像内容)时才 `action: "screenshot"`;链接要看真实 URL 时 snapshot 带 `urls: true`,元素位置重要时才 `labels: true`。
+重复流程才考虑学习:宿主仅留存站点、操作种类和次数,不保留输入、脚本、选择器或业务结果。`learningOpportunity` 只是重复形状提示,不证明业务相同;结合当前成功步骤判断收益。有价值或用户明确要求长期复用时才调用 `recipeHelp` 加载编写手册;偶发任务无需总结,不另起模型。候选可用下一次真实任务验证;正常 guard/expect 只运行代码,失效最多修订一轮,失败回普通操作。写操作不得为测试重放。
+
+大结果返回结构摘要和 `fullResult`,不是完整事实;用 `readResult(resultId,offset,maxChars)` 补读(`nextOffset:null` 表示结束),不猜省略内容或 ref。原文只留当前工具会话最近四份、每份最多 200 万字符;更大结果沿用明确截断,需缩小读取范围。`advisory` 是代码发现的可疑输出,不自动认定业务错误。
+
#### 两种浏览器模式(先认环境,再谈登录)
宿主用两种后端之一承接本工具,**顶层 action 集合一致**(两边都支持 snapshot / act 各 kind / requests / upload / dialog 等),差别在两处:少数参数级能力只有侧边栏模式有,以及"页面呈现在哪里"。判别依据是 `action: "status"` 返回结果里的 **`data.backend`**(工具结果的外层是 `{ ok, action, status, data }`,`status` 是数字状态码——**别去读 `status.backend`**,那是 undefined):
@@ -117,6 +121,8 @@
| `extract` | 按字段 schema 从 DOM 提结构化数据(列表/详情,优于全页 snapshot) |
| `requests` / `responseBody` | 看页面已发生的 XHR/fetch 列表(可 `filter`) / 等待并读下一个匹配响应的 body(先发起再触发;读 GET JSON 优先直接 navigate 到该 URL) |
| `recipe` / `siteguide` | 跑某站现成配方(`recipeId`+`inputs`) / 取某站内置指南(`site`,含入口/关键页/可用配方;非 sitemap.xml) |
+| `recipeHelp` / `saveRecipe` | 按需加载编写手册 / 保存已验证配方或新的只读候选 |
+| `readResult` | 按引用和字符偏移补读当前工具会话保留的大结果原文 |
| `screenshot` | 仅在需要视觉确认时用 |
| `console` / `pdf` / `upload` / `dialog` | 控制台日志 / 导出 PDF / 上传文件 / 处理原生弹窗 |
diff --git a/packages/lizi-mcps/src/browser/prompts/rules/recipe-author.md b/packages/lizi-mcps/src/browser/prompts/rules/recipe-author.md
index f617f78c5c..7c943ca54f 100644
--- a/packages/lizi-mcps/src/browser/prompts/rules/recipe-author.md
+++ b/packages/lizi-mcps/src/browser/prompts/rules/recipe-author.md
@@ -4,13 +4,15 @@
#### 作者流程(recon → 发现 → 抽取 → 验证 → 沉淀)
-1. **侦察**:先 `action: "siteguide"` + `site` 看有没有现成指南/配方;没有就 `navigate` 到目标页 + **scoped `snapshot`**(带 `selector` 收窄)摸清结构,`action: "requests"`(带**具体** `filter`)看页面发了哪些 XHR/fetch。
+1. **复用当前证据**:先看自动返回的配方候选,必要时 `siteguide` + `site`。从当前任务已成功的步骤整理,不重读整段历史、不再探索已知结构。`recipeHelp` 的 observations 只有历史操作形状和次数,不包含脚本、选择器或业务内容,不能据此编造可执行步骤。缺证据时才 scoped `snapshot` / 具体 filter 的 `requests`。
2. **优先发现接口**:很多列表/详情背后是 JSON API。找到接口 URL 后,把可变部分(关键词、页码、subreddit 等)抽成 `inputs` 变量,URL 里用 `{{var}}` 占位。**读 GET JSON 接口最稳的姿势:`navigate` 到该 URL,再 `extract` `{ fields: { body: "body" } }` 读回 JSON**(不要用 responseBody 来读历史响应,它是"等下一个匹配响应")。
3. **鉴权**:判断是否需要登录。需要就在 siteguide 的 `auth` 字段写清楚,并在配方里把登录态相关步骤设 `optional: true` 做探测;真正登录由用户在持久浏览器里完成一次。
4. **抽取**:扒 DOM 字段用 `extract`——**先 scoped `snapshot` 确认选择器在页面上真实存在再写**(别凭空猜选择器、别把属性拼进选择器)。`fields` 的 string 是纯 CSS 选择器(取 textContent),取属性用 `{selector, attr}`,取链接用 `{selector, type:"href"}`。列表用 `from` + `multiple`。
5. **交互步**:`click` / `type` / `select` 直接写**稳定 CSS `selector`**(运行时由 act 解析,不写死 snapshot ref,跨会话不腐烂)。`type` 配 `submit: true` 提交表单。
6. **验证**:用 `action:"recipe", site, recipeDraft, inputs` 当场试跑。交互和读取步骤须有 `guard:{url,selector?,text?}`:完整 URL 精确匹配,标准 CSS selector 须唯一可见匹配,可选 text 精确匹配(去首尾空格)。URL 应包含账号/项目身份;同 URL 多账号时用页面账号元素校验。最后一步须带 `expect:{minCount?,requiredFields?,equals?}`,用 `as` 和 `output:"{{变量}}"` 返回经过验证的结果。expect 检查每条记录的顶层字段,equals 的字符串可插值。guard/expect 不可 optional。
-7. **沉淀**:`action: "saveRecipe"`,传 `site`(站点 host)+ `recipeDraft`(配方对象)+ 可选 `siteGuideDraft`。只能保存本任务中刚试跑成功的同一份 draft 和 site;改动内容必须重新验证。不要提供宿主管理的 validation 字段。每站可保存多个 id。
+7. **沉淀**:`action: "saveRecipe"`,传 `site` + `recipeDraft` + 可选 `siteGuideDraft`。通常保存本任务中刚试跑成功的同一份 draft、site 和 profile;不要提供宿主管理的 validation 字段。新只读流程声明 `access:"read"` 后可加 `deferValidation:true`,不重新跑当前任务,先存 candidate,等下一次真实任务显式执行并通过所有 guard/expect 后转为 active。候选不能覆盖已有配方,写流程不能延后验证。每站可保存多个 id。
+
+验证用少量组合输入覆盖变化的参数、数量和空结果;优先使用下一次真实需求,不穷举、不承诺未测能力。active 仅证明已执行的检查通过,不代表所有输入都测试过。账号/项目的页面身份必须进入 guard,不能仅靠 profile 或站点名称推断登录身份。参数化所有业务值,不保存实际查询、用户资料、密码或令牌;普通记录只用于判断是否重复,不自动上传或转成内置配方。
#### 取数策略(先判断站点属于哪种,再选 step)
diff --git a/packages/lizi-mcps/src/browser/recipe-loader.ts b/packages/lizi-mcps/src/browser/recipe-loader.ts
index 8e3dbfbd79..0167097870 100644
--- a/packages/lizi-mcps/src/browser/recipe-loader.ts
+++ b/packages/lizi-mcps/src/browser/recipe-loader.ts
@@ -90,7 +90,9 @@ export const RecipeSchema = z.object({
/** Host-owned state; authored drafts cannot supply this. Legacy files remain runnable. */
validation: z.object({
site: z.string(),
- state: z.enum(['active', 'suspended']),
+ state: z.enum(['candidate', 'active', 'suspended']),
+ /** Newly learned recipes stay in their browser profile; legacy files omit it. */
+ profile: z.string().optional(),
}).optional(),
}).refine(recipe => recipe.adapter ? recipe.steps.length === 0 : recipe.steps.length > 0, 'recipe requires steps or a bundled adapter, exclusively');
diff --git a/packages/lizi-mcps/src/browser/result-cache.ts b/packages/lizi-mcps/src/browser/result-cache.ts
new file mode 100644
index 0000000000..3e42b2e608
--- /dev/null
+++ b/packages/lizi-mcps/src/browser/result-cache.ts
@@ -0,0 +1,131 @@
+import { randomUUID } from 'node:crypto';
+
+/** Session-only originals: bounded memory, no disk, no background jobs or model calls. */
+export class BrowserResultCache {
+ private readonly originals = new Map<
+ string,
+ { text: string; source: { profile?: string; targetId?: string } }
+ >();
+
+ clear(): void {
+ this.originals.clear();
+ }
+
+ source(id: string) {
+ return this.originals.get(id)?.source;
+ }
+
+ digest(
+ value: Record<string, unknown>,
+ source: { profile?: string; targetId?: string } = {},
+ ): Record<string, unknown> {
+ const json = JSON.stringify(value);
+ if (json.length <= 16_384) return value;
+ // Oversize results keep the existing explicit truncation fallback. Never
+ // advertise an original that could not be retained within the memory budget.
+ if (json.length > 2_000_000) return value;
+ if (this.originals.size >= 4) this.originals.delete(this.originals.keys().next().value!);
+ const id = `result-${randomUUID()}`;
+ this.originals.set(id, { text: json, source });
+ return {
+ ok: value.ok,
+ action: value.action,
+ errorCode: value.errorCode,
+ message: typeof value.message === 'string' ? value.message.slice(0, 2_000) : undefined,
+ ...(value.loginWall ? { loginWall: sample(value.loginWall, 0, { remaining: 1_000 }) } : {}),
+ ...(value.failureKind
+ ? { failureKind: value.failureKind, failedStep: value.failedStep }
+ : {}),
+ ...(value.recovery ? { recovery: value.recovery } : {}),
+ ...(value.maintenanceMessage ? { maintenanceMessage: value.maintenanceMessage } : {}),
+ truncated: true,
+ summary: sample(value, 0, { remaining: 6_000 }),
+ fullResult: {
+ id,
+ chars: json.length,
+ read: { action: 'readResult', resultId: id, offset: 0, maxChars: 12_000 },
+ },
+ hint: '摘要不是完整结果。缺少事实或页面 ref 时用 readResult 分段补读;不要猜测或重放动作。原文仅留在当前工具会话,最多保留最近四份大结果。',
+ };
+ }
+
+ read(id: string, offset: number, maxChars: number) {
+ const text = this.originals.get(id)?.text;
+ if (text === undefined)
+ return {
+ ok: false,
+ action: 'readResult',
+ message: '原文已过期或不属于当前工具会话;请重新只读获取所需内容,不要重放写操作。',
+ };
+ if (offset > text.length)
+ return {
+ ok: false,
+ action: 'readResult',
+ message: 'offset 超出原文长度',
+ chars: text.length,
+ };
+ const end = Math.min(text.length, offset + maxChars);
+ return {
+ ok: true,
+ action: 'readResult',
+ resultId: id,
+ offset,
+ chars: text.length,
+ text: text.slice(offset, end),
+ nextOffset: end < text.length ? end : null,
+ };
+ }
+}
+
+/** Deterministic structural samples; counts make omissions explicit. */
+function sample(value: unknown, depth: number, budget: { remaining: number }): unknown {
+ if (budget.remaining <= 0) return '[omitted]';
+ budget.remaining -= 80;
+ if (typeof value === 'string') {
+ budget.remaining -= Math.min(value.length, 240);
+ return value.length > 240 ? `${value.slice(0, 240)}… [${value.length} chars]` : value;
+ }
+ if (Array.isArray(value))
+ return {
+ count: value.length,
+ sample: depth >= 4 ? [] : value.slice(0, 2).map((item) => sample(item, depth + 1, budget)),
+ };
+ if (value && typeof value === 'object') {
+ const entries = Object.entries(value);
+ if (depth >= 4)
+ return {
+ keys: entries.slice(0, 12).map(([key]) => key.slice(0, 80)),
+ keyCount: entries.length,
+ };
+ return Object.fromEntries([
+ ...entries
+ .slice(0, 12)
+ .map(([key, item]) => [key.slice(0, 80), sample(item, depth + 1, budget)]),
+ ...(entries.length > 12 ? [['omittedKeys', entries.length - 12]] : []),
+ ]);
+ }
+ return value;
+}
+
+/** Advisory only: legitimate duplicate titles / empty fields must not become failures. */
+export function lintBrowserOutput(value: unknown): string[] {
+ const object =
+ value && typeof value === 'object' ? (value as Record<string, unknown>) : undefined;
+ const rows = Array.isArray(value)
+ ? value
+ : ['rows', 'records', 'items', 'results'].map((key) => object?.[key]).find(Array.isArray);
+ if (!rows?.length) return [];
+ const warnings = new Set<string>();
+ const seen = new Set<string>();
+ for (const row of rows.slice(0, 200)) {
+ const key = JSON.stringify(row);
+ if (seen.has(key)) warnings.add('duplicate_records');
+ seen.add(key);
+ if (!row || typeof row !== 'object') continue;
+ for (const item of Object.values(row)) {
+ if (item === '' || item === null) warnings.add('empty_fields');
+ if (typeof item === 'string' && /<\/?[a-z][^>]*>/i.test(item)) warnings.add('markup');
+ }
+ }
+ return [...warnings];
+}
diff --git a/packages/lizi-mcps/src/browser/server.ts b/packages/lizi-mcps/src/browser/server.ts
index f22171350f..c7ab649bdb 100644
--- a/packages/lizi-mcps/src/browser/server.ts
+++ b/packages/lizi-mcps/src/browser/server.ts
@@ -6,12 +6,10 @@ import type { BrowserMcpDeps } from '../types.js';
import { BrowserToolRegistry } from './tool-registry.js';
import { registerBrowserTools } from './tools.js';
import browserWorkflowRules from './prompts/rules/browser-workflow.md?raw';
-import recipeAuthorRules from './prompts/rules/recipe-author.md?raw';
/** key → markdown body. Bundled into list_tools responses ONCE per category. */
const RULES: Record<string, string> = {
'browser-workflow': browserWorkflowRules,
- 'recipe-author': recipeAuthorRules,
};
const D_LIST_TOOLS =
diff --git a/packages/lizi-mcps/src/browser/tools.ts b/packages/lizi-mcps/src/browser/tools.ts
index 3357b6c04e..a0a6483d93 100644
--- a/packages/lizi-mcps/src/browser/tools.ts
+++ b/packages/lizi-mcps/src/browser/tools.ts
@@ -33,6 +33,9 @@ import {
} from './recipe-loader.js';
import { runRecipe, findUnsafeEvaluateInterpolations } from './recipe-runner.js';
import { isHttpUrl } from './url-guard.js';
+import { BrowserExperienceRecorder, suggestRecipes, type ExperienceAction } from './experience.js';
+import { BrowserResultCache, lintBrowserOutput } from './result-cache.js';
+import recipeAuthorRules from './prompts/rules/recipe-author.md?raw';
// Layered registries: bundled L1 (Vite glob, parsed once) merged with the host's
// optional L2 user layer. Cached and keyed by the L2 `version` fingerprint, so a
@@ -96,6 +99,8 @@ const ACTIONS = [
'recipe',
'siteguide',
'saveRecipe',
+ 'recipeHelp',
+ 'readResult',
] as const;
const ACT_KINDS = [
@@ -279,7 +284,11 @@ function resultText(value: unknown): string {
// string ~2x the cap for quote-heavy content — defeating this backstop. Size
// the preview against the FINAL serialized length instead: start optimistic,
// then shrink by the measured overflow until the whole result fits.
+ const record = value && typeof value === 'object' ? value as Record<string, unknown> : {};
const base = {
+ ...(typeof record.ok === 'boolean' ? { ok: record.ok } : {}),
+ ...(typeof record.action === 'string' ? { action: record.action } : {}),
+ ...(typeof record.errorCode === 'string' ? { errorCode: record.errorCode } : {}),
truncated: true as const,
bytes: json.length,
limit: MAX_RESULT_BYTES,
@@ -476,15 +485,20 @@ async function screenshotToolResult(
function toRuntimeRequest(args: Record<string, unknown>): BrowserControlRequest {
const out: Record<string, unknown> = {};
for (const [key, value] of Object.entries(args)) {
- if (value !== undefined && key !== 'afterSnapshot') out[key] = value;
+ if (value !== undefined && !['afterSnapshot', 'intent', 'deferValidation', 'resultId', 'offset'].includes(key)) out[key] = value;
}
return out as unknown as BrowserControlRequest;
}
export function registerBrowserTools(registry: BrowserToolRegistry, deps: BrowserMcpDeps): void {
+ const experiences = new BrowserExperienceRecorder();
+ const results = new BrowserResultCache();
+ const discovered = new Map<string, string>();
+ const learningHints = new Set<string>();
+ const textResult = (value: Record<string, unknown>, source?: { profile?: string; targetId?: string }) => resultText(results.digest(value, source));
// Session-local evidence and repair budget: never share successful trials
// between agents, and never retain caller inputs or page contents here.
- const verifiedDrafts = new Map<string, { site: string; content: string }>();
+ const verifiedDrafts = new Map<string, { site: string; content: string; profile: string }>();
const failedRecipes = new Set<string>();
const repairUsed = new Set<string>();
const runningRecipes = new Set<string>();
@@ -523,9 +537,13 @@ export function registerBrowserTools(registry: BrowserToolRegistry, deps: Browse
'优先使用 snapshot 返回的 ref 执行 click/type/press,不要猜测 CSS selector。' +
'act/open/navigate/upload 可带 afterSnapshot:{},一次返回动作结果和精简快照;可用 selector 限定区域。' +
'注意:直接调用本工具时,wait/evaluate/saveResource 不是顶层 action(会报 INVALID_ARGS),它们只能作为 act 的 request.kind 子操作(配方 steps 里仅 wait/evaluate 是合法 DSL action,saveResource 在配方中同样不可用)。',
- rules: ['browser-workflow', 'recipe-author'],
+ rules: ['browser-workflow'],
inputShape: {
action: z.enum(ACTIONS).describe('浏览器操作类型'),
+ intent: z.string().max(120).optional().describe('open/navigate/siteguide: 可选操作意图,用于本地匹配配方;不会自动执行'),
+ deferValidation: z.boolean().optional().describe('saveRecipe: 将新的只读流程存为候选,下一次真实任务执行时校验;不额外重放当前任务'),
+ resultId: z.string().optional().describe('readResult: 大结果返回的 fullResult.id'),
+ offset: z.number().int().nonnegative().optional().describe('readResult: 原始 JSON 字符偏移'),
backend: z
.enum(['external', 'rsb-webview'])
.optional()
@@ -635,6 +653,24 @@ export function registerBrowserTools(registry: BrowserToolRegistry, deps: Browse
},
handler: async (args) => {
try {
+ if (args.action === 'readResult') {
+ if (!args.resultId) return errorResult(args.action, 'readResult requires resultId');
+ const source = results.source(args.resultId);
+ if (source && deps.pageReadsRestricted && await deps.pageReadsRestricted(source).catch(() => true)) {
+ results.clear();
+ return errorResult(args.action, '该页面处于代输入保护期,已清除缓存;请离开敏感页面后重新只读获取');
+ }
+ const value = results.read(args.resultId, args.offset ?? 0, Math.max(1, Math.min(args.maxChars ?? 12_000, 24_000)));
+ return { content: [{ type: 'text', text: resultText(value) }], isError: !value.ok };
+ }
+ if (args.action === 'recipeHelp') {
+ let observations: unknown[] = [];
+ if (args.site && deps.experienceStore) {
+ try { observations = await deps.experienceStore.list(args.site); } catch { /* Learning is optional. */ }
+ }
+ return { content: [{ type: 'text', text: resultText({ ok: true, action: 'recipeHelp', rules: recipeAuthorRules, observations }) }] };
+ }
+ if (args.deferValidation !== undefined && args.action !== 'saveRecipe') return errorResult(args.action, 'deferValidation 仅用于 saveRecipe');
if (args.afterSnapshot && (!['act', 'open', 'navigate', 'upload'].includes(args.action)
|| (args.action === 'act' && args.request?.kind === 'close'))) {
return errorResult(args.action, 'afterSnapshot 仅用于 act(不含 close)、open、navigate、upload');
@@ -647,6 +683,9 @@ export function registerBrowserTools(registry: BrowserToolRegistry, deps: Browse
}
if (!deps.setBackend) return errorResult(args.action, '当前宿主不支持切换浏览器模式');
const backend = await deps.setBackend(args.backend);
+ experiences.clear();
+ discovered.clear();
+ results.clear();
const ok = backend === args.backend;
return {
content: [{
@@ -733,6 +772,7 @@ export function registerBrowserTools(registry: BrowserToolRegistry, deps: Browse
// recipe: run a declarative per-site flow (composition over primitives).
// Merged L1 (bundled) + L2 (user); user version shadows builtin by id.
if (args.action === 'recipe') {
+ experiences.clear(args.targetId ? JSON.stringify([args.profile ?? '', args.targetId]) : undefined);
let entry: MergedRecipe | undefined;
const candidate = args.recipeDraft !== undefined;
if (candidate) {
@@ -747,8 +787,16 @@ export function registerBrowserTools(registry: BrowserToolRegistry, deps: Browse
entry = (await recipeRegistry(deps)).get(args.recipeId);
}
if (!entry) return errorResult('recipe', `unknown recipe: ${args.recipeId}`);
+ if (entry.recipe.validation?.state === 'candidate') {
+ const { validation, ...draft } = entry.recipe;
+ const issue = draftIssue(draft, validation.site);
+ if (issue || draft.access !== 'read') return errorResult('recipe', issue ?? '候选必须是只读流程');
+ }
const id = entry.recipe.id;
const persisted = candidate ? (await recipeRegistry(deps)).get(id)?.recipe : entry.recipe;
+ if (persisted?.validation?.profile !== undefined && persisted.validation.profile !== (args.profile ?? '')) {
+ return errorResult('recipe', '配方属于另一浏览器 profile;请显式使用原 profile,或为当前身份重新整理配方');
+ }
if (runningRecipes.has(id)) return errorResult('recipe', '该配方正在执行,请勿并发重放');
if (candidate && persisted?.validation && persisted.validation.site !== args.site) {
return errorResult('recipe', '已有配方的修订必须保存在原站点,请保持相同 site');
@@ -797,7 +845,16 @@ export function registerBrowserTools(registry: BrowserToolRegistry, deps: Browse
}).finally(() => runningRecipes.delete(id));
let maintenanceMessage: string | undefined;
if (runResult.ok && candidate) {
- verifiedDrafts.set(id, { site: args.site!, content: JSON.stringify(entry.recipe) });
+ verifiedDrafts.set(id, { site: args.site!, content: JSON.stringify(entry.recipe), profile: args.profile ?? '' });
+ } else if (runResult.ok && persisted?.validation?.state === 'candidate' && deps.saveUserRecipe) {
+ // Promotion describes the actual checks on this invocation, not
+ // proof of every possible parameter combination. Never replay it.
+ try {
+ const saved = await deps.saveUserRecipe({ site: persisted.validation.site,
+ recipe: { ...persisted, validation: { ...persisted.validation, state: 'active' } } });
+ if (!saved.ok) maintenanceMessage = '本次执行成功,候选状态保存失败;下次仍会按候选验证。';
+ recipeCache = null;
+ } catch { maintenanceMessage = '本次执行成功,候选状态保存失败;下次仍会按候选验证。'; }
} else if (!runResult.ok && lastCallDispatched && runResult.failureKind !== 'input' && runResult.failedStep !== undefined) {
// A failed draft is not evidence that the saved active version is
// stale. Keep its state, while limiting new/previously failed drafts.
@@ -812,7 +869,7 @@ export function registerBrowserTools(registry: BrowserToolRegistry, deps: Browse
.filter((g) => g.guide.recipes?.includes(id)).map((g) => g.guide.site);
if (sites.length === 1) {
const saved = await deps.saveUserRecipe({ site: sites[0],
- recipe: { ...persisted, validation: { site: sites[0], state: 'suspended' } } });
+ recipe: { ...persisted, validation: { ...persisted.validation, site: sites[0], state: 'suspended' } } });
if (!saved.ok) maintenanceMessage = '本任务已暂停;跨任务停用保存失败,请勿复用旧配方。';
recipeCache = null;
} else maintenanceMessage = '本任务已暂停;无法确定配方所属站点,未保存跨任务停用状态。';
@@ -821,8 +878,10 @@ export function registerBrowserTools(registry: BrowserToolRegistry, deps: Browse
}
return {
content: [
- { type: 'text', text: resultText({ action: 'recipe', provenance: entry.provenance, ...runResult,
- ...(!runResult.ok ? { recovery, maintenanceMessage } : candidate ? { verified: true } : {}) }) },
+ { type: 'text', text: textResult({ action: 'recipe', provenance: entry.provenance, ...runResult,
+ ...(maintenanceMessage ? { maintenanceMessage } : {}),
+ ...(runResult.ok && lintBrowserOutput(runResult.output).length ? { advisory: lintBrowserOutput(runResult.output) } : {}),
+ ...(!runResult.ok ? { recovery, maintenanceMessage } : candidate ? { verified: true } : {}) }, { profile: args.profile, targetId: activeTargetId }) },
],
isError: !runResult.ok,
};
@@ -848,6 +907,10 @@ export function registerBrowserTools(registry: BrowserToolRegistry, deps: Browse
} catch (err) {
return errorResult('siteguide', `siteguide registry error: ${err instanceof Error ? err.message : String(err)}`);
}
+ if (args.site && args.intent) {
+ return { content: [{ type: 'text', text: resultText({ ok: true, action: 'siteguide',
+ site: args.site, recipes: suggestRecipes(recipeReg, args.site.toLowerCase(), args.intent, args.profile) }) }] };
+ }
const recipeInputsOf = (ids: string[] | undefined, compact = false) =>
(ids ?? []).map((id) => {
const r = recipeReg.get(id);
@@ -983,11 +1046,14 @@ export function registerBrowserTools(registry: BrowserToolRegistry, deps: Browse
const issue = draftIssue(parsed.data, args.site);
if (issue) return errorResult('saveRecipe', issue);
const verified = verifiedDrafts.get(parsed.data.id);
- if (!verified || verified.site !== args.site || verified.content !== JSON.stringify(parsed.data)) {
+ if (args.deferValidation) {
+ if (parsed.data.access !== 'read') return errorResult('saveRecipe', '延后验证仅支持声明为 read 的新流程;写操作沿用当次授权和已执行验证');
+ if ((await recipeRegistry(deps)).has(parsed.data.id)) return errorResult('saveRecipe', '已有配方必须先验证修订,不能被未验证候选覆盖');
+ } else if (!verified || verified.site !== args.site || verified.content !== JSON.stringify(parsed.data) || verified.profile !== (args.profile ?? '')) {
return errorResult('saveRecipe', '请先用 action=recipe、site、相同 recipeDraft 试跑并通过校验;不能保存未验证或已改动的配方');
}
const saved = await deps.saveUserRecipe({ site: args.site,
- recipe: { ...parsed.data, validation: { site: args.site, state: 'active' } }, siteGuide: guide });
+ recipe: { ...parsed.data, validation: { site: args.site, state: args.deferValidation ? 'candidate' : 'active', profile: args.profile ?? '' } }, siteGuide: guide });
if (saved.ok) {
verifiedDrafts.delete(parsed.data.id);
failedRecipes.delete(parsed.data.id);
@@ -998,7 +1064,7 @@ export function registerBrowserTools(registry: BrowserToolRegistry, deps: Browse
}
return {
content: [
- { type: 'text', text: resultText({ ok: saved.ok, action: 'saveRecipe', path: saved.path, message: saved.message }) },
+ { type: 'text', text: resultText({ ok: saved.ok, action: 'saveRecipe', state: args.deferValidation ? 'candidate' : 'active', path: saved.path, message: saved.message }) },
],
isError: !saved.ok,
};
@@ -1088,11 +1154,58 @@ export function registerBrowserTools(registry: BrowserToolRegistry, deps: Browse
// error so the agent sees + acts on the embedded hint.
const inner = (result.data as { result?: { ok?: boolean } } | undefined)?.result;
const extractFailed = args.action === 'extract' && inner?.ok === false;
+ // Optional experience work must never turn a completed action into a
+ // failure (especially a write that the agent might otherwise replay).
+ const targetId = readTargetId(result) ?? args.request?.targetId ?? args.targetId;
+ const targetKey = targetId && JSON.stringify([args.profile ?? '', targetId]);
+ let retainResult = true;
+ try {
+ if (args.action === 'stop') { experiences.clear(); discovered.clear(); results.clear(); }
+ const restricted = deps.pageReadsRestricted && await deps.pageReadsRestricted({ profile: args.profile, targetId }).catch(() => true);
+ if (restricted) { retainResult = false; results.clear(); }
+ if (!result.ok || extractFailed || restricted || args.action === 'close' || args.request?.kind === 'close') {
+ if (targetKey) experiences.clear(targetKey);
+ } else if (args.action === 'open' || args.action === 'navigate') {
+ const actualUrl = (result.data as { url?: unknown } | undefined)?.url;
+ const url = typeof actualUrl === 'string' ? actualUrl : args.url ?? args.targetUrl;
+ if (url) {
+ const site = new URL(url).hostname;
+ if (targetKey) experiences.start(targetKey, url);
+ const user = await resolveUserLayer(deps);
+ const key = JSON.stringify([site, args.profile ?? '', args.intent ?? '']);
+ const version = user?.version ?? '';
+ if (discovered.get(key) !== version) {
+ const suggestions = suggestRecipes(recipeRegistryFrom(user), site, args.intent, args.profile);
+ if (discovered.size >= 64) discovered.delete(discovered.keys().next().value!);
+ discovered.set(key, version);
+ if (suggestions.length) result = { ...result, recipeSuggestions: suggestions } as typeof result;
+ }
+ }
+ } else if (targetKey && deps.experienceStore) {
+ const kind = args.action === 'extract' ? 'extract' : args.action === 'act' ? args.request?.kind : undefined;
+ if (kind && ['click', 'type', 'select', 'press', 'wait', 'extract', 'evaluate'].includes(kind)) {
+ const observation = experiences.step(targetKey, kind as ExperienceAction);
+ if (observation && inner?.ok !== false) {
+ const saved = await deps.experienceStore.record(observation);
+ const hintKey = JSON.stringify([saved.site, saved.actions]);
+ if (saved.observations >= 2 && !learningHints.has(hintKey)) {
+ if (learningHints.size >= 64) learningHints.delete(learningHints.values().next().value!);
+ learningHints.add(hintKey);
+ result = { ...result, learningOpportunity: { site: saved.site, observations: saved.observations,
+ hint: '相同操作形状已重复出现(不代表业务相同)。若预计还会使用且没有合适配方,用 recipeHelp 按当前成功步骤整理;可保存候选,等下一次真实任务验证。偶发操作无需学习。' } } as typeof result;
+ }
+ }
+ }
+ }
+ } catch { /* Structural hints are best effort; the operation result wins. */ }
+ const advisory = lintBrowserOutput((result.data as { result?: unknown } | undefined)?.result);
+ if (advisory.length) result = { ...result, advisory } as typeof result;
return {
- content: [{ type: 'text', text: resultText(result) }],
+ content: [{ type: 'text', text: retainResult ? textResult(result as unknown as Record<string, unknown>, { profile: args.profile, targetId }) : resultText(result) }],
isError: !result.ok || extractFailed,
};
} catch (err) {
+ experiences.clear();
deps.logger?.warn?.('browser runtime call failed', {
message: err instanceof Error ? err.message : String(err),
});
diff --git a/packages/lizi-mcps/src/types.ts b/packages/lizi-mcps/src/types.ts
index a81a080ac5..52a5104707 100644
--- a/packages/lizi-mcps/src/types.ts
+++ b/packages/lizi-mcps/src/types.ts
@@ -648,6 +648,8 @@ export interface ResolvedBrowserScreenshot {
/** Browser automation MCP host deps. Core browser execution is injected by host. */
export interface BrowserMcpDeps {
+ /** Local structural observations only; no URLs, scripts, selectors or input values. */
+ experienceStore?: import('./browser/experience.js').BrowserExperienceStore;
getRuntime(): BrowserControlRuntime;
/**
* Resolve a successful screenshot runtime result into verified image bytes.
diff --git a/scripts/browser-experience-live.mjs b/scripts/browser-experience-live.mjs
new file mode 100644
index 0000000000..11304114db
--- /dev/null
+++ b/scripts/browser-experience-live.mjs
@@ -0,0 +1,405 @@
+/** Opt-in public, read-only experiment. Runs the real MCP/runtime on an already
+ * authorized Cindy browser tab; candidate files live in a disposable directory.
+ * Measures tool text and browser calls, not provider billing or model reasoning.
+ */
+import assert from 'node:assert/strict';
+import fs from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import { pathToFileURL } from 'node:url';
+import { createHash } from 'node:crypto';
+import { createServer } from 'vite';
+
+const opt = (name) =>
+ process.argv.find((arg) => arg.startsWith(`--${name}=`))?.slice(name.length + 3);
+const sourceRoot = path.resolve(opt('source-root') ?? process.cwd());
+const baselineRoot = opt('baseline-root');
+const cdpUrl = opt('cdp-url');
+const targetId = opt('target');
+const output = opt('out');
+if (!cdpUrl || !targetId || !output || !baselineRoot)
+ throw new Error('需要 --cdp-url --target --out --baseline-root');
+const temp = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-experience-live-'));
+process.env.XDT_BROWSER_RUNTIME_DIR = path.join(temp, 'runtime');
+const report = {
+ startedAt: new Date().toISOString(),
+ sourceRoot,
+ baselineRoot,
+ calls: [],
+ checks: {},
+ scope: '真实生产 MCP 和浏览器运行时;无额外模型;工具文本不等于供应商账单',
+};
+let current;
+let vite, baselineVite, disconnect;
+const moduleAt = (file) => import(pathToFileURL(path.join(sourceRoot, file)).href);
+const makeVite = (root) =>
+ createServer({
+ root,
+ configFile: false,
+ appType: 'custom',
+ optimizeDeps: { noDiscovery: true, include: [], entries: [] },
+ server: { middlewareMode: true, watch: null, hmr: false, ws: false },
+ logLevel: 'error',
+ });
+try {
+ vite = await makeVite(sourceRoot);
+ baselineVite = await makeVite(baselineRoot);
+ const { registerBrowserTools } = await vite.ssrLoadModule(
+ '/packages/lizi-mcps/src/browser/tools.ts',
+ );
+ const { registerBrowserTools: registerBaseline } = await baselineVite.ssrLoadModule(
+ '/packages/lizi-mcps/src/browser/tools.ts',
+ );
+ const { BrowserToolRegistry } = await moduleAt('packages/lizi-mcps/src/browser/tool-registry.ts');
+ const { RecipeSchema } = await vite.ssrLoadModule(
+ '/packages/lizi-mcps/src/browser/recipe-loader.ts',
+ );
+ const { stepToRequest } = await vite.ssrLoadModule(
+ '/packages/lizi-mcps/src/browser/recipe-runner.ts',
+ );
+ const { browserExperienceStore } = await vite.ssrLoadModule(
+ '/apps/desktop/src/main/browser-recipes/experience.ts',
+ );
+ const { createBrowserControlRuntime } = await moduleAt(
+ 'packages/browser-control-runtime/src/runtime.ts',
+ );
+ ({ closePlaywrightBrowserConnection: disconnect } = await moduleAt(
+ 'packages/browser-control-runtime/src/_generated/extension/src/browser/pw-session.ts',
+ ));
+ const runtime = createBrowserControlRuntime({
+ config: {
+ browser: {
+ enabled: true,
+ attachOnly: true,
+ defaultProfile: 'experience-live',
+ profiles: { 'experience-live': { cdpUrl, attachOnly: true, color: '#00D9C5' } },
+ ssrfPolicy: { dangerouslyAllowPrivateNetwork: true },
+ },
+ },
+ logSink: () => {},
+ });
+ const observed = {
+ call: async (req) => {
+ const start = performance.now();
+ const result = await runtime.call(req);
+ current?.runtime.push({
+ action: req.action,
+ kind: req.request?.kind,
+ ok: result.ok,
+ ms: performance.now() - start,
+ });
+ if (current && req.action === 'snapshot') current.original = result;
+ return result;
+ },
+ };
+ const store = browserExperienceStore(path.join(temp, 'recipes'));
+ let version = 0;
+ // The live harness isolates recipe storage; the production host writer/loader
+ // is separately exercised by its filesystem tests. Reload JSON on every call.
+ const savedFile = path.join(temp, 'candidates.json');
+ const readRecipes = async () => {
+ try {
+ return new Map(
+ JSON.parse(await fs.readFile(savedFile, 'utf8')).map((recipe) => [
+ recipe.id,
+ RecipeSchema.parse(recipe),
+ ]),
+ );
+ } catch (err) {
+ if (err.code === 'ENOENT') return new Map();
+ throw err;
+ }
+ };
+ const deps = {
+ getRuntime: () => observed,
+ experienceStore: store,
+ getUserRecipes: async () => ({
+ recipes: await readRecipes(),
+ siteGuides: new Map(),
+ version: `experience-live-${version}`,
+ }),
+ saveUserRecipe: async ({ recipe }) => {
+ const recipes = await readRecipes();
+ recipes.set(recipe.id, recipe);
+ await fs.writeFile(savedFile, JSON.stringify([...recipes.values()]));
+ version++;
+ return { ok: true };
+ },
+ };
+ const fresh = (register = registerBrowserTools) => {
+ const registry = new BrowserToolRegistry();
+ register(registry, deps);
+ return registry;
+ };
+ let registry = fresh();
+ const baseline = fresh(registerBaseline);
+ const call = async (phase, args, owner = registry, allowFailure = false) => {
+ const row = { phase, args: { targetId, ...args }, runtime: [] };
+ report.calls.push(row);
+ current = row;
+ const start = performance.now();
+ const result = await owner.call('browser', row.args);
+ row.ms = performance.now() - start;
+ row.text = result.content
+ .filter((item) => item.type === 'text')
+ .map((item) => item.text)
+ .join('\n');
+ row.result = JSON.parse(row.text);
+ row.isError = Boolean(result.isError);
+ current = undefined;
+ if (!allowFailure) assert.notEqual(row.isError, true, row.text);
+ return row;
+ };
+
+ const url = 'https://itch.io/search?q=sokoban';
+ const opened = await call('automatic-discovery', { action: 'navigate', url, intent: 'search' });
+ assert(opened.result.recipeSuggestions.some((recipe) => recipe.id === 'itch-search'));
+ assert.equal(opened.runtime.length, 1);
+ const again = await call('discovery-cache', { action: 'navigate', url, intent: 'search' });
+ assert.equal(again.result.recipeSuggestions, undefined);
+ report.checks.discoveryWithoutExtraBrowserCall = true;
+
+ const recipe = JSON.parse(
+ await fs.readFile(
+ path.join(
+ sourceRoot,
+ 'packages/lizi-mcps/src/browser/cindy-recipes/itch.io/itch-search.recipe.json',
+ ),
+ 'utf8',
+ ),
+ );
+ const readFn = recipe.steps
+ .at(-1)
+ .fn.replaceAll('{{query|js}}', 'sokoban')
+ .replaceAll('{{limit|js}}', '5');
+ const expected = [];
+ for (let i = 0; i < 3; i++) {
+ await call(`precise-${i}`, { action: 'navigate', url }, baseline);
+ const precise = await call(
+ `precise-${i}`,
+ { action: 'act', request: { kind: 'evaluate', fn: readFn } },
+ baseline,
+ );
+ assert.equal(precise.result.data.result.matched, true);
+ expected.push(precise.result.data.result);
+ const reuse = await call(`reuse-${i}`, {
+ action: 'recipe',
+ recipeId: 'itch-search',
+ inputs: { query: 'sokoban', limit: 5 },
+ });
+ assert.deepEqual(reuse.result.output, expected.at(-1));
+ }
+ for (const [query, limit] of [
+ ['picross', 3],
+ ['nonogram', 4],
+ ['cindybenchzzzznomatch20261027', 5],
+ ]) {
+ const run = await call('new-inputs', {
+ action: 'recipe',
+ recipeId: 'itch-search',
+ inputs: { query, limit },
+ });
+ assert.equal(run.result.output.matched, true);
+ assert.equal(run.result.output.count, query.startsWith('cindybench') ? 0 : limit);
+ }
+ report.checks.preciseAndRecipeEqual = true;
+ report.checks.changedInputsAndEmpty = true;
+
+ // A separate public flow has no bundled recipe: observe twice across fresh
+ // MCP instances. Both use the same real host experience file.
+ const quoteUrl = 'https://quotes.toscrape.com/search.aspx';
+ const filterUrl = 'https://quotes.toscrape.com/filter.aspx';
+ // Selectors were observed in the preceding public-site experiment. Check
+ // the selected values and every quote rather than treating clicks as proof.
+ const draft = {
+ id: 'live-quote-search',
+ access: 'read',
+ match: ['quotes.toscrape.com'],
+ description: '按作者和标签查询语录',
+ inputs: { author: { required: true }, tag: { required: true } },
+ steps: [
+ { action: 'navigate', url: quoteUrl },
+ { action: 'wait', selector: '#author', timeoutMs: 10000 },
+ {
+ action: 'select',
+ selector: '#author',
+ values: ['{{author}}'],
+ guard: { url: quoteUrl, selector: '#author' },
+ },
+ {
+ action: 'wait',
+ fn: "() => location.pathname === '/filter.aspx' && document.querySelector('#author')?.value === '{{author|js}}' && [...(document.querySelector('#tag')?.options || [])].some(o=>o.value === '{{tag|js}}')",
+ timeoutMs: 10000,
+ },
+ {
+ action: 'select',
+ selector: '#tag',
+ values: ['{{tag}}'],
+ guard: { url: filterUrl, selector: '#tag' },
+ },
+ {
+ action: 'click',
+ selector: "input[name='submit_button']",
+ guard: { url: filterUrl, selector: "input[name='submit_button']" },
+ },
+ { action: 'wait', selector: '.results .quote', timeoutMs: 10000 },
+ {
+ action: 'evaluate',
+ guard: { url: filterUrl, selector: '.results' },
+ fn: "() => { const author=document.querySelector('#author').value, tag=document.querySelector('#tag').value; const rows=[...document.querySelectorAll('.results .quote')].map(q=>({text:q.querySelector('.content').textContent.trim(),author:q.querySelector('.author').textContent.trim(),tag:q.querySelector('.tag').textContent.trim()})); return {author,tag,rows,matched:author==='{{author|js}}' && tag==='{{tag|js}}' && rows.length>0 && rows.every(r=>r.author===author && r.tag===tag)}; }",
+ as: 'result',
+ expect: { equals: { matched: true } },
+ },
+ ],
+ output: '{{result}}',
+ };
+ for (let i = 0; i < 2; i++) {
+ registry = fresh();
+ const inputs = i
+ ? { author: 'J.K. Rowling', tag: 'choices' }
+ : { author: 'Albert Einstein', tag: 'learning' };
+ let read;
+ for (const step of draft.steps) read = await call(`observe-${i}`, stepToRequest(step, inputs));
+ assert.equal(read.result.data.result.matched, true);
+ if (i === 1) assert(read.result.learningOpportunity);
+ }
+ report.checks.repetitionAcrossToolSessions = true;
+ await call('learn-help', { action: 'recipeHelp', site: 'quotes.toscrape.com' });
+ const save = await call('learn-candidate', {
+ action: 'saveRecipe',
+ site: 'quotes.toscrape.com',
+ recipeDraft: draft,
+ deferValidation: true,
+ });
+ assert.equal(save.result.state, 'candidate');
+ assert.equal(save.runtime.length, 0);
+ registry = fresh();
+ const newInputs = { author: 'Albert Einstein', tag: 'music' };
+ const use = await call('candidate-real-use', {
+ action: 'recipe',
+ recipeId: draft.id,
+ inputs: newInputs,
+ });
+ assert.equal(use.result.ok, true);
+ assert.equal(use.result.output.matched, true);
+ assert.equal(use.result.output.tag, 'music');
+ assert.equal((await readRecipes()).get(draft.id).validation.state, 'active');
+ report.checks.candidateSavedWithoutReplayAndPromotedNextSession = true;
+ report.experiences = await store.list('quotes.toscrape.com');
+
+ // Fail one candidate guard, then do the permitted repair. Never write to the website.
+ const broken = {
+ ...draft,
+ id: 'live-quote-broken',
+ steps: draft.steps.map((step, i) =>
+ i === draft.steps.length - 1
+ ? { ...step, guard: { ...step.guard, selector: '#missing-for-test' } }
+ : step,
+ ),
+ };
+ await call('repair-setup', {
+ action: 'saveRecipe',
+ site: 'quotes.toscrape.com',
+ recipeDraft: broken,
+ deferValidation: true,
+ });
+ const failed = await call(
+ 'repair-failure',
+ { action: 'recipe', recipeId: broken.id, inputs: newInputs },
+ registry,
+ true,
+ );
+ assert.equal(failed.result.failureKind, 'guard');
+ assert.equal((await readRecipes()).get(broken.id).validation.state, 'suspended');
+ await call('repair-observe', {
+ action: 'snapshot',
+ selector: 'form',
+ refs: 'role',
+ compact: true,
+ maxChars: 3000,
+ });
+ const repaired = { ...draft, id: broken.id };
+ assert.equal(
+ (
+ await call('repair-trial', {
+ action: 'recipe',
+ site: 'quotes.toscrape.com',
+ recipeDraft: repaired,
+ inputs: newInputs,
+ })
+ ).result.verified,
+ true,
+ );
+ await call('repair-save', {
+ action: 'saveRecipe',
+ site: 'quotes.toscrape.com',
+ recipeDraft: repaired,
+ });
+ report.checks.singleRepair = true;
+
+ await call('digest-setup', { action: 'navigate', url });
+ const snapshot = await call('digest', {
+ action: 'snapshot',
+ snapshotFormat: 'ai',
+ refs: 'aria',
+ maxChars: 160000,
+ });
+ assert(snapshot.result.fullResult);
+ let offset = 0,
+ full = '';
+ do {
+ const part = await call('digest-readback', {
+ action: 'readResult',
+ resultId: snapshot.result.fullResult.id,
+ offset,
+ maxChars: 24000,
+ });
+ assert.equal(part.runtime.length, 0);
+ full += part.result.text;
+ offset = part.result.nextOffset;
+ } while (offset !== null);
+ assert.deepEqual(JSON.parse(full), snapshot.original);
+ report.checks.digestExactRoundTrip = true;
+ report.digest = {
+ originalText: JSON.stringify(snapshot.original),
+ summaryText: snapshot.text,
+ sha256: createHash('sha256').update(full).digest('hex'),
+ };
+ report.prompt = {};
+ for (const [label, root] of [
+ ['before', baselineRoot],
+ ['after', sourceRoot],
+ ]) {
+ const workflow = await fs.readFile(
+ path.join(root, 'packages/lizi-mcps/src/browser/prompts/rules/browser-workflow.md'),
+ 'utf8',
+ );
+ const author = await fs.readFile(
+ path.join(root, 'packages/lizi-mcps/src/browser/prompts/rules/recipe-author.md'),
+ 'utf8',
+ );
+ report.prompt[label] = {
+ workflow,
+ author,
+ common: label === 'before' ? workflow + author : workflow,
+ };
+ }
+ report.finishedAt = new Date().toISOString();
+} catch (err) {
+ report.error = err.stack ?? String(err);
+ process.exitCode = 1;
+} finally {
+ await fs.writeFile(output, JSON.stringify(report, null, 2));
+ await disconnect?.();
+ await vite?.close();
+ await baselineVite?.close();
+ await fs.rm(temp, { recursive: true, force: true });
+ console.log(
+ JSON.stringify({
+ output,
+ checks: report.checks,
+ error: report.error,
+ calls: report.calls.length,
+ }),
+ );
+}