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): 优化操作观察并支持配方按使用校验与修复

Dash4cd49ac27432
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 a6aa62adec..687369aa14 100644
--- a/apps/desktop/src/main/browser-recipes/__tests__/writer.test.ts
+++ b/apps/desktop/src/main/browser-recipes/__tests__/writer.test.ts
@@ -12,7 +12,7 @@ vi.mock('electron', () => ({
}));
const { writeUserRecipe, resetSiteRecipe } = await import('../writer.js');
-const { buildUserRecipes } = await import('../loader.js');
+const { loadUserBrowserRecipes } = await import('../loader.js');
let dir: string;
beforeEach(async () => {
@@ -23,10 +23,8 @@ afterEach(async () => {
});
/** Read a site's L2 files back the way the loader would. */
-async function readBack(site: string) {
- const recipeRaw = await fs.readFile(path.join(dir, site, 'recipe.json'), 'utf8').catch(() => null);
- const entries = recipeRaw ? { [`${site}/recipe.json`]: recipeRaw } : {};
- return buildUserRecipes(entries, {});
+async function readBack(_site: string) {
+ return loadUserBrowserRecipes(dir);
}
describe('writeUserRecipe / resetSiteRecipe', () => {
@@ -45,11 +43,31 @@ describe('writeUserRecipe / resetSiteRecipe', () => {
await writeUserRecipe({ site: 'x.com', recipe: { id: 'r', steps: [{ action: 'navigate', url: 'https://one/' }] } }, dir);
await writeUserRecipe({ site: 'x.com', recipe: { id: 'r', steps: [{ action: 'navigate', url: 'https://two/' }] } }, dir);
const files = await fs.readdir(path.join(dir, 'x.com'));
- expect(files).toEqual(['recipe.json']); // single file, overwritten
+ expect(files).toEqual(['recipes']);
+ expect(await fs.readdir(path.join(dir, 'x.com', 'recipes'))).toHaveLength(1);
const back = await readBack('x.com');
expect((back.recipes.get('r')?.steps[0] as { url: string }).url).toBe('https://two/');
});
+ it('loads a legacy recipe with its owning site so a future failure can suspend it', async () => {
+ await fs.mkdir(path.join(dir, 'legacy.example'));
+ await fs.writeFile(path.join(dir, 'legacy.example', 'recipe.json'), JSON.stringify({ id: 'legacy', steps: [{ action: 'navigate', url: 'https://legacy.example/' }] }));
+ const back = await loadUserBrowserRecipes(dir);
+ expect(back.recipes.get('legacy')?.validation).toEqual({ site: 'legacy.example', state: 'active' });
+ });
+
+ it('keeps multiple flows and suspended state across reload, shadowing the legacy id', async () => {
+ await fs.mkdir(path.join(dir, 'x.com'));
+ await fs.writeFile(path.join(dir, 'x.com', 'recipe.json'), JSON.stringify({ id: 'first', steps: [{ action: 'navigate', url: 'https://old/' }] }));
+ await writeUserRecipe({ site: 'x.com', recipe: { id: 'first', validation: { site: 'x.com', state: 'suspended' }, steps: [{ action: 'navigate', url: 'https://new/' }] } }, dir);
+ await writeUserRecipe({ site: 'x.com', recipe: { id: '../second', steps: [{ action: 'navigate', url: 'https://x.com/' }] } }, dir);
+ const back = await loadUserBrowserRecipes(dir);
+ expect(back.recipes.size).toBe(2);
+ expect(back.recipes.get('first')?.validation?.state).toBe('suspended');
+ expect(back.recipes.get('first')?.steps[0].url).toBe('https://new/');
+ expect(back.recipes.has('../second')).toBe(true);
+ });
+
it('rejects a path-unsafe site segment', async () => {
const res = await writeUserRecipe(
{ site: '../evil', recipe: { id: 'r', steps: [{ action: 'navigate', url: 'https://x/' }] } },
diff --git a/apps/desktop/src/main/browser-recipes/loader.ts b/apps/desktop/src/main/browser-recipes/loader.ts
index 2affb149c2..0b85ae8917 100644
Binary files a/apps/desktop/src/main/browser-recipes/loader.ts and b/apps/desktop/src/main/browser-recipes/loader.ts differ
diff --git a/apps/desktop/src/main/browser-recipes/writer.ts b/apps/desktop/src/main/browser-recipes/writer.ts
index 3dfa0c66bd..8b49de4547 100644
--- a/apps/desktop/src/main/browser-recipes/writer.ts
+++ b/apps/desktop/src/main/browser-recipes/writer.ts
@@ -2,9 +2,8 @@
* L2 user-recipe writer (host side) — the self-grow persistence path.
*
* Writes an agent/user-authored recipe (and optional site guide) into
- * `userData/browser-recipes/<site>/`. Same site → overwrite (a user "optimizing"
- * a site iterates the same recipe; we must NOT auto-rename or the by-id override
- * would split). `resetSite` deletes a site's L2 files so it falls back to the
+ * `userData/browser-recipes/<site>/recipes/`. Same id → overwrite; different
+ * flows on the same site coexist. `resetSite` deletes a site's L2 files so it falls back to the
* bundled L1 (the "restore default" semantics, like override-settings reset).
*
* The L2 `version` is content-derived (see loader.ts), so writing a file is
@@ -12,6 +11,7 @@
* Modeled on `apps/desktop/src/main/local-themes/writer.ts`.
*/
import fs from 'node:fs/promises';
+import crypto from 'node:crypto';
import path from 'node:path';
import { shell } from 'electron';
@@ -19,6 +19,7 @@ import type { Recipe, SiteGuide } from '@cindy/mcps';
import { createLogger } from '../logger.js';
import { userRecipesDir } from './loader.js';
+import { atomicWriteFileSync } from '../utils/atomicWriteFile.js';
const log = createLogger('browser-recipes');
@@ -51,13 +52,14 @@ export async function writeUserRecipe(
const siteDir = path.join(dir, seg);
try {
await fs.mkdir(siteDir, { recursive: true });
- const recipePath = path.join(siteDir, 'recipe.json');
- await fs.writeFile(recipePath, `${JSON.stringify(input.recipe, null, 2)}\n`, 'utf8');
+ // Hash arbitrary ids to a bounded, path-safe name on every platform.
+ const name = crypto.createHash('sha256').update(input.recipe.id).digest('hex');
+ const recipePath = path.join(siteDir, 'recipes', `${name}.json`);
+ atomicWriteFileSync(recipePath, `${JSON.stringify(input.recipe, null, 2)}\n`);
if (input.siteGuide) {
- await fs.writeFile(
+ atomicWriteFileSync(
path.join(siteDir, 'siteguide.json'),
`${JSON.stringify(input.siteGuide, null, 2)}\n`,
- 'utf8',
);
}
return { ok: true, path: recipePath };
diff --git a/docs/dev-rules/credentials-and-local-storage.md b/docs/dev-rules/credentials-and-local-storage.md
index 921bc88183..93b9b66d66 100644
--- a/docs/dev-rules/credentials-and-local-storage.md
+++ b/docs/dev-rules/credentials-and-local-storage.md
@@ -197,6 +197,7 @@ refresh 与 relay 自救节流。在途 refresh 尚未返回时收到的恢复
| 数据性质 | 正确位置 |
| ----------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Cindy 管理的持久数据 | Desktop 使用 `app.getPath('userData')`,共享 package 由宿主注入等价根目录 |
+| 浏览器用户配方 | `userData/browser-recipes/<site>/recipes/<id 的 SHA-256>.json`,每站多个流程,原子替换;兼容旧 `recipe.json`,新文件优先。只保存配方定义及 active/suspended 状态,不保存试跑的 inputs/页面返回值;禁止写入凭据,业务变动值用 inputs。试跑凭证与单轮修复预算只在 MCP 会话内存中,暂停状态跨重启保留。 |
| 预创建 worktree 的取消标记 | `userData/worktree-cancelled-creations/<sessionId 的 SHA-256>`,空文件原子排他创建;不含路径、草稿或关联密钥。保留以拒绝重启后迟到的创建请求,不按超时删除。只在核实未被任务认领后写入。同路径加 `.lock` 是可释放的跨进程操作锁,复用既有锁协议;同一 profile、同一任务的创建登记与取消回收串行,拿不到锁不得确认回收完成。异步创建完成后、登记前再次核对取消标记 |
| Mobile 已取消创建的草稿 | 复用账号隔离的 durable outbox;持久创建流程先保存草稿、原项目目录和附件,再登记 reservation 和发送远端 worktree 创建;创建回包前暂停发件箱投递。回收确认后,`creation.cancelled` 与原项目目录先持久写入,再忘记回收账本。重建使用新远端 ID,`storageSessionId` 保持原 AsyncStorage 键和附件目录,通过单次记录写入提交;写入失败时原草稿仍可读。编辑页恢复目录时重新探测资格,不沿用旧 worktree 的资格或分支偏好 |
| 可丢弃的临时数据 | `app.getPath('temp')` 或 `os.tmpdir()` 下的任务专属目录 |
diff --git a/packages/browser-control-runtime/src/__tests__/cdp-locality.test.ts b/packages/browser-control-runtime/src/__tests__/cdp-locality.test.ts
new file mode 100644
index 0000000000..1d79557794
--- /dev/null
+++ b/packages/browser-control-runtime/src/__tests__/cdp-locality.test.ts
@@ -0,0 +1,36 @@
+import { describe, expect, it } from 'vitest';
+import { isManagedLocalCdpConnection } from '../shim/cdp-locality.js';
+
+// Production CDP connection eligibility: the historical 2 GiB upload needs
+// shared local paths, but a remote/attached/tunnel endpoint must not get them.
+// Pure unit tier; existing upload tests do not cover connection locality.
+describe('managed CDP shared filesystem eligibility', () => {
+ const endpoint = 'http://127.0.0.1:18800';
+ const ws = 'ws://127.0.0.1:18800/devtools/browser/test';
+ const live = {
+ profile: { cdpUrl: endpoint, cdpIsLoopback: true },
+ running: { proc: { pid: 123, exitCode: null, signalCode: null } },
+ };
+
+ it('uses local paths for the live runtime-owned browser at the same endpoint', () => {
+ expect(isManagedLocalCdpConnection(endpoint, ws, [live])).toBe(true);
+ });
+ it('does not treat loopback attachment or a tunnel as a managed process', () => {
+ expect(isManagedLocalCdpConnection(endpoint, ws, [])).toBe(false);
+ expect(isManagedLocalCdpConnection(endpoint, ws, [{ ...live, running: null }])).toBe(false);
+ });
+ it.each([
+ { pid: 123, exitCode: 0, signalCode: null },
+ { pid: 123, exitCode: null, signalCode: 'SIGTERM' },
+ { pid: undefined, exitCode: null, signalCode: null },
+ ])('does not grant local paths after process exit or failed launch: %j', (proc) => {
+ expect(isManagedLocalCdpConnection(endpoint, ws, [{ ...live, running: { proc } }])).toBe(false);
+ });
+ it.each(['ws://127.0.0.1:18801/browser/test', 'ws://example.com:18800/browser/test', 'invalid'])('rejects a redirected or invalid endpoint: %s', (target) => {
+ expect(isManagedLocalCdpConnection(endpoint, target, [live])).toBe(false);
+ });
+ it('keeps remote configured profiles remote even if there is a process record', () => {
+ const remote = 'http://192.0.2.1:18800';
+ expect(isManagedLocalCdpConnection(remote, remote, [{ ...live, profile: { cdpUrl: remote, cdpIsLoopback: false } }])).toBe(false);
+ });
+});
diff --git a/packages/browser-control-runtime/src/__tests__/interaction-proxy-policy.test.ts b/packages/browser-control-runtime/src/__tests__/interaction-proxy-policy.test.ts
index 7f998d6c64..f8f7e0e58b 100644
--- a/packages/browser-control-runtime/src/__tests__/interaction-proxy-policy.test.ts
+++ b/packages/browser-control-runtime/src/__tests__/interaction-proxy-policy.test.ts
@@ -2,10 +2,10 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
const mocks = vi.hoisted(() => ({
assertBrowserNavigationResultAllowed: vi.fn(async () => undefined),
- assertPageNavigationCompletedSafely: vi.fn(async (_opts?: { page?: unknown }) => undefined),
- closeBlockedNavigationTarget: vi.fn(async () => undefined),
+ assertPageNavigationCompletedSafely: vi.fn(async (_opts: { page: unknown }): Promise<void> => undefined),
+ closeBlockedNavigationTarget: vi.fn(async (_opts: { page: unknown }): Promise<void> => undefined),
getPageForTargetId: vi.fn(),
- quarantineTargetWithoutClosing: vi.fn(async () => undefined),
+ quarantineTargetWithoutClosing: vi.fn(async (_opts: { page: { url(): string } }): Promise<void> => undefined),
refLocator: vi.fn(),
}));
@@ -52,6 +52,22 @@ describe('Playwright interaction proxy navigation policy', () => {
vi.clearAllMocks();
});
+ it.each(['() => false', 'false', 'async () => false'])('does not mistake a function/Promise for a satisfied wait: %s', async (fn) => {
+ const waitForFunction = vi.fn(async (predicate: () => unknown, _arg: unknown, options: { timeout: number }) => {
+ expect(options.timeout).toBe(500); // existing minimum wait timeout
+ expect(typeof predicate).toBe('function');
+ const result = predicate();
+ if (!result) throw new Error('Timeout 500ms exceeded');
+ });
+ const page = { url: () => 'https://example.com/', on: vi.fn(), off: vi.fn(), waitForFunction };
+ mocks.getPageForTargetId.mockResolvedValue(page);
+ await expect(executeActViaPlaywright({ cdpUrl: 'http://127.0.0.1:18800', targetId: 'page-1', evaluateEnabled: true,
+ action: { kind: 'wait', fn, timeoutMs: 200 } })).rejects.toThrow(
+ fn.startsWith('async') ? /synchronous predicate/ : /Timeout/,
+ );
+ expect(waitForFunction).toHaveBeenCalledTimes(1);
+ });
+
it('carries explicit proxy mode into main-frame and subframe checks', async () => {
let currentUrl = 'https://start.example/';
let navigationListener: ((frame: { url(): string }) => void) | undefined;
diff --git a/packages/browser-control-runtime/src/__tests__/runtime.test.ts b/packages/browser-control-runtime/src/__tests__/runtime.test.ts
index e1be971cb1..57412fa947 100644
--- a/packages/browser-control-runtime/src/__tests__/runtime.test.ts
+++ b/packages/browser-control-runtime/src/__tests__/runtime.test.ts
@@ -2,6 +2,33 @@ import { describe, expect, it } from 'vitest';
import { createBrowserControlRuntime, planDispatch } from '../runtime.js';
import { createUnavailableBrowserRuntime } from '../unavailable.js';
+import { resolveActionTargetIds } from '../shim/browser-action-targets.js';
+
+// Historical Play/AWS labels failed after tab selection had resolved their ID.
+// Unit tier: exercise the same normalization used by the real /act route;
+// the history replay script covers its wiring against real Chrome.
+describe('resolved action target identity', () => {
+ it.each([undefined, 'google-play-review-status', 'raw-tab-id'])(
+ 'executes an action on the selected tab when its target is %s', (targetId) => {
+ expect(resolveActionTargetIds({ kind: 'wait', timeMs: 1, targetId }, 'google-play-review-status', 'raw-tab-id'))
+ .toEqual({ kind: 'wait', timeMs: 1, targetId: 'raw-tab-id' });
+ },
+ );
+
+ it('normalizes nested batches without allowing a different target or mutating the request', () => {
+ const action = {
+ kind: 'batch' as const,
+ targetId: 'aws-ce',
+ actions: [{ kind: 'batch' as const, actions: [{ kind: 'wait' as const, timeMs: 1, targetId: 'aws-ce' }] }],
+ };
+ expect(resolveActionTargetIds(action, 'aws-ce', 'raw-id')).toMatchObject({
+ targetId: 'raw-id', actions: [{ targetId: 'raw-id', actions: [{ targetId: 'raw-id' }] }],
+ });
+ expect(action.actions[0].actions[0].targetId).toBe('aws-ce');
+ action.actions[0].actions[0].targetId = 'different-tab';
+ expect(() => resolveActionTargetIds(action, 'aws-ce', 'raw-id')).toThrow('targetId must match');
+ });
+});
describe('createUnavailableBrowserRuntime', () => {
it('reports BROWSER_RUNTIME_NOT_CONFIGURED for any action', async () => {
diff --git a/packages/browser-control-runtime/src/_generated/extension/src/browser/pw-session.ts b/packages/browser-control-runtime/src/_generated/extension/src/browser/pw-session.ts
index b47f8a28a8..e92550fb6d 100644
--- a/packages/browser-control-runtime/src/_generated/extension/src/browser/pw-session.ts
+++ b/packages/browser-control-runtime/src/_generated/extension/src/browser/pw-session.ts
@@ -9,6 +9,7 @@
*/
import crypto from "node:crypto";
import path from "node:path";
+import { isManagedLocalCdpConnection } from "../../../../shim/cdp-locality.js";
import {
isFutureDateTimestampMs,
parseFiniteNumber,
@@ -945,9 +946,13 @@ async function connectBrowser(cdpUrl: string, ssrfPolicy?: SsrFPolicy): Promise<
const endpoint = wsUrl ?? normalized;
const connectEndpoint = async (target: string) => {
const headers = getHeadersWithAuth(target);
+ const { getBrowserControlState } = await import("../browser-control-state.js");
+ const isLocal = isManagedLocalCdpConnection(
+ normalized, target, getBrowserControlState()?.profiles.values() ?? [],
+ );
// Bypass proxy for loopback CDP connections (#31219)
return await withNoProxyForCdpUrl(target, () =>
- chromium.connectOverCDP(target, { timeout, headers }),
+ chromium.connectOverCDP(target, { timeout, headers, isLocal }),
);
};
let browser: Browser;
diff --git a/packages/browser-control-runtime/src/_generated/extension/src/browser/pw-tools-core.interactions.ts b/packages/browser-control-runtime/src/_generated/extension/src/browser/pw-tools-core.interactions.ts
index 64a5f1a1c4..38f3d526bc 100644
--- a/packages/browser-control-runtime/src/_generated/extension/src/browser/pw-tools-core.interactions.ts
+++ b/packages/browser-control-runtime/src/_generated/extension/src/browser/pw-tools-core.interactions.ts
@@ -1760,7 +1760,16 @@ export async function waitForViaPlaywright(opts: {
if (opts.fn) {
const fn = normalizeOptionalString(opts.fn) ?? "";
if (fn) {
- await waitForStep(page.waitForFunction(fn, { timeout }));
+ // Pass a real function so Playwright caches its compilation between
+ // polls (string expressions re-eval and can fail under Trusted Types).
+ // Compile only on the host; execution stays in the page context.
+ const predicate = new Function(
+ "const value = (" + normalizeBrowserEvaluateFunctionSource(fn) + ")(); " +
+ "if (value && typeof value.then === 'function') { " +
+ "Promise.resolve(value).catch(() => {}); throw new Error('wait.fn requires a synchronous predicate'); } " +
+ "return value;",
+ ) as () => unknown;
+ await waitForStep(page.waitForFunction(predicate, undefined, { timeout }));
}
}
},
diff --git a/packages/browser-control-runtime/src/_generated/extension/src/browser/routes/agent.act.ts b/packages/browser-control-runtime/src/_generated/extension/src/browser/routes/agent.act.ts
index 09ddbaabe3..e8365e8be8 100644
--- a/packages/browser-control-runtime/src/_generated/extension/src/browser/routes/agent.act.ts
+++ b/packages/browser-control-runtime/src/_generated/extension/src/browser/routes/agent.act.ts
@@ -39,6 +39,7 @@ import {
} from "./agent.act.errors.js";
import { registerBrowserAgentActHookRoutes } from "./agent.act.hooks.js";
import { normalizeActRequest, validateBatchTargetIds } from "./agent.act.normalize.js";
+import { resolveActionTargetIds } from "../../../../../shim/browser-action-targets.js";
import { type ActKind, isActKind } from "./agent.act.shared.js";
import {
browserNavigationPolicyForProfile,
@@ -406,6 +407,7 @@ export function registerBrowserAgentActRoutes(
);
}
+ const requestedAction = action;
await withRouteTabContext({
req,
res,
@@ -413,6 +415,14 @@ export function registerBrowserAgentActRoutes(
targetId,
enforceCurrentUrlAllowed: shouldEnforceCurrentUrlForAct(action),
run: async ({ profileCtx, cdpUrl, tab, resolveTabUrl }) => {
+ let resolvedAction: BrowserActRequest;
+ try {
+ resolvedAction = resolveActionTargetIds(requestedAction, targetId, tab.targetId);
+ } catch {
+ return jsonActError(res, 403, ACT_ERROR_CODES.targetIdMismatch,
+ "action targetId must match request targetId");
+ }
+ const action = resolvedAction;
const evaluateEnabled = ctx.state().resolved.evaluateEnabled;
const navigationPolicy = browserNavigationPolicyForProfile(ctx, profileCtx);
const ssrfPolicy = navigationPolicy.ssrfPolicy;
@@ -449,14 +459,6 @@ export function registerBrowserAgentActRoutes(
...extra,
});
};
- if (action.targetId && action.targetId !== tab.targetId) {
- return jsonActError(
- res,
- 403,
- ACT_ERROR_CODES.targetIdMismatch,
- "action targetId must match request targetId",
- );
- }
const profileName = profileCtx.profile.name;
if (isExistingSession) {
const initialTabTargetIds = hasNavigationResultPolicy
diff --git a/packages/browser-control-runtime/src/shim/browser-action-targets.ts b/packages/browser-control-runtime/src/shim/browser-action-targets.ts
new file mode 100644
index 0000000000..ca2d250084
--- /dev/null
+++ b/packages/browser-control-runtime/src/shim/browser-action-targets.ts
@@ -0,0 +1,19 @@
+import type { BrowserActRequest } from '../_generated/extension/src/browser/client-actions.types.js';
+
+/** Resolve the already-selected tab once, including actions inside a batch. */
+export function resolveActionTargetIds(
+ action: BrowserActRequest,
+ requestedTargetId: string | undefined,
+ resolvedTargetId: string,
+): BrowserActRequest {
+ if (action.targetId && action.targetId !== requestedTargetId && action.targetId !== resolvedTargetId) {
+ throw new Error('action targetId must match request targetId');
+ }
+ return action.kind === 'batch'
+ ? {
+ ...action,
+ targetId: resolvedTargetId,
+ actions: action.actions.map((nested) => resolveActionTargetIds(nested, requestedTargetId, resolvedTargetId)),
+ }
+ : { ...action, targetId: resolvedTargetId };
+}
diff --git a/packages/browser-control-runtime/src/shim/cdp-locality.ts b/packages/browser-control-runtime/src/shim/cdp-locality.ts
new file mode 100644
index 0000000000..40a30eaa55
--- /dev/null
+++ b/packages/browser-control-runtime/src/shim/cdp-locality.ts
@@ -0,0 +1,28 @@
+interface ManagedProfile {
+ profile: { cdpUrl: string; cdpIsLoopback: boolean };
+ running: { proc: { pid?: number; exitCode: number | null; signalCode: string | null } } | null;
+}
+
+/** A loopback URL alone may be a tunnel. Require our live managed process too. */
+export function isManagedLocalCdpConnection(
+ configuredEndpoint: string,
+ connectedEndpoint: string,
+ profiles: Iterable<ManagedProfile>,
+): boolean {
+ const address = (value: string) => {
+ const url = new URL(value);
+ if (!['http:', 'https:', 'ws:', 'wss:'].includes(url.protocol)) return null;
+ if (!['127.0.0.1', '[::1]', 'localhost'].includes(url.hostname)) return null;
+ return `${url.hostname}:${url.port || (['https:', 'wss:'].includes(url.protocol) ? '443' : '80')}`;
+ };
+ try {
+ const expected = address(configuredEndpoint);
+ if (!expected || address(connectedEndpoint) !== expected) return false;
+ for (const { profile, running } of profiles) {
+ const proc = running?.proc;
+ if (profile.cdpIsLoopback && address(profile.cdpUrl) === expected
+ && proc?.pid && proc.exitCode === null && proc.signalCode === null) return true;
+ }
+ } catch { /* An unknown endpoint never gets shared-filesystem privileges. */ }
+ return false;
+}
diff --git a/packages/browser-control-runtime/upstream/MAINTAINING.md b/packages/browser-control-runtime/upstream/MAINTAINING.md
index e0b7472078..8f4030d9f9 100644
--- a/packages/browser-control-runtime/upstream/MAINTAINING.md
+++ b/packages/browser-control-runtime/upstream/MAINTAINING.md
@@ -170,7 +170,13 @@ pnpm --filter @cindy/browser-control-runtime test # 契约 + SSRF guard
## 9. 提效能力(network / extract / recipe / sitemap)
-在"自启动 Chrome + CDP"之上加的一层"高效原语 + 站点知识",目标是把盲探的 token/步数打下来。全部增量、不改 `_generated/`。
+在"自启动 Chrome + CDP"之上加的一层"高效原语 + 站点知识",目标是把盲探的 token/步数打下来。生成层行为通过 `sync.mjs` 的 LOCAL_PATCH 保留,禁止手改 `_generated/`。
+
+- **标签页别名**:`act` 路由在选择目标页后,经 `shim/browser-action-targets.ts` 将顶层及嵌套动作的同一别名换成真实 ID;不同目标仍拒绝。不能拿 label 与真实 ID 直接比较,否则工具推荐的 label 会在 click/wait 时误报不一致。
+- **本机大文件**:Playwright `connectOverCDP` 只有在既有 runtime state 证明该端点属于本进程启动且未退出的 Chrome、连接端点仍匹配同一 loopback 地址时才传 `isLocal:true`。复用 Playwright 本地路径上传,避免错误触发远程传输的 50 MB 限制;远程、attach-only 和仅 loopback 但没有托管进程证据的连接不启用。路径校验及交互导航守卫不变。连接判定见 `shim/cdp-locality.ts`。
+- **`afterSnapshot`(L2 MCP)**:`act`(不含 close)/ `open` / `navigate` / `upload` 可选择一次返回动作与后置快照,默认 compact、正文 4000 字符,支持 selector/frame 局部读取(自动用 role refs)。真实 Google Play 验证发现底层 role snapshot 忽略 maxChars,因此 L2 额外限制正文并移除截断部分的 refs,返回 truncated 提示;refs 等元数据不计入正文预算。不带参数的旧调用保持原行为;后置读失败保留动作成功,模型只能补读、不能重放写操作。沿用登录墙提示和代输入后的读取限制,不增加重试、缓存或持久状态。后置快照不保证 SPA 已加载完,缺少验收内容仍须等待后补读。
+- **历史复现对照**:`node --import tsx scripts/browser-history-replay.mjs --mode=baseline|optimized --out=<报告路径>`。使用隔离真实 Chrome 和本地重建页面,覆盖 Google Play/AWS 历史请求形状、64 MB/2 GB 文件选择回读及问卷步骤。baseline 需在修改前执行,optimized 在修改后执行;只切换 mode 不代表切换产品版本。比较结果字符数、模型侧工具调用次数和操作结果,不把它说成真实商店重发布、模型 token/缓存率或线上耗时对比。
+- **实际页面对照**:`scripts/browser-live-history-compare.mjs` 按 `--source-root` 加载指定 checkout 的真实 MCP/runtime,用 attach-only 连接已授权的 Cindy 专用浏览器,不启停 Chrome 或复制登录态。页面计划中的 role/name/href/selector 必须来自当次侦察;每步校验 URL 与实际业务信息,加载未完成的等待和补读计入指标。登录、重置起始页面、独立 alias 探测不计入流程;原始步骤与结果落到显式 `--out` 路径。只用于已授权的只读导航,不把线上提交、上传或发布塞进比较计划。
- **`requests` / `responseBody`(L1 runtime)**:接的是 vendored **已存在但原先没接线**的两条路由(`GET /requests`、`POST /response/body`,见 `_generated/.../pw-tools-core.activity.ts` / `pw-tools-core.responses.ts`)。runtime 复用 per-page 自动捕获缓冲(上限 500、page 关闭自动清),`runtime.ts` 的 `planDispatch` 加两个 case 即可,无新监听、无泄漏。语义:很多页面背后是 JSON API,读接口比扒 DOM 又稳又省。`responseBody` 在 chrome-mcp 接管态返 501,但默认 managed profile 不触发。
- **`extract`(L2 MCP,`extract.ts`)**:纯组合现有 `act:evaluate`。`buildExtractFnSource(spec)` 是**纯函数**,把字段 schema 编译成注入 JS(选择器一律 `JSON.stringify` 注入,防注入),handler 改写成 `act:{kind:'evaluate',fn}`。不碰 runtime 包。**报错教模型(对齐上游 `SELECTOR_UNSUPPORTED_MESSAGE` 范式)**:生成的 fn 给 `querySelector` 包 try/catch,非法选择器 → 返回 `{ok:false, error, hint}`(`EXTRACT_FIELD_HINT` 教正确字段格式);handler 跑前用 `collectSelectors` 预检 selector 含 `@`(观察到模型爱写 `h3 a@title`)→ 直接返回教学报错,不空跑。**不加 `@attr` 语法糖**(上游无此约定)。
@@ -191,6 +197,14 @@ pnpm --filter @cindy/browser-control-runtime test # 契约 + SSRF guard
> 加新 action 改了 `browser` 工具 schema → 会话启动一次性注册(`maker-core/.../claude-code/index.ts:713`),一次性失效缓存前缀、稳态不降;按规则 10 实测。新增 action 要两端同步:runtime `types.ts` 的 `BrowserControlAction` ⇄ `tools.ts` 的 `ACTIONS`(exhaustive switch 会强制对齐)。
+### 配方按使用维护与等待条件(2026-10-23)
+
+- `recipe` 支持 `site + recipeDraft` 内存试跑;`saveRecipe` 仅接受同一 MCP 会话已通过验证的相同内容。正常检查不请求模型,不定时后台刷新;失败交给当前任务模型观察、同 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`。宿主运行版不会因源码修改自动更新。
+
## 10. 相关文档
- `README.md` — runtime 包速览 + 安全说明(本目录上一级)。
diff --git a/packages/browser-control-runtime/upstream/browser-runtime.lock.json b/packages/browser-control-runtime/upstream/browser-runtime.lock.json
index 6bce2238b6..84679f55b9 100644
--- a/packages/browser-control-runtime/upstream/browser-runtime.lock.json
+++ b/packages/browser-control-runtime/upstream/browser-runtime.lock.json
@@ -62,6 +62,10 @@
"file": "extension/src/browser/navigation-guard.ts",
"desc": "allow explicit browser proxies only for public hostnames named in the strict hostname allowlist"
},
+ {
+ "file": "extension/src/browser/pw-session.ts",
+ "desc": "use Playwright local-path uploads only for a live browser managed by this runtime"
+ },
{
"file": "extension/src/browser/pw-session.ts",
"desc": "export a non-blocking quarantine so the popup-overflow path can mark a target unusable without awaiting close() (a hung page must not keep the interaction pending)"
@@ -86,6 +90,10 @@
"file": "extension/src/browser/routes/agent.act.hooks.ts",
"desc": "apply the effective browser proxy mode to direct input file uploads"
},
+ {
+ "file": "extension/src/browser/routes/agent.act.ts",
+ "desc": "resolve the selected tab alias before comparing or executing action targets"
+ },
{
"file": "extension/src/browser/routes/agent.act.ts",
"desc": "carry the effective browser proxy mode through interaction navigation guards"
@@ -112,7 +120,7 @@
}
],
"fileCount": 335,
- "contentHash": "9a4e02b5c865d4f3cec6e44b1862050ba706542d96a67f564c4c3b60cf7fdc97",
+ "contentHash": "0e6dedbbe3e2c850ccd4867e21b8fda3b25837b0d8145c6f0a4a6c47603447c7",
"fsSafe": {
"package": "@openclaw/fs-safe",
"version": "0.4.0"
diff --git a/packages/browser-control-runtime/upstream/shim-spec.md b/packages/browser-control-runtime/upstream/shim-spec.md
index b2bea64ea6..9e0a8df561 100644
--- a/packages/browser-control-runtime/upstream/shim-spec.md
+++ b/packages/browser-control-runtime/upstream/shim-spec.md
@@ -1,9 +1,15 @@
## agent-harness-runtime (6)
AnyAgentTool, NodeListNode, callGatewayTool, listNodes, resolveNodeIdFromList, selectDefaultNodeFromList
+## browser-action-targets (1, local patch)
+resolveActionTargetIds
+
## browser-config (3)
movePathToTrash, parseBrowserHttpUrl, redactCdpUrl
+## cdp-locality (1, local patch)
+isManagedLocalCdpConnection
+
## channel-actions (6)
imageResultFromFile, jsonResult, optionalStringEnum, readPositiveIntegerParam, readStringParam, stringEnum
diff --git a/packages/lizi-mcps/src/browser/browserMcpServer.test.ts b/packages/lizi-mcps/src/browser/browserMcpServer.test.ts
index 5bdee1448a..19c0e98cd1 100644
--- a/packages/lizi-mcps/src/browser/browserMcpServer.test.ts
+++ b/packages/lizi-mcps/src/browser/browserMcpServer.test.ts
@@ -43,6 +43,102 @@ async function makeHarness(
}
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,
+ // select the returned tab, and retain the existing password-handoff behavior.
+ it.each([{}, { selector: '#form', maxChars: 1000 }])('returns an opt-in post-action snapshot on the actual resulting tab: %j', async (afterSnapshot) => {
+ const h = await makeHarness({}, (request) => request.action === 'snapshot'
+ ? { targetId: 'new-tab', snapshot: '- button "Continue" [ref=e1]' }
+ : request.request && (request.request as { kind: string }).kind === 'evaluate'
+ ? { result: { password: true } }
+ : { targetId: 'new-tab' });
+ try {
+ const response = await h.client.callTool({ name: 'call_tool', arguments: { name: 'browser', args: {
+ action: 'act', targetId: 'old-tab', request: { kind: 'click', ref: 'e2' }, afterSnapshot,
+ } } });
+ expect(response.isError).toBe(false);
+ expect(JSON.parse((response.content as Array<{ text: string }>)[0].text)).toMatchObject({
+ ok: true, data: { targetId: 'new-tab' }, afterSnapshot: {
+ ok: true, data: { snapshot: '- button "Continue" [ref=e1]' }, loginWall: { fields: ['password'] },
+ },
+ });
+ expect(h.calls[0]).not.toHaveProperty('afterSnapshot');
+ expect(h.calls[1]).toMatchObject({
+ action: 'snapshot', targetId: 'new-tab', compact: true,
+ refs: 'selector' in afterSnapshot ? 'role' : 'aria', maxChars: 'maxChars' in afterSnapshot ? 1000 : 4000,
+ });
+ } finally { await h.cleanup(); }
+ });
+
+ // Live Google Play role snapshots exceeded maxChars. Verify the production
+ // MCP response bounds text and removes hidden refs, while preserving success.
+ it.each([undefined, 64])('bounds post-action snapshots even when the runtime ignores maxChars (%s)', async (maxChars) => {
+ const visible = '- button "Continue" [ref=e1]';
+ const h = await makeHarness({}, (request) => request.action === 'snapshot'
+ ? { snapshot: `${visible}\n${'x'.repeat(5000)}\n- button "Hidden" [ref=e2]`, refs: { e1: { role: 'button', name: 'Continue' }, e2: { role: 'button', name: 'Hidden' } }, stats: { chars: 5100 } }
+ : { targetId: 'tab' });
+ try {
+ const response = await h.client.callTool({ name: 'call_tool', arguments: { name: 'browser', args: {
+ action: 'act', targetId: 'tab', request: { kind: 'click', ref: 'e1' }, afterSnapshot: { selector: '#main-content', ...(maxChars ? { maxChars } : {}) },
+ } } });
+ const result = JSON.parse((response.content as Array<{ text: string }>)[0].text);
+ expect(response.isError).toBe(false);
+ expect(result.ok).toBe(true);
+ expect(result.afterSnapshot.data.snapshot).toBe(visible);
+ expect(result.afterSnapshot.data.snapshot.length).toBeLessThanOrEqual(maxChars ?? 4000);
+ expect(Object.keys(result.afterSnapshot.data.refs)).toEqual(['e1']);
+ expect(result.afterSnapshot.data.truncated).toBe(true);
+ expect(result.afterSnapshot.data.stats).toBeUndefined();
+ } finally { await h.cleanup(); }
+ });
+
+ it.each(['throw', 'error'] as const)('preserves a successful upload when the subsequent snapshot fails (%s)', async (failure) => {
+ let uploads = 0;
+ const runtime: BrowserControlRuntime = { async call(req) {
+ if (req.action === 'snapshot') {
+ if (failure === 'throw') throw new Error('page closed');
+ return { ok: false, action: req.action, message: 'page closed' };
+ }
+ uploads++;
+ return { ok: true, action: req.action, data: { targetId: 'tab' } };
+ } };
+ const h = await makeHarness({ getRuntime: () => runtime });
+ try {
+ const response = await h.client.callTool({ name: 'call_tool', arguments: { name: 'browser', args: {
+ action: 'upload', targetId: 'tab', paths: ['/fake/bundle.aab'], afterSnapshot: {},
+ } } });
+ expect(response.isError).toBe(false);
+ expect(JSON.parse((response.content as Array<{ text: string }>)[0].text)).toMatchObject({
+ ok: true, action: 'upload', afterSnapshot: { ok: false, action: 'snapshot', message: 'page closed' },
+ });
+ expect(uploads).toBe(1);
+ } finally { await h.cleanup(); }
+ });
+
+ it('does not read a new snapshot after a failed action', async () => {
+ const calls: string[] = [];
+ const h = await makeHarness({ getRuntime: () => ({ async call(req) {
+ calls.push(req.action);
+ return { ok: false, action: req.action, message: 'stale ref' };
+ } }) });
+ try {
+ const response = await h.client.callTool({ name: 'call_tool', arguments: { name: 'browser', args: {
+ action: 'act', request: { kind: 'click', ref: 'e1' }, afterSnapshot: {},
+ } } });
+ expect(response.isError).toBe(true);
+ expect(calls).toEqual(['act']);
+ } finally { await h.cleanup(); }
+ });
+
+ it.each([{ action: 'stop' }, { action: 'setBackend', backend: 'external' }, { action: 'act', request: { kind: 'close' } }])('rejects incompatible post-action observation before any side effect: %j', async (args) => {
+ const h = await makeHarness({ setBackend: async () => { throw new Error('must not switch'); } });
+ try {
+ const response = await h.client.callTool({ name: 'call_tool', arguments: { name: 'browser', args: { ...args, afterSnapshot: {} } } });
+ expect(response.isError).toBe(true);
+ expect(h.calls).toEqual([]);
+ } finally { await h.cleanup(); }
+ });
+
it('switches modes in the same MCP instance and immediately updates backend capabilities', async () => {
let backend: 'external' | 'rsb-webview' = 'external';
const switched: string[] = [];
@@ -634,7 +730,13 @@ describe('createBrowserMcpServer', () => {
saved.push(input);
return { ok: true, path: '/tmp/browser-recipes/x.com/recipe.json' };
},
- });
+ }, (_req, i) => ({ result: i === 0 ? true : { title: 'found' } }));
+ const recipeDraft = { id: 'x-search', steps: [{ action: 'evaluate', fn: '() => ({title: "found"})',
+ guard: { url: 'https://x.com/' }, expect: { requiredFields: ['title'] }, as: 'items' }], output: '{{items}}' };
+ const trial = await h.client.callTool({ name: 'call_tool', arguments: { name: 'browser', args: {
+ action: 'recipe', site: 'x.com', recipeDraft,
+ } } });
+ expect(trial.isError).toBe(false);
const result = await h.client.callTool({
name: 'call_tool',
arguments: {
@@ -642,7 +744,7 @@ describe('createBrowserMcpServer', () => {
args: {
action: 'saveRecipe',
site: 'x.com',
- recipeDraft: { id: 'x-search', steps: [{ action: 'navigate', url: 'https://x.com/?q={{q}}' }] },
+ recipeDraft,
},
},
});
@@ -1061,3 +1163,129 @@ describe('createBrowserMcpServer', () => {
});
});
+// Real MCP entry, no model stub: receipts, repair limits and persisted suspension.
+describe('recipe on-use maintenance', () => {
+ const draft = { id: 'maintenance-flow', steps: [{ action: 'evaluate' as const, fn: '() => ({title: "found"})',
+ guard: { url: 'https://example.com/' }, expect: { requiredFields: ['title'] }, as: 'items' }], output: '{{items}}' };
+ 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);
+ }
+ it('rejects unverified/modified/forged drafts and keeps evidence session-local', async () => {
+ const saved: unknown[] = [];
+ const deps = { saveUserRecipe: async (x: unknown) => { saved.push(x); return { ok: true }; } };
+ const h = await makeHarness(deps, (_req, i) => ({ result: i % 2 === 0 ? true : { title: 'found' } }));
+ const other = await makeHarness(deps);
+ try {
+ const save = { action: 'saveRecipe', site: 'example.com', recipeDraft: draft };
+ expect((await invoke(h, save)).ok).toBe(false);
+ expect((await invoke(h, { ...save, action: 'recipe' })).verified).toBe(true);
+ expect((await invoke(other, save)).ok).toBe(false);
+ expect((await invoke(h, { ...save, recipeDraft: { ...draft, description: 'changed' } })).ok).toBe(false);
+ expect((await invoke(h, { ...save, recipeDraft: { ...draft, validation: { site: 'example.com', state: 'active' } } })).ok).toBe(false);
+ expect((await invoke(h, save)).ok).toBe(true);
+ expect(saved).toHaveLength(1);
+ expect(saved[0]).toMatchObject({ recipe: { validation: { state: 'active' } } });
+ } finally { await h.cleanup(); await other.cleanup(); }
+ });
+ it('does not suspend a valid recipe when the caller omitted inputs', async () => {
+ const saved: unknown[] = [];
+ const stored = { ...draft, inputs: { query: { required: true } }, validation: { site: 'example.com', state: 'active' as const } };
+ const h = await makeHarness({
+ getUserRecipes: async () => ({ version: 'maintenance-missing-input', recipes: new Map([[stored.id, stored]]), siteGuides: new Map() }),
+ saveUserRecipe: async (x) => { saved.push(x); return { ok: true }; },
+ }, (_req, i) => ({ result: i === 0 ? true : { title: 'found' } }));
+ try {
+ expect((await invoke(h, { action: 'recipe', recipeId: stored.id })).ok).toBe(false);
+ expect(h.calls).toHaveLength(0);
+ expect(saved).toHaveLength(0);
+ expect((await invoke(h, { action: 'recipe', recipeId: stored.id, inputs: { query: 'test' } })).ok).toBe(true);
+ } finally { await h.cleanup(); }
+ });
+ it('rejects moving an existing recipe id to a different site', async () => {
+ const stored = { ...draft, validation: { site: 'example.com', state: 'active' as const } };
+ const h = await makeHarness({
+ getUserRecipes: async () => ({ version: 'maintenance-wrong-site', recipes: new Map([[stored.id, stored]]), siteGuides: new Map() }),
+ });
+ try {
+ const moved = { ...draft, steps: [{ ...draft.steps[0], guard: { url: 'https://other.example/' } }] };
+ expect((await invoke(h, { action: 'recipe', site: 'other.example', recipeDraft: moved })).message).toContain('原站点');
+ expect(h.calls).toHaveLength(0);
+ } finally { await h.cleanup(); }
+ });
+ it('does not bypass password-handoff restrictions through candidate guards', async () => {
+ const h = await makeHarness({ pageReadsRestricted: async () => true });
+ try {
+ expect((await invoke(h, { action: 'recipe', site: 'example.com', recipeDraft: draft })).ok).toBe(false);
+ expect(h.calls).toHaveLength(0);
+ } finally { await h.cleanup(); }
+ });
+ it('persists failure of a legacy recipe using its guide, without replacing it with a failed draft', async () => {
+ const saved: unknown[] = [];
+ const legacy = { id: 'legacy-guide-flow', steps: [{ action: 'extract' as const, extract: { fields: { title: 'h1' } } }] };
+ const h = await makeHarness({
+ getUserRecipes: async () => ({ version: 'legacy-guide-flow-v1', recipes: new Map([[legacy.id, legacy]]),
+ siteGuides: new Map([['example.com', { site: 'example.com', recipes: [legacy.id] }]]) }),
+ saveUserRecipe: async (x) => { saved.push(x); return { ok: true }; },
+ }, () => ({ result: { ok: false, error: 'invalid selector' } }));
+ try {
+ expect((await invoke(h, { action: 'recipe', recipeId: legacy.id })).ok).toBe(false);
+ expect(saved).toEqual([{ site: 'example.com', recipe: { ...legacy, validation: { site: 'example.com', state: 'suspended' } } }]);
+ } finally { await h.cleanup(); }
+ });
+ it('reports a failed suspension write and still prevents this session from rerunning it', async () => {
+ const stored = { ...draft, validation: { site: 'example.com', state: 'active' as const } };
+ const h = await makeHarness({
+ getUserRecipes: async () => ({ version: 'maintenance-write-failure', recipes: new Map([[stored.id, stored]]), siteGuides: new Map() }),
+ saveUserRecipe: async () => ({ ok: false, message: 'disk full' }),
+ }, () => ({ result: false }));
+ try {
+ expect((await invoke(h, { action: 'recipe', recipeId: stored.id })).maintenanceMessage).toContain('保存失败');
+ expect((await invoke(h, { action: 'recipe', recipeId: stored.id })).ok).toBe(false);
+ expect(h.calls).toHaveLength(1);
+ } finally { await h.cleanup(); }
+ });
+ it('persists suspension, allows one repair, and never automatically replays a completed action', async () => {
+ const recipe = { ...draft, steps: [{ action: 'click' as const, selector: '#save', guard: { url: 'https://example.com/' } }, ...draft.steps],
+ validation: { site: 'example.com', state: 'active' as 'active' | 'suspended' } };
+ let stored = recipe;
+ let version = 0;
+ let good = false;
+ const deps: Partial<BrowserMcpDeps> = {
+ getUserRecipes: async () => ({ version: `maintenance-${version}`, recipes: new Map([[stored.id, stored]]), siteGuides: new Map() }),
+ saveUserRecipe: async (input) => { stored = input.recipe as typeof recipe; version++; return { ok: true }; },
+ };
+ const h = await makeHarness(deps, (req) => {
+ const fn = (req.request as {fn?: string})?.fn;
+ return { result: fn?.includes('const g =') ? true : good ? { title: 'found' } : { title: '' } };
+ });
+ try {
+ expect((await invoke(h, { action: 'recipe', recipeId: recipe.id })).failureKind).toBe('expect');
+ expect(stored.validation.state).toBe('suspended');
+ expect(h.calls.filter((r) => (r as { request?: {kind: string} }).request?.kind === 'click')).toHaveLength(1);
+ const count = h.calls.length;
+ expect((await invoke(h, { action: 'recipe', recipeId: recipe.id })).ok).toBe(false);
+ expect(h.calls).toHaveLength(count);
+ const fresh = await makeHarness(deps);
+ try {
+ expect((await invoke(fresh, { action: 'recipe', recipeId: recipe.id })).ok).toBe(false);
+ expect(fresh.calls).toHaveLength(0);
+ } finally { await fresh.cleanup(); }
+ // Repair is read-only: verify the already-completed write rather than re-submit.
+ expect((await invoke(h, { action: 'recipe', site: 'example.com', recipeDraft: draft })).ok).toBe(false);
+ good = true;
+ const repairCalls = h.calls.length;
+ expect((await invoke(h, { action: 'recipe', site: 'example.com', recipeDraft: draft })).message).toContain('次数已用完');
+ expect(h.calls).toHaveLength(repairCalls);
+ expect(stored.steps[0].action).toBe('click'); // failed draft did not replace it
+ expect((await invoke(h, { action: 'saveRecipe', site: 'example.com', recipeDraft: draft })).ok).toBe(false);
+ } finally { await h.cleanup(); }
+ // A later task can successfully validate and save a repaired definition.
+ const next = await makeHarness(deps, (_r, i) => ({ result: i === 0 ? true : { title: 'found' } }));
+ try {
+ expect((await invoke(next, { action: 'recipe', site: 'example.com', recipeDraft: draft })).ok).toBe(true);
+ expect((await invoke(next, { action: 'saveRecipe', site: 'example.com', recipeDraft: draft })).ok).toBe(true);
+ expect(stored.validation.state).toBe('active');
+ } finally { await next.cleanup(); }
+ });
+});
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 c15777aba6..e71c7d4d76 100644
--- a/packages/lizi-mcps/src/browser/prompts/rules/browser-workflow.md
+++ b/packages/lizi-mcps/src/browser/prompts/rules/browser-workflow.md
@@ -32,7 +32,7 @@
3. **先读后点(snapshot → ref)**
- 点击 / 输入前先 `action: "snapshot"`(同一个 `targetId`,`refs: "aria"`)拿到页面结构和元素 `ref`。
- **永远用 snapshot 返回的 `ref` 去操作,绝不猜 CSS selector。**
- - 页面长 / 噪声多时用 `interactive: true`、`compact: true` 收窄;只关心某区域时用 `selector` / `frame` 限定。
+ - 页面长 / 噪声多时用 `interactive: true`、`compact: true` 收窄;只关心某区域时用 `selector` / `frame` 限定,此时使用 `refs:"role"`(`aria` 不支持局部快照)。
4. **窄操作,操作后重新观察**
- 用 `action: "act"` + `request: { kind, ref, ... }` 执行动作:
@@ -41,7 +41,8 @@
- 按键:`{ kind: "press", key: "Enter" }`
- 下拉:`{ kind: "select", ref, values: [...] }`
- 悬停 / 拖拽:`{ kind: "hover", ref }` / `{ kind: "drag", startRef, endRef }`
- - `ref` 必须取自**最近一次** snapshot。导航 / 弹窗 / 提交后页面变了,**先重新 snapshot 再继续**,别用旧 ref。
+ - 需要操作后观察时,在 `act` / `open` / `navigate` / `upload` 加 `afterSnapshot:{}`,一次调用就返回动作结果和正文默认最多 4000 字符的精简快照(`maxChars` 可调,最高 20000)。已看过页面结构、只需继续表单时可用 `afterSnapshot:{selector:"已确认的区域选择器"}`,避免每次重读整页。后置快照不保证异步页面已加载完;需要的信息还未出现时,等待具体内容再补读。
+ - `ref` 必须取自**最近一次** snapshot(含返回的 `afterSnapshot`)。导航 / 弹窗 / 提交后页面变了,先观察再继续,别用旧 ref。`afterSnapshot.ok:false` 只表示后续读取失败;顶层 `ok:true` 表示动作已经成功,只补读页面,不重做提交或上传。没带后置快照、快照被截断或内容不足时,再按需单独 snapshot。
- 别盲等。需要等待用 `{ kind: "wait", ... }`(等 `loadState` / `textGone` / `timeoutMs`),不要靠反复重试空转。
5. **遇阻塞停下来报告**
@@ -62,7 +63,7 @@
7. 任务完成后,可用不带 `proxyServer` 的 `{action:"start"}` 明确恢复普通直连模式。代理 A 切代理 B、代理切直连都会重启浏览器;重复同一代理则保持当前进程。
#### Token 效率(按"最省 → 兜底"的顺序选路)
-1. **先查有没有现成配方**:操作某个站之前,**先 `action: "siteguide"`**——带 `site`(站点 host)看该站内置指南 / 配方;**不确定有哪些站时,`siteguide` 不带 `site` 会列出全部内置站点 + 可用配方目录**(`sites:[{site,recipes,auth}]`)。命中配方就 `action: "recipe"`(`recipeId`+`inputs`)一步跑完(最省最稳),优先于手动 snapshot/extract。注意 `siteguide` 是我们内置的站点指南,**不是去抓网站自己的 `/sitemap.xml`**——不要为此去 navigate / curl `sitemap.xml`。
+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`。
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。
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 766c277183..04c0b38f14 100644
--- a/packages/lizi-mcps/src/browser/prompts/rules/recipe-author.md
+++ b/packages/lizi-mcps/src/browser/prompts/rules/recipe-author.md
@@ -1,6 +1,6 @@
### 给站点写配方(recipe authoring)
-当某个站点会被反复操作、值得沉淀成确定性流程时,用下面的流程给它写一份**配方**(declarative recipe),之后 `action: "recipe"` 一步跑完、几乎不让模型对着 DOM 盲探。配方是数据、不是代码;写完用 `action: "saveRecipe"` 存进你的本地层(L2),内置同名配方会被你的版本覆盖,删掉本地文件即恢复内置。
+当某个站点会被反复操作、值得沉淀成确定性流程时,用下面的流程给它写一份**配方**(declarative recipe),之后 `action: "recipe"` 一步跑完、几乎不让模型对着 DOM 盲探。配方包含可执行步骤;写完用 `action: "saveRecipe"` 存进你的本地层(L2),内置同名配方会被你的版本覆盖,删掉本地文件即恢复内置。
#### 作者流程(recon → 发现 → 抽取 → 验证 → 沉淀)
@@ -9,8 +9,8 @@
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"` 跑一遍**,确认 `output` 非空、字段对;不对就回到第 4 步修选择器。
-7. **沉淀**:`action: "saveRecipe"`,传 `site`(站点 host)+ `recipeDraft`(配方对象)+ 可选 `siteGuideDraft`。draft 会先按 schema 校验,不合法会返回报错让你修。
+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。
#### 取数策略(先判断站点属于哪种,再选 step)
@@ -24,7 +24,7 @@
{ "action": "evaluate", "as": "posts",
"fn": "async () => { const r = await fetch('/r/{{subreddit|js}}/hot.json?limit=25&raw_json=1', { credentials: 'include' }); const d = await r.json(); return (d.data?.children||[]).map(c => ({ title: c.data.title, score: c.data.score, url: 'https://www.reddit.com'+c.data.permalink })); }" }
```
- `evaluate` 的 `fn` 是一段**函数表达式源码**(可 `async`,会被 await),在页面上下文运行:因为已经在目标域上,`fetch(相对路径, { credentials: 'include' })` 自动带上该站 cookie(登录态),且是同源请求、不触发反爬。fn 的返回值用 `as` 存起来、`output` 引用(runner 会自动解包,见下)。**登录本身由用户在持久浏览器里完成一次**,配方只负责带着 cookie 取数。
+ `wait.fn` 必须是同步条件表达式/函数,不支持 async;等待异步内容时检查页面上的就绪标记。`evaluate` 的 `fn` 是一段**函数表达式源码**(可 `async`,会被 await),在页面上下文运行:因为已经在目标域上,`fetch(相对路径, { credentials: 'include' })` 自动带上该站 cookie(登录态),且是同源请求、不触发反爬。fn 的返回值用 `as` 存起来、`output` 引用(runner 会自动解包,见下)。**登录本身由用户在持久浏览器里完成一次**,配方只负责带着 cookie 取数。
#### recipe schema(写 `recipeDraft` 时照这个)
@@ -37,9 +37,9 @@
"steps": [
{ "action": "navigate", "url": "https://site/api?q={{query|url}}" },
{ "action": "wait", "loadState": "load" },
- { "action": "type", "selector": "input[name=q]", "value": "{{query}}", "submit": true },
- { "action": "click", "selector": "button.go" },
{ "action": "extract", "as": "items",
+ "guard": { "url": "https://site/api?q={{query|url}}" },
+ "expect": { "minCount": 1, "requiredFields": ["title", "url"] },
"extract": { "from": ".row", "multiple": true,
"fields": { "title": ".t", "url": { "selector": "a", "type": "href" } } } }
],
@@ -58,4 +58,7 @@
#### 取舍
- **分页**:第一版把页码/cursor 做成 `inputs`,一次配方跑一页,翻页多调几次。
-- 配方是**加速器不是唯一路径**:站点改版导致某步失败时,停下来用 snapshot+ref 手动完成,并考虑用 `saveRecipe` 更新配方。
+- 偶发任务直接精确读取;只有重复使用、收益明确的流程才沉淀。正常 guard/expect 由代码执行,不调用额外模型、不定时刷新。
+- 配方失败后先观察当前页面;当前任务同一 id 最多试跑一轮修订,成功后保存,失败则普通操作完成任务。不要换 id 绕过预算。已有自动维护配方会暂停复用,跨任务保留,后续任务可重新验证修订版。
+- 写操作失败或后置读取失败,先核实写入是否已经生效;不要为了验证配方再次提交、发送、购买或发布。修复验证用只读检查、测试环境或下一次确有授权的操作。工具不会自动重放任何步骤。
+- 不把密码、验证码、Cookie、令牌或实际业务数据写进配方,变动值用 inputs。
diff --git a/packages/lizi-mcps/src/browser/recipe-loader.ts b/packages/lizi-mcps/src/browser/recipe-loader.ts
index 95eb9abc08..46571ecdaf 100644
--- a/packages/lizi-mcps/src/browser/recipe-loader.ts
+++ b/packages/lizi-mcps/src/browser/recipe-loader.ts
@@ -20,6 +20,18 @@ import { z } from 'zod';
import { ExtractSpecSchema } from './extract.js';
+/** Cheap page identity check, evaluated before a step (no model call). */
+const RecipeGuardSchema = z.object({
+ url: z.string().min(1),
+ selector: z.string().optional(),
+ text: z.string().optional(),
+});
+const RecipeExpectationSchema = z.object({
+ minCount: z.number().int().nonnegative().optional(),
+ requiredFields: z.array(z.string().min(1)).optional(),
+ equals: z.record(z.string(), z.union([z.string(), z.number(), z.boolean()])).optional(),
+}).refine((v) => v.minCount !== undefined || Boolean(v.requiredFields?.length) || Boolean(Object.keys(v.equals ?? {}).length), 'expect must contain a result check');
+
/** A single declarative step. `action` maps to a browser primitive (see runner). */
export const RecipeStepSchema = z.object({
action: z.enum([
@@ -56,7 +68,10 @@ export const RecipeStepSchema = z.object({
as: z.string().optional(),
/** If true, a failed step is logged but does not abort the recipe. */
optional: z.boolean().optional(),
-});
+ guard: RecipeGuardSchema.optional(),
+ expect: RecipeExpectationSchema.optional(),
+}).refine((s) => !s.expect || s.action === 'extract' || s.action === 'evaluate', 'expect is only supported for extract/evaluate')
+ .refine((s) => !s.optional || (!s.guard && !s.expect), 'validation steps cannot be optional');
export const RecipeSchema = z.object({
id: z.string().min(1),
@@ -67,6 +82,11 @@ export const RecipeSchema = z.object({
steps: z.array(RecipeStepSchema).min(1),
/** Output template, e.g. "{{results}}". A bare single-var ref returns that var verbatim. */
output: z.string().optional(),
+ /** Host-owned state; authored drafts cannot supply this. Legacy files remain runnable. */
+ validation: z.object({
+ site: z.string(),
+ state: z.enum(['active', 'suspended']),
+ }).optional(),
});
export type Recipe = z.infer<typeof RecipeSchema>;
diff --git a/packages/lizi-mcps/src/browser/recipe-runner.test.ts b/packages/lizi-mcps/src/browser/recipe-runner.test.ts
index 71bb265b1d..2acf566a3e 100644
--- a/packages/lizi-mcps/src/browser/recipe-runner.test.ts
+++ b/packages/lizi-mcps/src/browser/recipe-runner.test.ts
@@ -1,3 +1,5 @@
+import { runInNewContext } from 'node:vm';
+
import type { BrowserControlRequest, BrowserControlResult } from '@cindy/browser-control-runtime';
import { describe, expect, it } from 'vitest';
@@ -422,3 +424,63 @@ describe('findUnsafeEvaluateInterpolations', () => {
).toHaveLength(0);
});
});
+
+
+describe('recipe guards and output checks', () => {
+ it.each([
+ { visible: 1, hidden: 1, url: 'https://x.com/', text: 'account', ok: true },
+ { visible: 2, hidden: 0, url: 'https://x.com/', text: 'account', ok: false },
+ { visible: 0, hidden: 1, url: 'https://x.com/', text: 'account', ok: false },
+ { visible: 1, hidden: 0, url: 'https://x.com/other', text: 'account', ok: false },
+ { visible: 1, hidden: 0, url: 'https://x.com/', text: 'other account', ok: false },
+ ])('checks page identity and unique visible nodes in the actual extraction: %j', async (scenario) => {
+ let reads = 0;
+ let calls = 0;
+ const nodes = [
+ ...Array.from({ length: scenario.visible }, () => ({ textContent: scenario.text, getBoundingClientRect: () => ({ width: 10, height: 10 }) })),
+ ...Array.from({ length: scenario.hidden }, () => ({ textContent: scenario.text, getBoundingClientRect: () => ({ width: 0, height: 0 }) })),
+ ];
+ const result = await runRecipe({ id: 'guarded-read', steps: [{ action: 'extract',
+ guard: { url: 'https://x.com/', selector: '#account', text: 'account' },
+ extract: { fields: { title: 'h1' } }, expect: { requiredFields: ['title'] }, as: 'data' }], output: '{{data}}' }, {}, {
+ call: async (req) => {
+ calls++;
+ const value = await runInNewContext(`(${req.request!.fn})()`, {
+ location: { href: scenario.url }, getComputedStyle: () => ({ visibility: 'visible' }),
+ document: { querySelectorAll: () => nodes, querySelector: () => { reads++; return { textContent: 'Title' }; } },
+ });
+ return { ok: true, action: req.action, data: { result: value } };
+ },
+ });
+ expect(result.ok).toBe(scenario.ok);
+ expect(reads).toBe(scenario.ok ? 1 : 0);
+ expect(calls).toBe(1); // guard + extract use one page evaluation
+ if (scenario.ok) expect(result.output).toMatchObject({ records: [{ title: 'Title' }] });
+ else expect(result.failureKind).toBe('guard');
+ });
+ it('stops before a write when page identity does not match', async () => {
+ const m = mockCall([{ data: { result: false } }]);
+ const result = await runRecipe({ id: 'save', steps: [{ action: 'click', selector: '#save', guard: { url: 'https://x.com/' } }] }, {}, m);
+ expect(result).toMatchObject({ ok: false, failureKind: 'guard', failedStep: 0, steps: [] });
+ expect(m.calls).toHaveLength(1);
+ expect(m.calls[0].request?.kind).toBe('evaluate');
+ });
+ it.each([[[]], [[{ title: '' }]], [[{ title: 'wrong' }]]])('rejects missing or wrong business results: %j', async (records) => {
+ const m = mockCall([{ data: { result: { records, count: 100 } } }]);
+ const result = await runRecipe({ id: 'read', steps: [{ action: 'extract', extract: { fields: { title: 'h1' } }, expect: { minCount: 1, requiredFields: ['title'], equals: { title: 'expected' } } }] }, {}, m);
+ expect(result).toMatchObject({ ok: false, failureKind: 'expect' });
+ });
+ it('accepts validated fields and preserves structured output', async () => {
+ const m = mockCall([{ data: { result: true } }, { data: { result: [{ title: 'expected', count: 0 }] } }]);
+ const result = await runRecipe({ id: 'read', steps: [{ action: 'evaluate', fn: '() => []', guard: { url: 'https://x.com/' }, expect: { minCount: 1, requiredFields: ['count'], equals: { title: '{{title}}' } }, as: 'result' }], output: '{{result}}' }, { title: 'expected' }, m);
+ expect(result).toMatchObject({ ok: true, output: [{ title: 'expected', count: 0 }] });
+ });
+ it('captures a transport exception without retrying a possibly successful write', async () => {
+ let calls = 0;
+ const result = await runRecipe({ id: 'save', steps: [{ action: 'click', selector: '#save' }, { action: 'click', selector: '#again' }] }, {}, {
+ call: async () => { calls++; throw new Error('response lost'); },
+ });
+ expect(result).toMatchObject({ ok: false, failedStep: 0, failureKind: 'action' });
+ expect(calls).toBe(1);
+ });
+});
diff --git a/packages/lizi-mcps/src/browser/recipe-runner.ts b/packages/lizi-mcps/src/browser/recipe-runner.ts
index 3d7e1d2145..6e3f01034f 100644
--- a/packages/lizi-mcps/src/browser/recipe-runner.ts
+++ b/packages/lizi-mcps/src/browser/recipe-runner.ts
@@ -27,6 +27,7 @@ export interface RecipeRunResult {
failedStep?: number;
failedAction?: string;
message?: string;
+ failureKind?: 'input' | 'guard' | 'expect' | 'action';
}
// `{{var}}` with an optional `|modifier` (e.g. `{{query|url}}`). The modifier
@@ -256,6 +257,50 @@ function stepResultValue(step: RecipeStep, res: BrowserControlResult): unknown {
return res.data;
}
+/** Guard data is JSON-encoded, never interpolated into executable source. */
+function guardRequest(step: RecipeStep, vars: Record<string, unknown>): BrowserControlRequest | undefined {
+ if (!step.guard) return undefined;
+ const guard = {
+ url: interpolate(step.guard.url, vars),
+ selector: interpOpt(step.guard.selector, vars),
+ text: interpOpt(step.guard.text, vars),
+ };
+ if (!isHttpUrl(guard.url)) throw new Error('guard.url 必须是完整 http(s) URL');
+ return { action: 'act', request: { kind: 'evaluate', fn: `() => {
+ const g = ${JSON.stringify(guard)};
+ if (location.href !== g.url) return false;
+ const nodes = g.selector ? Array.from(document.querySelectorAll(g.selector)).filter(el => {
+ const rect = el.getBoundingClientRect();
+ const style = getComputedStyle(el);
+ return rect.width > 0 && rect.height > 0 && style.visibility !== 'hidden' && style.visibility !== 'collapse';
+ }) : [document.body];
+ return nodes.length === 1 && !!nodes[0] && (g.text === undefined || nodes[0].textContent.trim() === g.text);
+ }` } };
+}
+
+/** Validate actual records, not a producer's claimed count. Empty results cannot
+ * satisfy required fields/equals through Array.every's vacuous truth. */
+function expectationError(step: RecipeStep, value: unknown, vars: Record<string, unknown>): string | undefined {
+ if (!step.expect) return undefined;
+ const record = value && typeof value === 'object' ? value as Record<string, unknown> : undefined;
+ const rows = Array.isArray(value) ? value : Array.isArray(record?.records) ? record.records : record ? [record] : [];
+ const { minCount, requiredFields, equals } = step.expect;
+ if (minCount !== undefined && rows.length < minCount) return `expect: 至少 ${minCount} 条,实际 ${rows.length} 条`;
+ if ((requiredFields?.length || Object.keys(equals ?? {}).length) && !rows.length) return 'expect: 结果为空';
+ for (const row of rows) {
+ if (!row || typeof row !== 'object') return 'expect: 结果必须是对象';
+ for (const field of requiredFields ?? []) {
+ const v = (row as Record<string, unknown>)[field];
+ if (v == null || (typeof v === 'string' && !v.trim())) return `expect: 必需字段 ${field} 为空`;
+ }
+ for (const [field, expected] of Object.entries(equals ?? {})) {
+ const target = typeof expected === 'string' ? interpolate(expected, vars) : expected;
+ if ((row as Record<string, unknown>)[field] !== target) return `expect: 字段 ${field} 不匹配`;
+ }
+ }
+ return undefined;
+}
+
/** Execute a recipe. `inputs` seed the variable scope; step `as` adds to it. */
export async function runRecipe(
recipe: Recipe,
@@ -311,8 +356,31 @@ export async function runRecipe(
for (let i = 0; i < recipe.steps.length; i++) {
const step = recipe.steps[i];
let req: BrowserControlRequest;
+ let combinedGuard = false;
try {
req = stepToRequest(step, vars);
+ // Construct all input-dependent checks before touching the page.
+ const guard = guardRequest(step, vars);
+ if (guard && step.action === 'extract') {
+ // Read-only extraction can verify identity and read fields in one page
+ // evaluation. This avoids an extra browser round trip and DOM race.
+ const extractFn = req.request!.fn;
+ req = { ...req, request: { ...req.request!, fn: `async () => {
+ if (!((${guard.request!.fn})())) return { matched: false };
+ return { matched: true, value: await ((${extractFn})()) };
+ }` } };
+ combinedGuard = true;
+ } else if (guard) {
+ let matched = false;
+ try {
+ const result = await deps.call(guard);
+ matched = result.ok && (result.data as { result?: unknown } | undefined)?.result === true;
+ } catch { /* A failed observation never authorizes the action. */ }
+ if (!matched) return {
+ ok: false, recipe: recipe.id, steps, failedStep: i, failedAction: step.action,
+ failureKind: 'guard', message: '页面身份或定位条件已变化;该步骤未执行,请重新观察页面。',
+ };
+ }
} catch (err) {
return {
ok: false,
@@ -320,12 +388,32 @@ export async function runRecipe(
steps,
failedStep: i,
failedAction: step.action,
+ failureKind: 'input',
message: err instanceof Error ? err.message : String(err),
};
}
- const res = await deps.call(req);
+ let res: BrowserControlResult;
+ try {
+ res = await deps.call(req);
+ } catch (err) {
+ res = { ok: false, action: req.action, message: err instanceof Error ? err.message : String(err) };
+ }
+ if (combinedGuard && res.ok) {
+ const checked = (res.data as { result?: { matched?: boolean; value?: unknown } } | undefined)?.result;
+ if (checked?.matched !== true) return {
+ ok: false, recipe: recipe.id, steps, failedStep: i, failedAction: step.action,
+ failureKind: 'guard', message: '页面身份或定位条件已变化;未读取结果,请重新观察页面。',
+ };
+ res = { ...res, data: { ...(res.data as object), result: checked.value } };
+ }
const innerError = innerEvaluateError(step, res);
- const stepOk = res.ok && innerError === undefined;
+ let expectError: string | undefined;
+ try {
+ if (res.ok && !innerError) expectError = expectationError(step, stepResultValue(step, res), vars);
+ } catch (err) {
+ expectError = err instanceof Error ? err.message : String(err);
+ }
+ const stepOk = res.ok && innerError === undefined && expectError === undefined;
steps.push({ action: step.action, ok: stepOk });
// Only store the result on success: a failed (but `optional`) step must not
// leak a `{ok:false,...}`/failure blob into `vars`, or a later `{{as}}` ref
@@ -333,7 +421,7 @@ export async function runRecipe(
// throws "missing recipe variable" (loud) — the intended behavior.
if (stepOk && step.as) vars[step.as] = stepResultValue(step, res);
if (!stepOk) {
- const failMessage = res.message ?? innerError ?? `step ${i} (${step.action}) failed`;
+ const failMessage = res.message ?? innerError ?? expectError ?? `step ${i} (${step.action}) failed`;
if (step.optional) {
deps.logger?.warn?.(`recipe ${recipe.id} step ${i} (${step.action}) failed but is optional`, {
message: failMessage,
@@ -346,6 +434,7 @@ export async function runRecipe(
steps,
failedStep: i,
failedAction: step.action,
+ failureKind: expectError ? 'expect' : 'action',
message: failMessage,
};
}
diff --git a/packages/lizi-mcps/src/browser/tools.ts b/packages/lizi-mcps/src/browser/tools.ts
index 947308d87d..80292aff3c 100644
--- a/packages/lizi-mcps/src/browser/tools.ts
+++ b/packages/lizi-mcps/src/browser/tools.ts
@@ -29,6 +29,7 @@ import {
SiteGuideSchema,
type MergedRecipe,
type MergedSiteGuide,
+ type Recipe,
} from './recipe-loader.js';
import { runRecipe, findUnsafeEvaluateInterpolations } from './recipe-runner.js';
import { isHttpUrl } from './url-guard.js';
@@ -240,6 +241,29 @@ function readTargetId(result: { data?: unknown }): string | undefined {
return typeof id === 'string' && id ? id : undefined;
}
+/** Some runtime role snapshots ignore maxChars; bound the advertised observation here. */
+function limitAfterSnapshot(result: BrowserControlResult, maxChars: number): BrowserControlResult {
+ const data = result.data as { snapshot?: unknown; refs?: Record<string, unknown>; [key: string]: unknown } | undefined;
+ if (!result.ok || typeof data?.snapshot !== 'string' || data.snapshot.length <= maxChars) return result;
+ const prefix = data.snapshot.slice(0, maxChars);
+ const newline = prefix.lastIndexOf('\n');
+ const snapshot = newline >= 0 ? prefix.slice(0, newline) : prefix;
+ const visibleRefs = new Set([...snapshot.matchAll(/\[ref=([^\]]+)\]/g)].map((match) => match[1]));
+ return {
+ ...result,
+ data: {
+ ...data,
+ snapshot,
+ ...(data.refs ? { refs: Object.fromEntries(Object.entries(data.refs).filter(([id]) => visibleRefs.has(id))) } : {}),
+ // The original statistics describe the full page, not this bounded view.
+ stats: undefined,
+ truncated: true,
+ originalChars: data.snapshot.length,
+ hint: '快照正文已截断;若缺少所需内容,请缩小 selector 范围或单独 snapshot 补读,不要重复已成功的动作。',
+ },
+ };
+}
+
function resultText(value: unknown): string {
const json = JSON.stringify(value);
// JSON.stringify returns undefined only for undefined/function inputs; callers
@@ -448,12 +472,42 @@ 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) out[key] = value;
+ if (value !== undefined && key !== 'afterSnapshot') out[key] = value;
}
return out as unknown as BrowserControlRequest;
}
export function registerBrowserTools(registry: BrowserToolRegistry, deps: BrowserMcpDeps): void {
+ // 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 failedRecipes = new Set<string>();
+ const repairUsed = new Set<string>();
+ const runningRecipes = new Set<string>();
+ const recovery = '先重新观察当前页面;当前任务每个配方最多验证一轮修订。失败后回普通操作。写操作先核实是否已成功,不得自动重放。';
+ function draftIssue(recipe: Recipe, site: string | undefined): string | undefined {
+ if (recipe.validation) return 'validation 由宿主管理,recipeDraft 不得提供';
+ if (!site || !/^[a-zA-Z0-9][a-zA-Z0-9.-]{0,252}$/.test(site)) return '试跑配方需要 site(完整站点 host)';
+ const unsafe = findUnsafeEvaluateInterpolations(recipe);
+ if (unsafe.length) return `recipeDraft 插值不安全:${unsafe.join('; ')}`;
+ for (const step of recipe.steps) {
+ if (['click', 'type', 'select', 'extract', 'evaluate'].includes(step.action) && !step.guard) {
+ return '交互和读取步骤必须有 guard:{url,selector?,text?},先确认页面身份';
+ }
+ for (const url of [step.guard?.url, step.action === 'navigate' ? step.url : undefined]) {
+ if (url !== undefined) {
+ try {
+ if (!isHttpUrl(url) || new URL(url).hostname !== site.toLowerCase()) return 'guard/navigation URL 必须属于 site';
+ } catch { return 'guard/navigation URL 不合法'; }
+ }
+ }
+ }
+ const last = recipe.steps.at(-1);
+ if (!last?.expect || !last.as || recipe.output !== `{{${last.as}}}`) {
+ return '最后一步必须用 expect 验证结果,并用 as/output 返回该结果';
+ }
+ return undefined;
+ }
const actKind = actKindSchema(deps);
const elementQuery = elementQuerySchema(deps);
registry.register({
@@ -463,6 +517,7 @@ export function registerBrowserTools(registry: BrowserToolRegistry, deps: Browse
'浏览器自动化统一入口。通过 action 选择 status/start/tabs/navigate/snapshot/screenshot/act 等操作; ' +
'status 返回实际浏览器模式; setBackend 切换并保存全局浏览器模式(内置 rsb-webview / 外置 external)。' +
'优先使用 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'],
inputShape: {
@@ -494,6 +549,13 @@ export function registerBrowserTools(registry: BrowserToolRegistry, deps: Browse
depth: z.number().int().nonnegative().optional(),
selector: z.string().optional(),
frame: z.string().optional(),
+ afterSnapshot: z.strictObject({
+ selector: z.string().trim().min(1).optional(),
+ frame: z.string().trim().min(1).optional(),
+ interactive: z.boolean().optional(),
+ depth: z.number().int().nonnegative().optional(),
+ maxChars: z.number().int().min(1).max(20_000).optional(),
+ }).optional().describe('动作成功后读取精简快照,正文默认最多 4000 字符;只读失败不改变动作的成功状态,不要重复动作'),
labels: z.boolean().optional(),
urls: z.boolean().optional(),
fullPage: z.boolean().optional(),
@@ -524,7 +586,7 @@ export function registerBrowserTools(registry: BrowserToolRegistry, deps: Browse
recipeDraft: z
.record(z.string(), z.unknown())
.optional()
- .describe('action=saveRecipe: 要保存到本地层的配方对象(同 recipe schema:id/steps/inputs/output…),会先按 schema 校验'),
+ .describe('action=recipe: 带 site 试跑候选配方;成功后 action=saveRecipe 保存相同 site 和 recipeDraft。需要 guard 页面校验和末步 expect 结果校验。'),
siteGuideDraft: z
.record(z.string(), z.unknown())
.optional()
@@ -569,6 +631,10 @@ export function registerBrowserTools(registry: BrowserToolRegistry, deps: Browse
},
handler: async (args) => {
try {
+ 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');
+ }
// Host configuration is not a vendored browser action. Await the same
// lifecycle transition as Settings before issuing any new page actions.
if (args.action === 'setBackend') {
@@ -662,14 +728,33 @@ 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') {
- if (!args.recipeId) return errorResult('recipe', 'recipe requires `recipeId`');
let entry: MergedRecipe | undefined;
- try {
+ const candidate = args.recipeDraft !== undefined;
+ if (candidate) {
+ const parsed = RecipeSchema.safeParse(args.recipeDraft);
+ if (!parsed.success) return errorResult('recipe', `recipeDraft 不合法:${parsed.error.message}`);
+ if (args.recipeId && args.recipeId !== parsed.data.id) return errorResult('recipe', 'recipeId 必须与 recipeDraft.id 一致');
+ const issue = draftIssue(parsed.data, args.site);
+ if (issue) return errorResult('recipe', issue);
+ entry = { recipe: parsed.data, provenance: 'user' };
+ } else {
+ if (!args.recipeId) return errorResult('recipe', 'recipe requires recipeId 或 recipeDraft + site');
entry = (await recipeRegistry(deps)).get(args.recipeId);
- } catch (err) {
- return errorResult('recipe', `recipe registry error: ${err instanceof Error ? err.message : String(err)}`);
}
if (!entry) return errorResult('recipe', `unknown recipe: ${args.recipeId}`);
+ const id = entry.recipe.id;
+ const persisted = candidate ? (await recipeRegistry(deps)).get(id)?.recipe : entry.recipe;
+ if (runningRecipes.has(id)) return errorResult('recipe', '该配方正在执行,请勿并发重放');
+ if (candidate && persisted?.validation && persisted.validation.site !== args.site) {
+ return errorResult('recipe', '已有配方的修订必须保存在原站点,请保持相同 site');
+ }
+ const suspended = failedRecipes.has(id) || persisted?.validation?.state === 'suspended';
+ if (!candidate && suspended) return errorResult('recipe', `配方已暂停复用。${recovery}`);
+ if (candidate && (suspended || repairUsed.has(id))) {
+ if (repairUsed.has(id)) return errorResult('recipe', `本任务的修复验证次数已用完。${recovery}`);
+ repairUsed.add(id);
+ }
+ verifiedDrafts.delete(id);
// Thread the caller's tab/profile routing into every recipe step:
// step requests from stepToRequest carry no profile/targetId, so
// without this each navigate/extract would fall back to the runtime's
@@ -684,6 +769,7 @@ export function registerBrowserTools(registry: BrowserToolRegistry, deps: Browse
// which is ambiguous with multiple tabs open). Once a navigate hands back
// a target, the whole recipe stays pinned to it.
let activeTargetId = args.targetId;
+ runningRecipes.add(id);
const runResult = await runRecipe(entry.recipe, args.inputs as Record<string, unknown> | undefined, {
call: async (req) => {
const res = await runtime.call({
@@ -696,10 +782,34 @@ export function registerBrowserTools(registry: BrowserToolRegistry, deps: Browse
return res;
},
logger: deps.logger,
- });
+ }).finally(() => runningRecipes.delete(id));
+ let maintenanceMessage: string | undefined;
+ if (runResult.ok && candidate) {
+ verifiedDrafts.set(id, { site: args.site!, content: JSON.stringify(entry.recipe) });
+ } else if (!runResult.ok && runResult.failureKind !== 'input' && runResult.failedStep !== undefined) {
+ failedRecipes.add(id);
+ // Keep the last known definition, not a failed candidate. A normal
+ // use failure persists across tasks; missing input does not age a recipe.
+ if (persisted && deps.saveUserRecipe) {
+ try {
+ // Bundled recipes predate validation metadata; their guide
+ // supplies the owning site. Never guess from a host substring.
+ const sites = persisted.validation ? [persisted.validation.site] :
+ [...siteGuideRegistryFrom(await resolveUserLayer(deps)).values()]
+ .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' } } });
+ if (!saved.ok) maintenanceMessage = '本任务已暂停;跨任务停用保存失败,请勿复用旧配方。';
+ recipeCache = null;
+ } else maintenanceMessage = '本任务已暂停;无法确定配方所属站点,未保存跨任务停用状态。';
+ } catch { maintenanceMessage = '本任务已暂停;跨任务停用保存失败,请勿复用旧配方。'; }
+ }
+ }
return {
content: [
- { type: 'text', text: resultText({ action: 'recipe', provenance: entry.provenance, ...runResult }) },
+ { type: 'text', text: resultText({ action: 'recipe', provenance: entry.provenance, ...runResult,
+ ...(!runResult.ok ? { recovery, maintenanceMessage } : candidate ? { verified: true } : {}) }) },
],
isError: !runResult.ok,
};
@@ -735,6 +845,7 @@ export function registerBrowserTools(registry: BrowserToolRegistry, deps: Browse
// input constraints (e.g. "id must be passed as a string") that the
// bare input-name list cannot express.
description: r?.recipe.description,
+ ...(r?.recipe.validation ? { state: r.recipe.validation.state } : {}),
inputs: Object.keys(spec),
required: Object.entries(spec)
.filter(([, v]) => v?.required)
@@ -847,8 +958,17 @@ export function registerBrowserTools(registry: BrowserToolRegistry, deps: Browse
);
}
}
- const saved = await deps.saveUserRecipe({ site: args.site, recipe: parsed.data, siteGuide: guide });
+ 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)) {
+ 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 });
if (saved.ok) {
+ verifiedDrafts.delete(parsed.data.id);
+ failedRecipes.delete(parsed.data.id);
// invalidate so this session sees it now (cross-session is covered by
// the content-derived version check in the registry).
recipeCache = null;
@@ -909,6 +1029,38 @@ export function registerBrowserTools(registry: BrowserToolRegistry, deps: Browse
// First key, so it survives truncation of a large snapshot.
if (loginWall) result = { loginWall, ...result } as typeof result;
}
+ if (args.afterSnapshot && result.ok) {
+ // Keep observation separate: a successful upload/click must never be
+ // reported as failed (and replayed) because its follow-up read failed.
+ const snapshotOptions = args.afterSnapshot;
+ const targetId = readTargetId(result) ?? args.request?.targetId ?? args.targetId;
+ let afterSnapshot: BrowserControlResult;
+ try {
+ afterSnapshot = await runtime.call({
+ action: 'snapshot',
+ profile: args.profile,
+ targetId,
+ snapshotFormat: 'ai',
+ refs: snapshotOptions.selector || snapshotOptions.frame ? 'role' : 'aria',
+ compact: true,
+ maxChars: 4000,
+ ...snapshotOptions,
+ });
+ if (afterSnapshot.ok) {
+ const loginWall = await detectLoginWall(runtime, args.profile, readTargetId(afterSnapshot) ?? targetId);
+ if (loginWall) afterSnapshot = { loginWall, ...afterSnapshot } as typeof afterSnapshot;
+ afterSnapshot = limitAfterSnapshot(afterSnapshot, snapshotOptions.maxChars ?? 4000);
+ }
+ } catch (err) {
+ afterSnapshot = {
+ ok: false,
+ action: 'snapshot',
+ errorCode: 'BROWSER_RUNTIME_ACTION_FAILED',
+ message: err instanceof Error ? err.message : String(err),
+ };
+ }
+ result = { ...result, afterSnapshot } as typeof result;
+ }
// For extract, the runtime call may succeed (evaluate ran) while the
// in-page extract reports ok:false (invalid selector); surface that as an
// error so the agent sees + acts on the embedded hint.
diff --git a/scripts/browser-live-recipe-compare.mjs b/scripts/browser-live-recipe-compare.mjs
new file mode 100644
index 0000000000..596fb491ec
--- /dev/null
+++ b/scripts/browser-live-recipe-compare.mjs
@@ -0,0 +1,238 @@
+/**
+ * Opt-in, read-only live integration experiment, not a unit test.
+ * Production entry: BrowserToolRegistry -> registerBrowserTools -> real runtime.
+ * Evidence gap: prior Google Play runs needed a second observation after every
+ * click. Compare that path with explicit readiness + extraction, split/recipe.
+ * All selectors/fields come from a separately inspected plan, never credentials.
+ * Only attach to the already-authorized Cindy browser; never start/stop Chrome.
+ */
+import fs from 'node:fs/promises';
+import assert from 'node:assert/strict';
+import os from 'node:os';
+import path from 'node:path';
+import { pathToFileURL } from 'node:url';
+import { execFileSync } from 'node:child_process';
+import { performance } from 'node:perf_hooks';
+import { createServer } from 'vite';
+
+const opt = (name) => process.argv.find((arg) => arg.startsWith(`--${name}=`))?.slice(name.length + 3);
+const sourceRoot = opt('source-root');
+const cdpUrl = opt('cdp-url');
+const targetId = opt('target');
+const planFile = opt('plan');
+const output = opt('out');
+const order = (opt('order') ?? 'snapshot,precise,recipe,precise,recipe,snapshot,recipe,snapshot,precise').split(',');
+if (!sourceRoot || !cdpUrl || !targetId || !planFile || !output || order.some((m) => !['snapshot', 'precise', 'recipe', 'guarded'].includes(m))) {
+ throw new Error('需要 source-root/cdp-url/target/plan/out;order 只接受 snapshot/precise/recipe/guarded');
+}
+const plan = JSON.parse(await fs.readFile(planFile, 'utf8'));
+const origin = new URL(plan.startUrl).origin;
+const tempRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-live-recipe-'));
+process.env.XDT_BROWSER_RUNTIME_DIR = tempRoot;
+const fromSource = (file) => import(pathToFileURL(path.join(sourceRoot, file)).href);
+let vite, disconnect, active, currentCall, lastRuntimeUrl;
+const report = {
+ startedAt: new Date().toISOString(), sourceRoot,
+ sourceHead: execFileSync('git', ['rev-parse', 'HEAD'], { cwd: sourceRoot, encoding: 'utf8' }).trim(),
+ planFile, order, runs: [], setup: [],
+ scope: '真实页面生产工具调用;不含模型推理和宿主 MCP 往返;配方只在实验进程内注册',
+};
+const checksOf = (step) => [...new Set([step.readyText, ...(step.checks ?? [])])];
+// Use supported locator + URL conditions. The pilot exposed that wait.fn with
+// a function-source string is truthy in the installed Playwright version.
+const readySelector = (step) => '#main-content' + checksOf(step).map((text) => `:has-text(${JSON.stringify(text)})`).join('');
+try {
+ // Vite expands the production import.meta.glob catalog. No mocked recipe loader.
+ vite = await createServer({ root: sourceRoot, configFile: false, appType: 'custom',
+ optimizeDeps: { noDiscovery: true, include: [], entries: [] },
+ server: { middlewareMode: true, watch: null }, logLevel: 'error' });
+ const { registerBrowserTools } = await vite.ssrLoadModule('/packages/lizi-mcps/src/browser/tools.ts');
+ const { RecipeSchema } = await vite.ssrLoadModule('/packages/lizi-mcps/src/browser/recipe-loader.ts');
+ const { BrowserToolRegistry } = await fromSource('packages/lizi-mcps/src/browser/tool-registry.ts');
+ const { createBrowserControlRuntime } = await fromSource('packages/browser-control-runtime/src/runtime.ts');
+ ({ closePlaywrightBrowserConnection: disconnect } = await fromSource('packages/browser-control-runtime/src/_generated/extension/src/browser/pw-session.ts'));
+ const recipes = new Map(plan.steps.map((step, i) => {
+ const recipe = RecipeSchema.parse({ id: `live-readonly-step-${i}`, match: [new URL(plan.startUrl).host],
+ steps: [
+ { action: 'click', selector: step.selector, timeoutMs: 15000 },
+ { action: 'wait', url: origin + step.expectedPath, selector: readySelector(step), timeoutMs: 15000 },
+ { action: 'extract', extract: step.extract, as: 'data' },
+ ], output: '{{data}}' });
+ return [recipe.id, recipe];
+ }));
+ for (const [i, step] of plan.steps.entries()) {
+ const basic = recipes.get(`live-readonly-step-${i}`);
+ const guarded = RecipeSchema.parse({ ...basic, id: `live-guarded-step-${i}`,
+ validation: { site: new URL(plan.startUrl).host, state: 'active' },
+ steps: basic.steps.map((s, n) => n === 0 ? { ...s,
+ guard: { url: i ? origin + plan.steps[i - 1].expectedPath : plan.startUrl,
+ selector: step.selector.replace(/:visible/g, '') },
+ } : n === 2 ? { ...s, guard: { url: origin + step.expectedPath, selector: '#main-content' },
+ expect: { minCount: 1, requiredFields: Object.keys(step.extract.fields) },
+ } : s),
+ });
+ recipes.set(guarded.id, guarded);
+ }
+ report.recipes = [...recipes.values()];
+ const runtime = createBrowserControlRuntime({
+ config: { browser: { enabled: true, attachOnly: true, defaultProfile: 'live-comparison',
+ profiles: { 'live-comparison': { cdpUrl, attachOnly: true, color: '#00D9C5' } },
+ ssrfPolicy: { dangerouslyAllowPrivateNetwork: true } } }, logSink: () => {},
+ });
+ const observedRuntime = new Proxy(runtime, { get(target, prop) {
+ if (prop !== 'call') return Reflect.get(target, prop);
+ return async (req) => {
+ const started = performance.now();
+ const result = await target.call(req);
+ if (result.data?.url) lastRuntimeUrl = result.data.url;
+ currentCall?.runtime.push({ action: req.action, kind: req.request?.kind,
+ ms: performance.now() - started, ok: result.ok, url: result.data?.url });
+ return result;
+ };
+ } });
+ let recipeVersion = 0;
+ const registry = new BrowserToolRegistry();
+ registerBrowserTools(registry, { getRuntime: () => observedRuntime, supportsSemanticQueries: () => false,
+ getUserRecipes: async () => ({ recipes, siteGuides: new Map(), version: `live-recipe-experiment-${recipeVersion}` }),
+ saveUserRecipe: async ({ recipe }) => { recipes.set(recipe.id, recipe); recipeVersion++; return { ok: true }; } });
+ const call = async (args, measured = true, allowFailure = false) => {
+ const row = { args, runtime: [] };
+ currentCall = row;
+ const started = performance.now();
+ try {
+ const response = await registry.call('browser', { targetId, ...args });
+ const text = response.content.filter((c) => c.type === 'text').map((c) => c.text).join('');
+ row.result = JSON.parse(text);
+ row.characters = text.length;
+ if (!row.result.ok && !allowFailure) throw new Error(row.result.message ?? text);
+ if (lastRuntimeUrl && new URL(lastRuntimeUrl).origin !== origin) throw new Error('页面离开目标网站,停止实验');
+ return row.result;
+ } finally {
+ row.ms = performance.now() - started;
+ (measured && active ? active.rows : report.setup).push(row);
+ currentCall = undefined;
+ }
+ };
+ const snapshot = () => call({ action: 'snapshot', refs: 'aria', compact: true });
+ const wait = (step, measured = true) => call({ action: 'act', request: { kind: 'wait', url: origin + step.expectedPath, selector: readySelector(step), timeoutMs: 15000 } }, measured);
+ for (const mode of order) {
+ active = { mode, rows: [], checkpoints: [], staleObservations: 0, startedAt: new Date().toISOString() };
+ report.runs.push(active);
+ await call({ action: 'navigate', url: plan.startUrl }, false);
+ await wait({ expectedPath: new URL(plan.startUrl).pathname, readyText: plan.startReadyText }, false);
+ // Registry/catalog initialization is measured as setup, not hidden in the first recipe.
+ await call({ action: 'siteguide' }, false);
+ const started = performance.now();
+ let observed = await snapshot();
+ for (const [i, step] of plan.steps.entries()) {
+ let evidence, structured;
+ if (mode === 'snapshot') {
+ const lines = (observed.data?.snapshot ?? '').split('\n');
+ const matches = Object.entries(observed.data?.refs ?? {}).filter(([id, ref]) => {
+ if (ref.role !== step.role || ref.name !== step.name) return false;
+ if (!step.href) return true;
+ const line = lines.findIndex((t) => t.includes(`[ref=${id}]`));
+ return lines[line + 1]?.trim() === `- /url: ${step.href}`;
+ });
+ if (matches.length !== 1) throw new Error(`导航控件不唯一或缺失:${step.name}`);
+ const result = await call({ action: 'act', request: { kind: 'click', ref: matches[0][0] }, afterSnapshot: step.afterSnapshot });
+ observed = result.afterSnapshot;
+ if (!observed?.ok) throw new Error('点击成功但观察失败,停止,不重复动作');
+ const ready = () => new URL(observed.data.url).pathname === step.expectedPath && checksOf(step).every((t) => observed.data.snapshot.includes(t));
+ if (!ready()) {
+ active.staleObservations++;
+ // Same explicit readiness predicate in every arm; snapshot arm still
+ // incurs the premature read that the experiment is investigating.
+ await wait(step);
+ observed = await snapshot();
+ }
+ if (!ready()) throw new Error(`缺少页面验收结果:${step.name}`);
+ evidence = observed.data.snapshot;
+ } else {
+ let result;
+ if (mode === 'recipe' || mode === 'guarded') {
+ result = await call({ action: 'recipe', recipeId: `live-${mode === 'guarded' ? 'guarded' : 'readonly'}-step-${i}` });
+ structured = result.output;
+ } else {
+ await call({ action: 'act', request: { kind: 'click', selector: step.selector, timeoutMs: 15000 } });
+ await wait(step);
+ result = await call({ action: 'extract', extract: step.extract });
+ structured = result.data?.result;
+ }
+ if (!structured?.ok || structured.count < 1) throw new Error(`提取结果为空或失败:${step.name}`);
+ evidence = JSON.stringify(structured);
+ }
+ const checks = checksOf(step).map((text) => ({ text, found: evidence.includes(text) }));
+ const checkpoint = { click: step.name, url: lastRuntimeUrl, checks, ...(structured ? { structured } : {}) };
+ active.checkpoints.push(checkpoint);
+ if (new URL(lastRuntimeUrl).pathname !== step.expectedPath || checks.some((c) => !c.found)) {
+ throw new Error(`页面或业务检查点不匹配:${JSON.stringify(checkpoint)}`);
+ }
+ }
+ active.wallMs = performance.now() - started;
+ active.ok = true;
+ active.calls = active.rows.length;
+ active.characters = active.rows.reduce((sum, row) => sum + row.characters, 0);
+ active.runtimeCalls = active.rows.reduce((sum, row) => sum + row.runtime.length, 0);
+ active.finalUrl = lastRuntimeUrl;
+ console.log(JSON.stringify({ mode, run: report.runs.length, calls: active.calls, characters: active.characters,
+ runtimeCalls: active.runtimeCalls, wallMs: active.wallMs, staleObservations: active.staleObservations, ok: true }));
+ await fs.writeFile(output, JSON.stringify(report, null, 2) + '\n', { mode: 0o600 });
+ }
+ if (opt('maintenance-checks') === 'true') {
+ active = undefined;
+ report.maintenance = [];
+ const probe = async (name, args, check) => {
+ const result = await call(args, false, true);
+ check(result);
+ report.maintenance.push({ name, ok: true, result });
+ return result;
+ };
+ await probe('wait false times out', { action: 'act', request: { kind: 'wait', fn: '() => false', timeoutMs: 200 } }, r => { assert.equal(r.ok, false); assert.match(r.message, /[Tt]imeout/); });
+ await probe('wait true succeeds', { action: 'act', request: { kind: 'wait', fn: '() => true', timeoutMs: 200 } }, r => assert.equal(r.ok, true));
+ await probe('async false cannot fake success', { action: 'act', request: { kind: 'wait', fn: 'async () => false', timeoutMs: 200 } }, r => { assert.equal(r.ok, false); assert.match(r.message, /synchronous predicate/); });
+ await probe('wait evaluates until true', { action: 'act', request: { kind: 'wait', fn: `() => Date.now() >= ${Date.now() + 300}`, timeoutMs: 2000 } }, r => assert.equal(r.ok, true));
+ const site = new URL(plan.startUrl).host;
+ const draft = { id: 'live-maintenance-overview', steps: [{ action: 'extract',
+ guard: { url: plan.startUrl, selector: '#main-content' },
+ extract: plan.steps.at(-1).extract, expect: { minCount: 1, requiredFields: ['title'], equals: { title: '发布概览' } },
+ as: 'data' }], output: '{{data}}' };
+ await probe('reject unverified save', { action: 'saveRecipe', site, recipeDraft: draft }, r => assert.equal(r.ok, false));
+ await probe('validate candidate on real page', { action: 'recipe', site, recipeDraft: draft }, r => assert.equal(r.verified, true));
+ await probe('reject altered draft', { action: 'saveRecipe', site, recipeDraft: { ...draft, description: 'changed' } }, r => assert.equal(r.ok, false));
+ await probe('save verified draft', { action: 'saveRecipe', site, recipeDraft: draft }, r => assert.equal(r.ok, true));
+ await call({ action: 'navigate', url: origin + plan.steps[0].expectedPath }, false);
+ await wait(plan.steps[0], false);
+ await probe('wrong page stops before action', { action: 'recipe', recipeId: draft.id }, r => { assert.equal(r.failureKind, 'guard'); assert.equal(r.steps.length, 0); });
+ assert.equal(recipes.get(draft.id).validation.state, 'suspended');
+ await probe('suspended recipe does not execute', { action: 'recipe', recipeId: draft.id }, r => assert.equal(r.ok, false));
+ assert.equal(report.setup.at(-1).runtime.length, 0);
+ const repaired = { ...draft, steps: [{ ...draft.steps[0], guard: { url: origin + plan.steps[0].expectedPath, selector: '#main-content' },
+ extract: plan.steps[0].extract, expect: { minCount: 1, requiredFields: Object.keys(plan.steps[0].extract.fields) } }] };
+ await probe('one observed repair passes', { action: 'recipe', site, recipeDraft: repaired }, r => assert.equal(r.verified, true));
+ await probe('save repaired definition', { action: 'saveRecipe', site, recipeDraft: repaired }, r => assert.equal(r.ok, true));
+ assert.equal(recipes.get(draft.id).validation.state, 'active');
+ const bad = { ...repaired, id: 'live-missing-field', steps: [{ ...repaired.steps[0], expect: { requiredFields: ['missingField'] } }] };
+ await probe('missing field rejected', { action: 'recipe', site, recipeDraft: bad }, r => assert.equal(r.failureKind, 'expect'));
+ await probe('one failed repair rejected', { action: 'recipe', site, recipeDraft: bad }, r => assert.equal(r.failureKind, 'expect'));
+ await probe('repair loop blocked', { action: 'recipe', site, recipeDraft: bad }, r => assert.match(r.message, /次数已用完/));
+ assert.equal(report.setup.at(-1).runtime.length, 0);
+ await probe('failed repair cannot be saved', { action: 'saveRecipe', site, recipeDraft: bad }, r => assert.equal(r.ok, false));
+ await call({ action: 'navigate', url: plan.startUrl }, false);
+ await wait({ expectedPath: new URL(plan.startUrl).pathname, readyText: plan.startReadyText }, false);
+ console.log(JSON.stringify({ maintenanceChecks: report.maintenance.length, ok: true }));
+ }
+ report.ok = true;
+} catch (error) {
+ report.ok = false;
+ report.error = String(error);
+ if (active) active.ok = false;
+ console.error(report.error);
+} finally {
+ // Disconnect only this client; leave Chrome and its login intact.
+ await disconnect?.({ cdpUrl });
+ await vite?.close();
+ await fs.rm(tempRoot, { recursive: true, force: true });
+ await fs.writeFile(output, JSON.stringify(report, null, 2) + '\n', { mode: 0o600 });
+}
+process.exitCode = report.ok ? 0 : 1;
diff --git a/scripts/browser-runtime/sync.mjs b/scripts/browser-runtime/sync.mjs
index 2e44249cdd..615966f1e7 100644
--- a/scripts/browser-runtime/sync.mjs
+++ b/scripts/browser-runtime/sync.mjs
@@ -291,6 +291,53 @@ const LOCAL_PATCHES = {
},
],
'extension/src/browser/routes/agent.act.ts': [
+ {
+ desc: 'resolve the selected tab alias before comparing or executing action targets',
+ transform: (source) => applyExactReplacements(source, [
+ [
+ `import { normalizeActRequest, validateBatchTargetIds } from "./agent.act.normalize.js";`,
+ `import { normalizeActRequest, validateBatchTargetIds } from "./agent.act.normalize.js";
+import { resolveActionTargetIds } from "openclaw/plugin-sdk/browser-action-targets";`,
+ ],
+ [
+ ` await withRouteTabContext({
+ req,
+ res,
+ ctx,
+ targetId,
+ enforceCurrentUrlAllowed: shouldEnforceCurrentUrlForAct(action),
+ run: async ({ profileCtx, cdpUrl, tab, resolveTabUrl }) => {`,
+ ` const requestedAction = action;
+ await withRouteTabContext({
+ req,
+ res,
+ ctx,
+ targetId,
+ enforceCurrentUrlAllowed: shouldEnforceCurrentUrlForAct(action),
+ run: async ({ profileCtx, cdpUrl, tab, resolveTabUrl }) => {
+ let resolvedAction: BrowserActRequest;
+ try {
+ resolvedAction = resolveActionTargetIds(requestedAction, targetId, tab.targetId);
+ } catch {
+ return jsonActError(res, 403, ACT_ERROR_CODES.targetIdMismatch,
+ "action targetId must match request targetId");
+ }
+ const action = resolvedAction;`,
+ ],
+ [
+ ` if (action.targetId && action.targetId !== tab.targetId) {
+ return jsonActError(
+ res,
+ 403,
+ ACT_ERROR_CODES.targetIdMismatch,
+ "action targetId must match request targetId",
+ );
+ }
+`,
+ ``,
+ ],
+ ]),
+ },
{
desc: 'carry the effective browser proxy mode through interaction navigation guards',
transform: (source) => applyExactReplacements(source, [
@@ -826,7 +873,16 @@ const LOCAL_PATCHES = {
cleanup();
}
}`,
- ` await waitForStep(page.waitForFunction(fn, { timeout }));
+ ` // Pass a real function so Playwright caches its compilation between
+ // polls (string expressions re-eval and can fail under Trusted Types).
+ // Compile only on the host; execution stays in the page context.
+ const predicate = new Function(
+ "const value = (" + normalizeBrowserEvaluateFunctionSource(fn) + ")(); " +
+ "if (value && typeof value.then === 'function') { " +
+ "Promise.resolve(value).catch(() => {}); throw new Error('wait.fn requires a synchronous predicate'); } " +
+ "return value;",
+ ) as () => unknown;
+ await waitForStep(page.waitForFunction(predicate, undefined, { timeout }));
}
}
},
@@ -1456,6 +1512,30 @@ const UNTORN_DOWN_BROWSER_MESSAGE =
},
],
'extension/src/browser/pw-session.ts': [
+ {
+ desc: 'use Playwright local-path uploads only for a live browser managed by this runtime',
+ transform: (source) => applyExactReplacements(source, [
+ [
+ `import path from "node:path";`,
+ `import path from "node:path";
+import { isManagedLocalCdpConnection } from "openclaw/plugin-sdk/cdp-locality";`,
+ ],
+ [
+ ` const headers = getHeadersWithAuth(target);
+ // Bypass proxy for loopback CDP connections (#31219)`,
+ ` const headers = getHeadersWithAuth(target);
+ const { getBrowserControlState } = await import("../browser-control-state.js");
+ const isLocal = isManagedLocalCdpConnection(
+ normalized, target, getBrowserControlState()?.profiles.values() ?? [],
+ );
+ // Bypass proxy for loopback CDP connections (#31219)`,
+ ],
+ [
+ `chromium.connectOverCDP(target, { timeout, headers })`,
+ `chromium.connectOverCDP(target, { timeout, headers, isLocal })`,
+ ],
+ ]),
+ },
{
desc: 'export a non-blocking quarantine so the popup-overflow path can mark a target unusable without awaiting close() (a hung page must not keep the interaction pending)',
find: `// Quarantine and close a tab that OpenClaw itself navigated to a blocked URL.`,