/** * ============================================================ * vision/appGuide.ts —— 应用指南的发现与匹配 * ------------------------------------------------------------ * 问题:靠**应用显示名精确匹配**去找 `apps/.md` 在真实环境里会静默失败, * 且失败得毫无提示: * - 同一应用中英文名不同(`WeChat` vs `微信`),取决于系统语言 * - 应用改名、版本更迭、企业定制版换 displayName * - 多语言环境下系统报的显示名本身就会变 * * 对策:按**稳定标识**优先匹配 —— bundleId(macOS)/ 可执行文件名(Windows) * 是应用的真身份,几乎不会变;显示名只作兜底。 * * ★ 匹配失败必须**如实报告**「未找到指南」,不静默降级。 * 静默的后果是模型以为自己有该应用的知识、实际在裸奔,而没人知道。 * * frontmatter 用 `yaml` 库真解析(`manualSchema.ts`)。这里曾经有一个手搓的 * 受限解析器,理由是「零依赖」;但 schema v2 有两层嵌套(flows.steps[]), * 受限解析器表达不了,而 `yaml` 早已是本项目依赖(skillList / workflow-runner * 都在用)——「零依赖」在这里已经不是真实约束,只是历史。 * ============================================================ */ import { existsSync, readdirSync } from 'node:fs'; import { readdir, readFile } from 'node:fs/promises'; import { join } from 'node:path'; import { getResourceSearchPaths } from '../../../utils/resourcePaths.js'; import { readPluginManifest } from '../../../plugins/pluginManifest.js'; import { EMPTY_MANUAL, normalizeIrreversible, normalizeIrreversibleWithLevels, splitManual, toAppManual, validateManual, type AppManual, } from '../manualSchema.js'; /** * 工作区说明书目录名。**第一方资源**,与 `skills/` `workflows/` 同构。 * * 它是 `/computeruse capture --write` 的落点,因此必须满足两件事: * ① 用户 cwd 里**不需要任何 manifest 引导** —— 让每个业务项目为了存一份说明书 * 长出一个完整插件目录是荒唐的 * ② **不能被 `/new` 删掉** —— `persistContext.ts::clearContext` 会递归清空 cwd * 下所有 `.minimal-agent` / `.minimal-agent-*` 目录。捕获的说明书是**长期 * 知识**,不是会话状态,放进那个前缀等于用户跑一次 `/new` 就全没了 */ export const WORKSPACE_MANUAL_DIR = 'app-manuals'; /** 一个说明书来源。`kind` 决定优先级,也决定它是否可写。 */ export interface ManualProvider { kind: 'workspace' | 'plugin'; /** 展示名:工作区目录名,或提供说明书的插件名 */ label: string; dir: string; } /** * 说明书的两类来源,**按优先级从高到低**返回。 * * ① 工作区 `/app-manuals/` —— 用户自己的,可写,优先级最高 * ② 插件声明 —— plugin.json 里 `"appManuals": "app"` 的**显式 opt-in** * * ★ 第二类此前是纯目录约定(任何插件目录下有 `app` 子目录就自动生效), * 等于「任意目录自动影响可信内核」。现在必须显式声明,且路径经 * `pluginManifest.ts::resolveInsidePlugin` 收敛(拒绝绝对路径 / `..` / 软链逃逸)。 * * ★ 刻意**不走** `discoverPlugins()`:它按 manifest 名去重,于是 cwd 里放一个 * 同名插件会把包内插件**整体**屏蔽掉。而说明书的既有语义是**逐文件覆盖** * (放一份 `wechat.md` 只该覆盖那一份)。这里按目录逐个读 manifest,保住这一点。 * * 必须走 `getResourceSearchPaths` 而不是 `import.meta.url` 直接拼:绿色版 * (`bun --compile`)下后者是嵌入式虚拟路径,拼出来的目录在磁盘上不存在, * 说明书会静默全部失效。 */ export function appManualProviders(workingDir?: string): ManualProvider[] { const providers: ManualProvider[] = []; for (const dir of getResourceSearchPaths(WORKSPACE_MANUAL_DIR, import.meta.url, workingDir)) { if (existsSync(dir)) providers.push({ kind: 'workspace', label: WORKSPACE_MANUAL_DIR, dir }); } for (const root of getResourceSearchPaths('plugins', import.meta.url, workingDir)) { let entries: string[]; try { entries = readdirSync(root); } catch { continue; } // 排序理由同 skillList.ts:来源顺序决定同名覆盖的赢家,fs 返回顺序不稳定 // 会让同一份目录在不同机器上得到不同结果。 for (const entry of [...entries].sort()) { if (entry.startsWith('.')) continue; const pluginRoot = join(root, entry); const manifest = readPluginManifest(pluginRoot); for (const dir of manifest?.appManualDirs ?? []) { providers.push({ kind: 'plugin', label: manifest?.name ?? entry, dir }); } } } return providers; } export interface AppGuide { /** 文件名(不含 .md) */ name: string; /** 绝对路径 */ path: string; bundleIds: string[]; processNames: string[]; displayNames: string[]; /** * 应用声明的全部不可逆动作标识(归一为 `kind:value` 格式)。 * * 包含两个来源的合并结果: * - 旧格式 `irreversible:` 列表 → 全部计入 * - 新格式 `irreversible.critical:` + `irreversible.normal:` → 分别计入 * * 风险分级不在这里区分,由 `classifyIrreversibleRisk` 结合 * 全局高危黑名单与应用级 critical 列表共同判定。 */ irreversible: string[]; /** * 应用级高危(critical)不可逆列表。 * 这些动作即使在 supervised=false 时也必须人工确认。 * 元素格式与 irreversible 一致(`kind:value`)。 * 可选:未声明时等价于空数组(即该应用没有自定义的高危红线, * 只用全局黑名单判定)。 */ irreversibleCritical?: string[]; /** * schema v2 的结构化部分。v1 说明书解析出来是各字段皆空的 manual, * 因此消费方不必区分版本 —— 「没声明」和「旧格式」在行为上本来就一样。 * * 可选是为了让**合成 guide**(测试里只关心匹配与不可逆判定的那些)不必 * 编造一份空 manual;`parseGuide` 走过的真实说明书一定有值。 */ manual?: AppManual; /** frontmatter 之后的正文(散文层)。 */ body?: string; } const asList = (v: unknown): string[] => Array.isArray(v) ? v.map(String) : v ? [String(v)] : []; /** 把一份说明书内容解析成 AppGuide。文件读取与目录扫描留给调用方。 */ export function parseGuide(name: string, path: string, content: string): AppGuide { const { raw, body } = splitManual(content); const rawMatch = raw.match; const match: Record = rawMatch && typeof rawMatch === 'object' && !Array.isArray(rawMatch) ? (rawMatch as Record) : {}; // 不可逆:支持新旧两种 frontmatter 写法。 // // 旧格式: // irreversible: // - intent:send-message // - intent:payment-or-transfer // → 全部计入 irreversible,并按全局黑名单自动分级。 // // 新格式(推荐): // irreversible: // critical: // - intent:payment-or-transfer // - intent:remove-contact // normal: // - intent:send-message // - intent:send-file // → critical 列表计入 irreversibleCritical,两个列表合并入 irreversible。 const rawIrreversible = raw.irreversible; const { all: irreversible, critical: irreversibleCritical } = normalizeIrreversibleWithLevels(rawIrreversible); return { name, path, // 标识一律小写化:匹配要大小写不敏感(`WeChat` / `wechat` / `WECHAT` // 在不同来源里都出现过),把归一放在加载期做一次比在每个比较点做一次可靠。 bundleIds: asList(match.bundleId).map((s) => s.toLowerCase()), processNames: asList(match.processName).map((s) => s.toLowerCase()), displayNames: asList(match.displayName).map((s) => s.toLowerCase()), irreversible, irreversibleCritical, manual: toAppManual(raw), body, }; } /** 说明书之间的冲突。两类都会让「哪一份生效」变成目录顺序的副产品。 */ export interface ManualConflict { kind: 'same-name' | 'same-identity'; /** 冲突的标识(guide 名,或被两份说明书同时认领的 bundleId/进程名/显示名) */ key: string; /** 生效的那一份 */ winner: string; /** 被遮蔽的那一份 */ shadowed: string; } /** * 因为自身写错而**没有进入匹配池**的说明书。 * * 保留整个 `guide` 而不只是名字路径:调用方需要拿它的 match 声明去回答 * 「当前这个应用是不是**本该**有说明书」——只报「没找到」会把一个能修的 * 问题表现成一个不存在的问题。 */ export interface RejectedManual { guide: AppGuide; /** 只含 `level:'error'` 的那些 —— warn 不构成拒绝理由。 */ errors: string[]; } export interface LoadedManuals { guides: AppGuide[]; conflicts: ManualConflict[]; rejected: RejectedManual[]; } /** * 一份说明书是否**坏到不该进模型上下文**。 * * 为什么在加载期就拦,而不是等诊断命令去发现:写错的失败方式全是**静默**的 * —— `match` 写错就永远匹配不上、`precondition` 写错就永远不生效、 * `actionClass` 拼错就等于没写。而一份坏说明书进了上下文**比没有说明书更糟**: * 模型会照着执行一套并不存在的流程,且回执里看不出任何异常。 * * 只拦 error,warn 照常加载 —— warn 说的是「这样写会不稳」(例如控件只有坐标 * 没有 AX 锚点),那仍然是可用的知识。 */ function rejectionOf(guide: AppGuide): RejectedManual | null { const errors = validateManual({ manual: guide.manual ?? EMPTY_MANUAL, irreversible: guide.irreversible, identifiers: guide.bundleIds.length + guide.processNames.length + guide.displayNames.length, }) .filter((issue) => issue.level === 'error') .map((issue) => issue.message); return errors.length > 0 ? { guide, errors } : null; } const manualCache = new Map(); /** * 从所有来源加载说明书,**先扫到的胜出**(工作区 > cwd 插件 > 包内插件), * 并报告冲突。 * * ★ 冲突检测不能只看文件名。`wechat.md` 与 `my-wechat.md` 可以同时声明 * `bundleId: com.tencent.xinWeChat` —— 文件名不同、身份相同,`matchGuide` * 只会返回先扫到的那一份,另一份**永远不生效且没人知道**。目录顺序决定 * 哪份知识生效,这不该是静默的。 * * ★ 结果按 workingDir 做进程级内存缓存。manual 文件在运行时不会动态修改, * 重复扫文件系统是纯浪费;region 吸附每次动作都调用,缓存带来的收益显著。 * 目录不存在/无说明书的空结果也会缓存,避免每次都重新扫。 */ export async function loadAllAppManuals(workingDir?: string): Promise { const cacheKey = workingDir; const cached = manualCache.get(cacheKey); if (cached) return cached; const byName = new Map(); const byIdentity = new Map(); const conflicts: ManualConflict[] = []; const rejected: RejectedManual[] = []; for (const provider of appManualProviders(workingDir)) { for (const guide of await loadGuides(provider.dir).catch(() => [])) { // 校验在**去重之前**:一份坏说明书不该先占住名字再被发现有问题, // 那会把同名的好说明书一起挡在门外。 const rejection = rejectionOf(guide); if (rejection) { rejected.push(rejection); continue; } const existing = byName.get(guide.name); if (existing) { conflicts.push({ kind: 'same-name', key: guide.name, winner: existing.path, shadowed: guide.path, }); continue; } byName.set(guide.name, guide); for (const identity of [...guide.bundleIds, ...guide.processNames, ...guide.displayNames]) { const owner = byIdentity.get(identity); if (owner && owner.name !== guide.name) { conflicts.push({ kind: 'same-identity', key: identity, winner: owner.path, shadowed: guide.path, }); continue; } if (!owner) byIdentity.set(identity, guide); } } } const result: LoadedManuals = { guides: [...byName.values()], conflicts, rejected }; manualCache.set(cacheKey, result); return result; } /** 扫描 app/ 目录,读出每份说明书。`_` 前缀的(模板)跳过。 */ export async function loadGuides(appsDir: string): Promise { const entries = await readdir(appsDir).catch(() => [] as string[]); const guides: AppGuide[] = []; for (const file of [...entries].sort()) { if (!file.endsWith('.md') || file.startsWith('_')) continue; const path = join(appsDir, file); const content = await readFile(path, 'utf8').catch(() => null); if (content === null) continue; guides.push(parseGuide(file.replace(/\.md$/, ''), path, content)); } return guides; } /** 匹配用的应用身份。取自 `ComputerState.activeApp`。 */ export interface AppIdentity { /** macOS bundleId / Windows 可执行文件名 */ id?: string; /** 显示名 */ name?: string; } export type MatchedBy = 'bundleId' | 'processName' | 'displayName'; export interface GuideMatch { guide: AppGuide; matchedBy: MatchedBy; } /** * 匹配当前前台应用。**bundleId > 进程名 > 显示名**,并报告命中的是哪一级 —— * 靠显示名命中的置信度明显更低(多语言/改名会飘),值得让调用方知道。 */ export function matchGuide(guides: AppGuide[], app: AppIdentity | undefined): GuideMatch | null { if (!app) return null; const id = (app.id ?? '').toLowerCase(); const name = (app.name ?? '').toLowerCase(); const attempts: [keyof AppGuide, string, MatchedBy][] = [ ['bundleIds', id, 'bundleId'], ['processNames', id, 'processName'], ['processNames', name, 'processName'], ['displayNames', name, 'displayName'], ]; for (const [field, needle, label] of attempts) { if (!needle) continue; const guide = guides.find((g) => (g[field] as string[]).includes(needle)); if (guide) return { guide, matchedBy: label }; } return null; } // ============================================================ // 不可逆动作判定 // ============================================================ export interface IrreversibleAction { /** ComputerUse action 名,如 click / key */ command: string; /** key 动作的组合键 */ combo?: string; /** click 落点(**相对坐标 0–1000**) */ point?: { x: number; y: number }; /** 模型自报的意图 */ intent?: string; } export interface IrreversibleHit { entry: string; /** 引擎能独立验证(key/region),还是只能靠模型自报(intent) */ checkable: boolean; why: string; } /** * `apps/.md` 的 `irreversible:` 列表用**可检查的模式**声明,而不是动作名。 * * 原因:`click 500 500` 手里只有坐标,对不上「发送按钮」这种名字。 * 三种模式各自可检查性不同,如实分级: * * key:<组合键> 按下即触发(微信里 Enter 就是发送)—— **完全可检查** * region: 相对坐标矩形(发送按钮所在)—— 可检查,但坐标会随版本/窗口尺寸漂 * intent:<名称> 模型自报意图 —— **仅建议性**,模型不报就拦不住 * * ⚠️ 这一层的定位是「显著提高误触成本 + 留下审计记录」,**不是真拦截**。 * 真正的强制拦截在宿主的 toolGate 与人工介入通道。 */ export function matchIrreversible( guide: AppGuide | null, action: IrreversibleAction, ): IrreversibleHit | null { if (!guide || guide.irreversible.length === 0) return null; for (const entry of guide.irreversible) { const [kind, ...rest] = String(entry).split(':'); const value = rest.join(':').trim(); if (kind === 'key' && action.command === 'key') { if (normalizeCombo(value) === normalizeCombo(action.combo ?? '')) { return { entry, checkable: true, why: `按键 ${value} 在本应用中触发不可逆动作` }; } } if (kind === 'region' && action.point && CLICK_LIKE.has(action.command)) { const rect = parseRegion(value); if (rect && inRect(action.point, rect)) { return { entry, checkable: true, why: `点击落在不可逆区域 ${value}` }; } } if (kind === 'intent' && action.intent && value === action.intent) { return { entry, checkable: false, why: `自报的意图「${action.intent}」被声明为不可逆` }; } } return null; } /** 点击类动作集合。也被 `computeruse.ts` 的拒绝重放判据复用,避免两处各写一份。 */ export const CLICK_LIKE = new Set(['click', 'double_click', 'right_click', 'middle_click']); function normalizeCombo(combo: string): string { return String(combo) .toLowerCase() .split('+') .map((s) => s.trim()) .filter(Boolean) .sort() .join('+'); } function parseRegion(value: string): { x: number; y: number; width: number; height: number } | null { const nums = value.split(',').map((n) => Number(n.trim())); if (nums.length !== 4 || nums.some((n) => !Number.isFinite(n))) return null; return { x: nums[0]!, y: nums[1]!, width: nums[2]!, height: nums[3]! }; } function inRect( point: { x: number; y: number }, rect: { x: number; y: number; width: number; height: number }, ): boolean { return ( point.x >= rect.x && point.x < rect.x + rect.width && point.y >= rect.y && point.y < rect.y + rect.height ); } /** 人话渲染。未命中时**如实说明**并列出已有的指南,便于用户补全。 */ export function describeMatch( result: GuideMatch | null, guides: AppGuide[], app: AppIdentity | undefined, ): string { if (result) { const confidence = result.matchedBy === 'displayName' ? '(靠显示名命中,置信度较低:显示名会随系统语言/版本变化)' : ''; // ⚠️ 这里曾经写「**先 Read 它再操作**」。那是 skill 时代的话术,与现在的 // 「引擎在每次观测里直接注入摘要」直接冲突 —— 留着只会让模型白花一次 // Read 去看它刚刚已经读过的内容。 return [ `已匹配应用说明书:${result.guide.path}`, `摘要已随本次观测注入,不必再 Read。(匹配依据:${result.matchedBy}${confidence})`, ].join('\n'); } const known = guides.length > 0 ? guides.map((g) => g.name).join('、') : '(无)'; return [ `⚠️ 未找到「${app?.name ?? '当前应用'}」的操作指南(标识:${app?.id ?? '未知'})。`, `已有指南:${known}`, '', '你对这个应用一无所知,因此要**更频繁地确认**:每个动作后看回执,', '关键步骤前后各观测一次,不要连续盲操作。', '遇到值得记录的坑,告诉用户可以用 `/computeruse capture` 采一份草稿。', ].join('\n'); }