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): 内置配方新增 X 单推与微信公众号文章免登录读取 (#786)

Dashf168e6da5e58
diff --git a/packages/lizi-mcps/src/browser/recipe-runner.test.ts b/packages/lizi-mcps/src/browser/recipe-runner.test.ts
index 6b81729ef3..71bb265b1d 100644
--- a/packages/lizi-mcps/src/browser/recipe-runner.test.ts
+++ b/packages/lizi-mcps/src/browser/recipe-runner.test.ts
@@ -179,6 +179,37 @@ describe('runRecipe', () => {
expect(calls).toHaveLength(0);
});
+ it('rejects (before any step) a numeric input beyond the safe-integer range', async () => {
+ // A 19-digit snowflake id passed as a JSON number was already rounded by
+ // JSON.parse — stringifying it would navigate to the WRONG resource, so the
+ // runner must fail loudly instead of dispatching the corrupted value.
+ const { call, calls } = mockCall();
+ const res = await runRecipe(SEARCH_RECIPE, { q: 1892345678901234567 }, { call });
+ expect(res.ok).toBe(false);
+ expect(res.message).toMatch(/safe-integer range.*pass it as a string/);
+ expect(calls).toHaveLength(0);
+ });
+
+ it('still coerces safe numbers (e.g. limit: 25) to strings', async () => {
+ const { call } = mockCall();
+ const res = await runRecipe(SEARCH_RECIPE, { q: 25 }, { call });
+ expect(res.ok).toBe(true);
+ });
+
+ it('rejects an unsafe number even when the variable is NOT declared in inputs', async () => {
+ // RecipeSchema allows `inputs` to be omitted while vars is seeded with every
+ // caller entry — the safe-integer guard must not be bypassable that way.
+ const { call, calls } = mockCall();
+ const undeclared: Recipe = {
+ id: 'undeclared',
+ steps: [{ action: 'navigate', url: 'https://example.com/{{q}}' }],
+ };
+ const res = await runRecipe(undeclared, { q: 1892345678901234567 }, { call });
+ expect(res.ok).toBe(false);
+ expect(res.message).toMatch(/safe-integer range/);
+ expect(calls).toHaveLength(0);
+ });
+
it('fails loudly (never dispatches) when a saved recipe navigates to file://', async () => {
// The recipe path calls runtime.call directly, so the scheme guard must live
// in stepToRequest — a malicious saved recipe must not reach file:// even
diff --git a/packages/lizi-mcps/src/browser/recipe-runner.ts b/packages/lizi-mcps/src/browser/recipe-runner.ts
index de623dd4e8..3d7e1d2145 100644
--- a/packages/lizi-mcps/src/browser/recipe-runner.ts
+++ b/packages/lizi-mcps/src/browser/recipe-runner.ts
@@ -264,18 +264,37 @@ export async function runRecipe(
): Promise<RecipeRunResult> {
const vars: Record<string, unknown> = { ...(inputs ?? {}) };
for (const [name, spec] of Object.entries(recipe.inputs ?? {})) {
- const value = vars[name];
- if (spec.required && (value === undefined || value === null)) {
+ if (spec.required && (vars[name] === undefined || vars[name] === null)) {
return { ok: false, recipe: recipe.id, steps: [], message: `missing required input: ${name}` };
}
- // Declared inputs are interpolated into URLs / selectors / JS strings. Scalar
- // number/boolean/bigint values coerce cleanly (`String(50)` → "50") and are
- // exactly what built-in recipes advertise via siteguide (e.g. numeric `limit`),
- // so normalize them to their string form here. Objects/arrays would corrupt
- // into "[object Object]" / surprising JSON, so reject those loudly instead
- // (rule 9: code-enforced).
+ }
+ // Normalize EVERY caller-supplied value — not just declared inputs. vars is
+ // seeded with all caller entries and RecipeSchema allows `inputs` to be
+ // omitted, so an L2 recipe can interpolate an undeclared variable; the
+ // guards below must not be bypassable by leaving a name undeclared.
+ // Interpolated values land in URLs / selectors / JS strings. Scalar
+ // number/boolean/bigint values coerce cleanly (`String(50)` → "50") and are
+ // exactly what built-in recipes advertise via siteguide (e.g. numeric `limit`),
+ // so normalize them to their string form here. Objects/arrays would corrupt
+ // into "[object Object]" / surprising JSON, so reject those loudly instead
+ // (rule 9: code-enforced).
+ for (const [name, value] of Object.entries(vars)) {
if (value !== undefined && value !== null && typeof value !== 'string') {
if (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') {
+ // A number beyond the safe-integer range was ALREADY rounded by
+ // JSON.parse before we ever saw it (e.g. a 19-digit X snowflake id),
+ // so String(value) would bake the corrupted value into a URL/JS step.
+ // Fail loudly BEFORE any step runs instead of navigating with it.
+ if (typeof value === 'number' && Math.abs(value) > Number.MAX_SAFE_INTEGER) {
+ return {
+ ok: false,
+ recipe: recipe.id,
+ steps: [],
+ message:
+ `recipe input "${name}" exceeds the JSON safe-integer range and has lost precision — ` +
+ 'pass it as a string (e.g. a 19-digit tweet id must be quoted)',
+ };
+ }
vars[name] = String(value);
} else {
return {
diff --git a/packages/lizi-mcps/src/browser/recipes-builtin.test.ts b/packages/lizi-mcps/src/browser/recipes-builtin.test.ts
new file mode 100644
index 0000000000..ae2468b7d4
--- /dev/null
+++ b/packages/lizi-mcps/src/browser/recipes-builtin.test.ts
@@ -0,0 +1,94 @@
+/**
+ * Guards over the bundled L1 recipe catalog (`./recipes/<site>/{recipe,siteguide}.json`).
+ *
+ * The unit tests in recipe-loader.test.ts cover the parsers with hand-written
+ * fixtures; nothing so far validated the *shipped* JSON itself. These tests run
+ * the real `loadRecipes()` / `loadSiteGuides()` glob so a malformed bundled
+ * recipe (bad JSON, schema violation, duplicate id, unsafe `fn` interpolation,
+ * or a `{{var}}` that no input/`as` provides) fails CI instead of surfacing as
+ * a runtime "missing recipe variable" / injection hazard.
+ */
+import { describe, expect, it } from 'vitest';
+
+import { loadRecipes, loadSiteGuides, type Recipe } from './recipe-loader.js';
+import { findUnsafeEvaluateInterpolations } from './recipe-runner.js';
+
+const recipes = loadRecipes();
+const siteGuides = loadSiteGuides();
+
+// Same shape as recipe-runner's VAR_RE (kept local: the runner does not export it).
+const VAR_RE = /\{\{\s*([\w-]+)\s*(?:\|\s*([a-z]+)\s*)?\}\}/g;
+
+/** `{{var}}` names a single step interpolates. */
+function stepVarRefs(step: Recipe['steps'][number]): Set<string> {
+ const refs = new Set<string>();
+ const scan = (text: string | undefined) => {
+ if (!text) return;
+ for (const m of text.matchAll(new RegExp(VAR_RE.source, 'g'))) refs.add(m[1]);
+ };
+ scan(step.url);
+ scan(step.selector);
+ scan(step.fn);
+ scan(step.value);
+ scan(step.textGone);
+ scan(step.filter);
+ for (const v of step.values ?? []) scan(v);
+ return refs;
+}
+
+
+describe('bundled recipe catalog', () => {
+ it('loads at least the known catalog size', () => {
+ // Loading itself already enforces valid JSON / schema / unique ids (loadRecipes throws).
+ expect(recipes.size).toBeGreaterThanOrEqual(50);
+ expect(siteGuides.size).toBeGreaterThanOrEqual(50);
+ });
+
+ it('every recipe passes the unsafe-fn-interpolation lint (|js required inside fn)', () => {
+ for (const [id, recipe] of recipes) {
+ expect(findUnsafeEvaluateInterpolations(recipe), `recipe ${id}`).toEqual([]);
+ }
+ });
+
+ it('every {{var}} reference resolves in execution order (preceding `as` or required input)', () => {
+ // Mirrors runRecipe exactly: `as` lands in vars only AFTER its step
+ // succeeds, and the runner has no input defaults. So at each reference
+ // point the variable must come from a PRECEDING step's `as`, or be a
+ // `required:true` input — a later producer, an undeclared name, or an
+ // optional input referenced before its producer would all throw
+ // "missing recipe variable" at runtime.
+ for (const [id, recipe] of recipes) {
+ const inputs = recipe.inputs ?? {};
+ const produced = new Set<string>();
+ const checkRef = (name: string, where: string) => {
+ if (produced.has(name)) return; // satisfied by a preceding step's `as`
+ expect(
+ inputs[name]?.required,
+ `recipe ${id}: ${where} references {{${name}}}, which is neither a preceding step's \`as\` nor a required:true input`,
+ ).toBe(true);
+ };
+ recipe.steps.forEach((step, i) => {
+ for (const name of stepVarRefs(step)) checkRef(name, `step ${i} (${step.action})`);
+ if (step.as) produced.add(step.as);
+ });
+ if (recipe.output) {
+ for (const m of recipe.output.matchAll(new RegExp(VAR_RE.source, 'g'))) checkRef(m[1], 'output');
+ }
+ }
+ });
+
+ it('every siteguide `recipes` entry points at an existing recipe id', () => {
+ for (const [site, guide] of siteGuides) {
+ for (const rid of guide.recipes ?? []) {
+ expect(recipes.has(rid), `siteguide ${site} references unknown recipe "${rid}"`).toBe(true);
+ }
+ }
+ });
+
+ it('every recipe is listed by some siteguide (discoverable via siteguide action)', () => {
+ const listed = new Set([...siteGuides.values()].flatMap((g) => g.recipes ?? []));
+ for (const id of recipes.keys()) {
+ expect(listed.has(id), `recipe ${id} is not referenced by any siteguide`).toBe(true);
+ }
+ });
+});
diff --git a/packages/lizi-mcps/src/browser/recipes/api.fxtwitter.com/recipe.json b/packages/lizi-mcps/src/browser/recipes/api.fxtwitter.com/recipe.json
new file mode 100644
index 0000000000..e23461c448
--- /dev/null
+++ b/packages/lizi-mcps/src/browser/recipes/api.fxtwitter.com/recipe.json
@@ -0,0 +1,16 @@
+{
+ "id": "x-tweet",
+ "match": ["api.fxtwitter.com", "x.com", "twitter.com"],
+ "description": "免登录读取单条 X(Twitter)公开推文:正文/作者/互动数/媒体/引用。走 FxTwitter 公开 API(无需登录、无需 API key),id 传推文数字 id(URL 里 /status/ 后面那串),**必须作为字符串传入**——19 位雪花 id 超出 JSON number 安全整数范围,传数字会丢精度。私密与已删推文取不到;时间线/搜索见 x.com 的 siteguide(需登录)。",
+ "inputs": { "id": { "required": true } },
+ "steps": [
+ { "action": "navigate", "url": "https://api.fxtwitter.com/status/{{id|url}}" },
+ { "action": "wait", "loadState": "load" },
+ {
+ "action": "evaluate",
+ "as": "tweet",
+ "fn": "() => { let d; try { d = JSON.parse(document.body.innerText); } catch (e) { throw new Error('fxtwitter 返回非 JSON(可能被网络设备拦截或服务异常),页面开头:' + document.body.innerText.slice(0, 200)); } if (!d.tweet) throw new Error('未找到推文(code ' + d.code + ' ' + d.message + '):id 是否正确?私密/已删推文取不到;注意 id 必须以字符串传入,JSON number 会对 19 位雪花 id 丢精度'); const t = d.tweet; if (String(t.id) !== '{{id|js}}') throw new Error('返回的推文 id(' + t.id + ')与请求 id({{id|js}})不一致——id 很可能因以 JSON number 传入而丢精度,请改为字符串重试'); const a = t.author || {}; const m = t.media || {}; const media = (m.photos || []).map(p => ({ type: 'photo', url: p.url })).concat((m.videos || []).map(v => ({ type: v.type || 'video', url: v.url, thumbnail: v.thumbnail_url }))); return { url: t.url, id: t.id, text: t.text, lang: t.lang, created_at: t.created_at, author: { name: a.name, screen_name: a.screen_name, followers: a.followers }, replies: t.replies, retweets: t.retweets, likes: t.likes, quotes: t.quotes, bookmarks: t.bookmarks, views: t.views, replying_to: t.replying_to, media, quote: t.quote ? { text: t.quote.text, author: t.quote.author && t.quote.author.screen_name, url: t.quote.url } : null }; }"
+ }
+ ],
+ "output": "{{tweet}}"
+}
diff --git a/packages/lizi-mcps/src/browser/recipes/api.fxtwitter.com/siteguide.json b/packages/lizi-mcps/src/browser/recipes/api.fxtwitter.com/siteguide.json
new file mode 100644
index 0000000000..660f760576
--- /dev/null
+++ b/packages/lizi-mcps/src/browser/recipes/api.fxtwitter.com/siteguide.json
@@ -0,0 +1,11 @@
+{
+ "site": "api.fxtwitter.com",
+ "auth": "无需登录、无需 API key:FxTwitter(FixTweet)是公开只读 API,读 X(Twitter)公开内容的首选,优先于走 x.com 登录态",
+ "entry": {
+ "tweet": "https://api.fxtwitter.com/status/<id>",
+ "tweetWithUser": "https://api.fxtwitter.com/<screen_name>/status/<id>",
+ "userProfile": "https://api.fxtwitter.com/<screen_name>"
+ },
+ "recipes": ["x-tweet"],
+ "notes": "读单条 X 公开推文最省最稳的路径,直接 navigate 到 API URL 再解析 body JSON,不碰 x.com 风控。响应 {code,message,tweet:{text,author:{screen_name,name,followers},replies,retweets,likes,quotes,bookmarks,views,created_at,lang,replying_to,media:{photos[],videos[]},quote}};code 404 = 不存在/已删/私密。x-tweet 配方封装 /status/<id> 并展平常用字段。另有免登录用户资料端点 /<screen_name>(响应 {code,message,user:{screen_name,name,followers,following,tweets,likes,description,joined,...}}),无需配方、照同样姿势 navigate + 解析即可,可替代需登录的 x.com twitter-profile 配方。能力边界:只覆盖单条推文与用户资料;时间线/搜索/回复列表这个 API 做不到——需要登录态走 x.com 内部 GraphQL(见 x.com siteguide)。"
+}
diff --git a/packages/lizi-mcps/src/browser/recipes/mp.weixin.qq.com/recipe.json b/packages/lizi-mcps/src/browser/recipes/mp.weixin.qq.com/recipe.json
new file mode 100644
index 0000000000..e922cda302
--- /dev/null
+++ b/packages/lizi-mcps/src/browser/recipes/mp.weixin.qq.com/recipe.json
@@ -0,0 +1,16 @@
+{
+ "id": "wechat-article",
+ "match": ["mp.weixin.qq.com"],
+ "description": "读取一篇微信公众号文章:标题/公众号名/作者/发布时间/正文全文/正文图片地址。无需登录,url 传文章分享链接(https://mp.weixin.qq.com/s/... 或 /s?__biz=... 形式)。注意:没有免登录的搜索/列表接口,文章链接需由用户提供。",
+ "inputs": { "url": { "required": true } },
+ "steps": [
+ { "action": "navigate", "url": "{{url}}" },
+ { "action": "wait", "loadState": "load" },
+ {
+ "action": "evaluate",
+ "as": "article",
+ "fn": "() => { if (location.hostname !== 'mp.weixin.qq.com') { throw new Error('当前页面不是微信公众号文章(host: ' + location.hostname + '),url 必须是 https://mp.weixin.qq.com/s/... 链接'); } const q = (s) => { const el = document.querySelector(s); return el ? el.textContent.trim() : ''; }; const content = document.querySelector('#js_content'); if (!content) { throw new Error('页面没有正文容器 #js_content(链接可能已过期、文章被删除/屏蔽,或被环境验证页拦截)。页面开头:' + (document.body.innerText || '').slice(0, 120)); } const images = Array.from(content.querySelectorAll('img')).map(im => im.getAttribute('data-src') || im.getAttribute('src') || '').filter(u => u.indexOf('http') === 0); const full = content.innerText.trim(); const MAX = 40000; return { title: q('#activity-name') || document.title, account: q('#js_name'), author: q('#js_author_name'), publishTime: q('#publish_time'), text: full.slice(0, MAX), truncated: full.length > MAX, images }; }"
+ }
+ ],
+ "output": "{{article}}"
+}
diff --git a/packages/lizi-mcps/src/browser/recipes/mp.weixin.qq.com/siteguide.json b/packages/lizi-mcps/src/browser/recipes/mp.weixin.qq.com/siteguide.json
new file mode 100644
index 0000000000..343153317a
--- /dev/null
+++ b/packages/lizi-mcps/src/browser/recipes/mp.weixin.qq.com/siteguide.json
@@ -0,0 +1,10 @@
+{
+ "site": "mp.weixin.qq.com",
+ "auth": "无需登录:公众号文章分享链接是公开页面,持久浏览器直接打开即可(真浏览器执行 JS 后正文可见,不需要伪装微信 UA)",
+ "entry": {
+ "article": "https://mp.weixin.qq.com/s/<key>",
+ "articleLegacy": "https://mp.weixin.qq.com/s?__biz=<biz>&mid=<mid>&idx=<idx>&sn=<sn>"
+ },
+ "recipes": ["wechat-article"],
+ "notes": "关键选择器:标题 #activity-name、公众号名 #js_name、作者 #js_author_name(部分文章没有)、发布时间 #publish_time(由页面内联 JS 填充,load 后可读)、正文容器 #js_content。正文图片是懒加载:真实地址在 img[data-src] 而非 src;图片域名 mmbiz.qpic.cn 有防盗链,浏览器外直接下载需带 Referer: https://mp.weixin.qq.com/。wechat-article 配方返回全文文本(超 4 万字符截断并标 truncated)与图片地址列表。能力边界:mp.weixin.qq.com 没有免登录的搜索/列表接口,「列出某公众号历史文章」做不到,文章 URL 需由用户提供(聊天分享/收藏)。失败模式:#js_content 缺失 = 链接过期(带 chksm 的临时链接有时效)、文章被删除/违规屏蔽、或频繁访问触发环境验证页——遇验证页应停下告知用户,不要反复重试。"
+}
diff --git a/packages/lizi-mcps/src/browser/recipes/scrapethissite.com/siteguide.json b/packages/lizi-mcps/src/browser/recipes/scrapethissite.com/siteguide.json
new file mode 100644
index 0000000000..9cdb835918
--- /dev/null
+++ b/packages/lizi-mcps/src/browser/recipes/scrapethissite.com/siteguide.json
@@ -0,0 +1,9 @@
+{
+ "site": "scrapethissite.com",
+ "auth": "无需登录:公开的抓取练习沙盒站",
+ "entry": {
+ "forms": "https://www.scrapethissite.com/pages/forms/"
+ },
+ "recipes": ["hockey-search"],
+ "notes": "抓取练习沙盒,hockey-search 是交互步(type+submit → extract)的示例配方,也可用作端到端验证配方引擎是否正常的探针站。"
+}
diff --git a/packages/lizi-mcps/src/browser/recipes/x.com/siteguide.json b/packages/lizi-mcps/src/browser/recipes/x.com/siteguide.json
index 865a551191..3fda5bdcef 100644
--- a/packages/lizi-mcps/src/browser/recipes/x.com/siteguide.json
+++ b/packages/lizi-mcps/src/browser/recipes/x.com/siteguide.json
@@ -7,5 +7,5 @@
"homeTimeline": "https://x.com/i/api/graphql/<queryId>/HomeTimeline?variables=...&features=..."
},
"recipes": ["twitter-profile"],
- "notes": "x.com(原 twitter.com)所有数据走内部 GraphQL /i/api/graphql/<queryId>/<Operation>。策略:cookie/login + 页面内取 token。关键姿势——先 navigate 到 https://x.com 拿到同源 + 登录 cookie,在同一个 evaluate fn 里:(a) 从 document.cookie 读出 ct0 当 X-Csrf-Token;(b) 用网页端公开固定 bearer(配方里已内置,非用户私密 token)拼 Authorization;(c) 带 X-Twitter-Auth-Type:OAuth2Session、X-Twitter-Active-User:yes;(d) fetch 内部 graphql 接口、credentials:include。twitter-profile 配方封装 UserByScreenName,返回展平后的 {screen_name,name,bio,location,followers,following,tweets,likes,verified,created_at,url}。重要坑:GraphQL 的 queryId 会随网页端版本变化,配方里内置的是一个已知 fallback queryId,大多数时候可用;若某天返回非 JSON 或报 queryId expired,需要从当前页面加载的 client-web *.js bundle 里重新抓 'queryId:\"...\"' + 'operationName:\"UserByScreenName\"' 对应的最新 id 替换。其它读接口同理但不在配方内:1) 首页时间线 HomeTimeline(for-you,GET)/ HomeLatestTimeline(following,POST),响应在 data.home.home_timeline_urt.instructions[].entries[].content.itemContent.tweet_results.result(取 legacy.full_text/favorite_count/retweet_count 等),需要分页 cursor;2) 推文搜索 SearchTimeline 在网页端是 SPA 内部 XHR、queryId 同样易变,纯 fetch 复现不稳定,优先用 profile / timeline。"
+ "notes": "先看免登录捷径:读单条公开推文用 api.fxtwitter.com 的 x-tweet 配方,读公开用户资料也可走 api.fxtwitter.com/<screen_name>(见 api.fxtwitter.com siteguide),都不需要登录、不碰 x.com 风控;只有时间线/搜索/回复列表这类必须登录态的才走本站内部 GraphQL。x.com(原 twitter.com)所有数据走内部 GraphQL /i/api/graphql/<queryId>/<Operation>。策略:cookie/login + 页面内取 token。关键姿势——先 navigate 到 https://x.com 拿到同源 + 登录 cookie,在同一个 evaluate fn 里:(a) 从 document.cookie 读出 ct0 当 X-Csrf-Token;(b) 用网页端公开固定 bearer(配方里已内置,非用户私密 token)拼 Authorization;(c) 带 X-Twitter-Auth-Type:OAuth2Session、X-Twitter-Active-User:yes;(d) fetch 内部 graphql 接口、credentials:include。twitter-profile 配方封装 UserByScreenName,返回展平后的 {screen_name,name,bio,location,followers,following,tweets,likes,verified,created_at,url}。重要坑:GraphQL 的 queryId 会随网页端版本变化,配方里内置的是一个已知 fallback queryId,大多数时候可用;若某天返回非 JSON 或报 queryId expired,需要从当前页面加载的 client-web *.js bundle 里重新抓 'queryId:\"...\"' + 'operationName:\"UserByScreenName\"' 对应的最新 id 替换。其它读接口同理但不在配方内:1) 首页时间线 HomeTimeline(for-you,GET)/ HomeLatestTimeline(following,POST),响应在 data.home.home_timeline_urt.instructions[].entries[].content.itemContent.tweet_results.result(取 legacy.full_text/favorite_count/retweet_count 等),需要分页 cursor;2) 推文搜索 SearchTimeline 在网页端是 SPA 内部 XHR、queryId 同样易变,纯 fetch 复现不稳定,优先用 profile / timeline。"
}
diff --git a/packages/lizi-mcps/src/browser/tools.ts b/packages/lizi-mcps/src/browser/tools.ts
index 30fda29cd4..272fb4f838 100644
--- a/packages/lizi-mcps/src/browser/tools.ts
+++ b/packages/lizi-mcps/src/browser/tools.ts
@@ -444,6 +444,10 @@ export function registerBrowserTools(registry: BrowserToolRegistry, deps: Browse
const spec = r?.recipe.inputs ?? {};
return {
id,
+ // Surface the author's description at discovery time — it carries
+ // input constraints (e.g. "id must be passed as a string") that the
+ // bare input-name list cannot express.
+ description: r?.recipe.description,
inputs: Object.keys(spec),
required: Object.entries(spec)
.filter(([, v]) => v?.required)