AnyBot/.claude/skills/verify-anybot/scripts/fake-model.mjs

110 lines
6.0 KiB
JavaScript
Raw Normal View History

feat: 驗證用 skill verify-anybot——隔離的 scratch AnyBot、假模型、無頭 Chrome 操作手機頁面 照 pstack 的 create-verification-skill 產生(Claude Code 放在 .claude/skills/)。功能地圖沿用 docs/feature-map/,skill 不另放一份:改哪一區就開那一份照「驗證:」走,skill 補上怎麼開、怎麼操作、 怎麼留證據、怎麼收乾淨。 - scripts/ctl:build、up(假模型 → setup --seed 建 Bot → --serve)、doctor、serve/stop/restart、 ask(--ask --json)、api(手機 API)、phone(無頭 Chrome 操作手機頁面)、state、down(收掉,證據留在 target/verify-anybot/<時間>/)。 - scripts/scratch-env:每個 scratch AnyBot 的隔離環境(env -i、DOCKER_HOST 指到不存在、自己的 HOME 和資料夾、Hugging Face 連不上、保險庫金鑰放檔案),拒絕裸的 anybot 和 AnyBot.app。 - ctl up 先放 vault-index-imported 標記:scratch 不會跑 security dump-keychain 去列使用者的鑰匙圈。 - scripts/fake-model.mjs:OpenAI 相容的假模型,回固定答案,訊息裡寫 [[call 工具 {JSON}]] 就叫那個工具。 - scripts/phone.mjs:只用 Node 內建 fetch/WebSocket 的 CDP 驅動,390×844 的 iPhone 畫面,只信任 scratch 那張憑證的公鑰。 - docs/feature-map/README.md:「驗證指令工具還沒做」改成指向這個 skill。 已驗證: cargo test featuremap::(5 個全過);照 SKILL.md 從頭跑 phone 區的範例旅程(ctl build 後整段照貼, 結束碼 0):錯密碼顯示「密碼不對」、正確密碼看到 Bot 清單、手機傳訊息拿到假模型回答、update_bot 的允許卡片 按「允許」後名稱改了且大腦的 approvals 變空、按「拒絕」後步驟是 denied 名稱不變、restart 後登入和聊天都還在、 手機與帳號頁登出 verify-cli 後它拿 401、這支手機自己登出回到登入頁、ctl down 後證據還在、沒有殘留程式、 使用者的 Docker 和 Lima 沒動;另外跑過 ctl up --no-serve + --ask --json(含自動拒絕核准)和 scratch-env --sample-state。 未驗證: 電腦版視窗的路(設定 › 手機與帳號 的開關和裝置清單、桌面上的允許卡片同步消失、ctl desktop-shot) ——會在使用者正在用的 Mac 螢幕上開視窗,這次不跑;帳號登入、推播通知、App 圖示數字——要 relay 帳號伺服器 和真的手機;外觀顏色跟著電腦——要在桌面改;完整 cargo test、layout_audit:: 沒跑——沒有改 src/。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 02:17:13 +00:00
#!/usr/bin/env node
// 驗證用的假模型:OpenAI 相容的 /v1/chat/completions,回固定答案,不連任何真的模型服務。
// AnyBot 的「自訂(OpenAI 相容)」供應商指到這裡(ctl up 用 `setup --seed` 設好)。
//
// 規則(只看最後一則訊息,所以不會無限迴圈):
// - 最後一則是工具結果 → 文字「FAKE-MODEL 收到工具結果:…」,這一輪結束。
// - 使用者訊息裡有 [[call 工具 {JSON}]] → 叫那個工具(這一輪的工具清單裡要有)。
// - 其他 → 文字「FAKE-MODEL 回答:<使用者那句>」。
// - 沒帶工具的請求(AnyBot 自己的小工作:摘要、記憶、標題…)→ 文字「FAKE-MODEL 輔助回答」。
// 每個請求寫一行到 --log(JSONL):時間、種類、工具數、最後一則、回了什麼。只聽 127.0.0.1。
//
// 用法:node fake-model.mjs --port 0 --log requests.jsonl --port-file model.port
import http from "node:http";
import fs from "node:fs";
const arg = (name, dflt) => {
const i = process.argv.indexOf(name);
return i > 0 && process.argv[i + 1] !== undefined ? process.argv[i + 1] : dflt;
};
const PORT = Number(arg("--port", "0"));
const LOG = arg("--log", "");
const PORT_FILE = arg("--port-file", "");
const MODEL = "fake-model";
const log = (entry) => {
if (LOG) fs.appendFileSync(LOG, JSON.stringify({ t: new Date().toISOString(), ...entry }) + "\n");
};
const textOf = (content) => {
if (typeof content === "string") return content;
if (Array.isArray(content)) return content.map((p) => (typeof p === "string" ? p : p?.text ?? "")).join("");
return "";
};
// What to answer: {text} or {call: {name, args}}.
function decide(body) {
const msgs = Array.isArray(body.messages) ? body.messages : [];
const tools = (Array.isArray(body.tools) ? body.tools : []).map((t) => t?.function?.name ?? t?.name).filter(Boolean);
const last = msgs[msgs.length - 1] ?? {};
const lastUser = [...msgs].reverse().find((m) => m.role === "user");
const userText = textOf(lastUser?.content);
const info = { tools: tools.length, last_role: last.role ?? "", user: userText.slice(0, 200) };
if (tools.length === 0) return { info: { ...info, kind: "aux" }, text: "FAKE-MODEL 輔助回答" };
if (last.role === "tool") {
return { info: { ...info, kind: "after-tool", tool_result: textOf(last.content).slice(0, 200) }, text: `FAKE-MODEL 收到工具結果:${textOf(last.content).slice(0, 80)}` };
}
const m = last.role === "user" ? textOf(last.content).match(/\[\[call\s+([A-Za-z0-9_.:-]+)\s*(\{[\s\S]*?\})?\s*\]\]/) : null;
if (m) {
const name = m[1];
let args = {};
try { args = m[2] ? JSON.parse(m[2]) : {}; } catch (e) { return { info: { ...info, kind: "bad-directive" }, text: `FAKE-MODEL:[[call]] 的 JSON 看不懂(${e.message})` }; }
if (!tools.includes(name)) return { info: { ...info, kind: "missing-tool", want: name }, text: `FAKE-MODEL:這一輪沒有 ${name} 這個工具(有:${tools.slice(0, 30).join("、")})` };
return { info: { ...info, kind: "call" }, call: { name, args } };
}
// (AnyBot 在訊息後面加的〔送出時間…〕〔用繁體中文…〕提示不回聲,答案才固定。)
const said = userText.replace(/〔[^〕]*〕/g, "").replace(/\s+/g, " ").trim();
return { info: { ...info, kind: "turn" }, text: `FAKE-MODEL 回答:${said.slice(0, 200)}` };
}
let calls = 0;
function answer(res, body, d) {
const id = `call_fake_${++calls}`;
if (body.stream) {
res.writeHead(200, { "Content-Type": "text/event-stream", "Cache-Control": "no-cache", Connection: "close" });
const delta = d.call
? { tool_calls: [{ index: 0, id, type: "function", function: { name: d.call.name, arguments: JSON.stringify(d.call.args) } }] }
: { role: "assistant", content: d.text };
res.write(`data: ${JSON.stringify({ id: "fake", object: "chat.completion.chunk", model: MODEL, choices: [{ index: 0, delta }] })}\n\n`);
res.write(`data: ${JSON.stringify({ id: "fake", object: "chat.completion.chunk", model: MODEL, choices: [{ index: 0, delta: {}, finish_reason: d.call ? "tool_calls" : "stop" }] })}\n\n`);
res.end("data: [DONE]\n\n");
return;
}
const message = d.call
? { role: "assistant", content: null, tool_calls: [{ id, type: "function", function: { name: d.call.name, arguments: JSON.stringify(d.call.args) } }] }
: { role: "assistant", content: d.text };
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ id: "fake", object: "chat.completion", model: MODEL, choices: [{ index: 0, message, finish_reason: d.call ? "tool_calls" : "stop" }] }));
}
const server = http.createServer((req, res) => {
let raw = "";
req.on("data", (c) => (raw += c));
req.on("end", () => {
const path = (req.url || "").split("?")[0];
if (req.method === "GET" && path.endsWith("/models")) {
log({ method: req.method, path, kind: "models" });
res.writeHead(200, { "Content-Type": "application/json" });
return res.end(JSON.stringify({ object: "list", data: [{ id: MODEL, object: "model" }] }));
}
if (req.method === "POST" && path.endsWith("/chat/completions")) {
let body = {};
try { body = JSON.parse(raw || "{}"); } catch (_) {}
const d = decide(body);
log({ method: req.method, path, model: body.model ?? "", stream: !!body.stream, ...d.info, reply: d.call ? { call: d.call } : { text: d.text } });
return answer(res, body, d);
}
log({ method: req.method, path, kind: "unknown" });
res.writeHead(404, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: { message: `fake model: no ${req.method} ${path}` } }));
});
});
server.listen(PORT, "127.0.0.1", () => {
const port = server.address().port;
if (PORT_FILE) fs.writeFileSync(PORT_FILE, String(port));
console.log(`fake model listening on http://127.0.0.1:${port}/v1`);
});
for (const sig of ["SIGINT", "SIGTERM"]) process.on(sig, () => server.close(() => process.exit(0)));