/** * ============================================================ * diagnostics.ts —— 给宿主/插件的 Computer Use 只读门面 * ------------------------------------------------------------ * 桌面操作的**执行**在 `computeruse.ts`(可信内核工具),**知识与命令面**在 * `plugins/computer_use/`。插件需要的只有三类事:看一眼状态、读诊断、把一次 * 观测沉淀成说明书草稿。本模块就是这三类事的全部出口。 * * ★ 为什么不直接把 `computerUseService` 交给插件(此前就是这么做的): * 那个对象的 `request()` 能派发 `click` / `type` / `file_drop`。一个「只做 * 诊断与知识管理」的插件不该拿得到操作鼠标键盘的能力,而 `plugin-sdk.ts` * 当时的注释恰恰宣称「只开放这几件事」——注释与代码不一致时改代码。 * * ★ 为什么写盘(`writeManualDraft`)也在这里而不是插件里:它需要用户确认 + * 原子写。若留给插件,插件就得直接 import `askBridge` 与文件 API —— * 刚收窄的 SDK 会立刻从别的路径重新变宽。**有副作用的那一步由内核持有**, * 插件只负责编排与呈现。 * ============================================================ */ import { randomUUID } from 'node:crypto'; import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'; import { existsSync } from 'node:fs'; import { dirname, join } from 'node:path'; import { getWorkingDir } from '../../bootstrap/workingDir.js'; import { hasAskHandler, requestUserChoice } from '../../askBridge.js'; import { anonymousOwnerId, computerUseService, ComputerUseService, computerUseStateDir, findComputerUseHelper } from './computerUseService.js'; import type { ComputerState, ComputerUseResponse, ComputerUseRunContext } from './protocol.js'; import { WORKSPACE_MANUAL_DIR, loadAllAppManuals, matchGuide, type AppGuide } from './vision/appGuide.js'; import { appendFieldNotes, markFlowVerified } from './manualSchema.js'; import { deriveFocusSnapshot } from './vision/focus.js'; /** * 诊断用的运行身份:**只有 observe 能力**。 * * 不是靠调用方自觉传对参数——这条命令面在结构上就派发不出写类动作,因为它 * 手里的 run 从来没拿到过 interact/type/submit。 */ function diagnosticRun(): ComputerUseRunContext { return { ownerId: anonymousOwnerId(), conversationKey: 'diagnostics', runId: randomUUID(), surface: 'cli', allowedApps: [], grantId: randomUUID(), capabilities: ['observe'], // 观测档下没有任何不可逆动作可做,也就不该存在一条「问人要授权」的路径。 supervised: false, }; } export interface ManualDraft { /** 建议的文件名(不含 .md) */ name: string; markdown: string; /** 采集过程中值得说出来的事(权限不足、已有同名说明书…) */ warnings: string[]; } export type WriteDraftResult = | { ok: true; path: string } | { ok: false; error: string }; export const computerUseDiagnostics = { platformSupported(): boolean { return ComputerUseService.platformSupported(); }, helperPath(): string | null { return findComputerUseHelper(); }, stateDir(): string { return computerUseStateDir(); }, /** 说明书落盘目录(工作区,可写)。 */ manualDir(): string { return join(getWorkingDir(), WORKSPACE_MANUAL_DIR); }, status(signal?: AbortSignal): Promise { return computerUseService.request(diagnosticRun(), { action: 'status' }, signal); }, permissions(signal?: AbortSignal): Promise { return computerUseService.request(diagnosticRun(), { action: 'permissions' }, signal); }, observe(signal?: AbortSignal): Promise { return computerUseService.request(diagnosticRun(), { action: 'observe' }, signal, { internalObserve: true }); }, captureDraft(name: string | undefined, signal?: AbortSignal): Promise { return captureDraft(name, signal); }, writeManualDraft(draft: ManualDraft, signal?: AbortSignal): Promise { return writeManualDraft(draft, signal); }, /** 取一份说明书的**原始 markdown**(验收回写要做行级编辑,不能只拿解析结果)。 */ readManualSource(name: string): Promise { return readManualSource(name); }, /** 把验收结果写回工作区那份说明书。 */ saveVerification(input: SaveVerificationInput, signal?: AbortSignal): Promise { return saveVerification(input, signal); }, }; export interface ManualSource { name: string; /** 原始文件路径(可能在只读的包内目录)。 */ path: string; markdown: string; guide: AppGuide; /** 这份说明书是不是已经在工作区(可写)。 */ inWorkspace: boolean; } export interface SaveVerificationInput { source: ManualSource; /** 全部步骤通过、可以翻 `verified: true` 的 flow。 */ verifiedFlows: string[]; /** 追加到 `## 实测记录` 的行。 */ notes: string[]; } /** * 读一份说明书的原文。 * * 为什么要原文而不是 `AppGuide`:验收要把 `verified: false` 翻成 true,而 * 「parse → 改 → 重新序列化」会抹掉 frontmatter 里的全部注释。那些注释是 * 说明书里最难重建的部分,所以回写走行级编辑(`markFlowVerified`), * 前提是手里有原始字节。 */ async function readManualSource(name: string): Promise { const { guides, rejected } = await loadAllAppManuals(); const guide = guides.find((item) => item.name === name) ?? rejected.find((item) => item.guide.name === name)?.guide; if (!guide) return `没有名为「${name}」的说明书。用 /computeruse apps 看清单。`; const markdown = await readFile(guide.path, 'utf8').catch(() => null); if (markdown === null) return `读不到 ${guide.path}。`; return { name, path: guide.path, markdown, guide, inWorkspace: guide.path.startsWith(computerUseDiagnostics.manualDir()), }; } /** * 写回验收结果。 * * ★ **一律写工作区那份**,哪怕原文在包内目录。包内目录在 npm / 绿色版安装后 * 通常只读,而且那是我们随包发布的知识,不该被某台机器的一次验收改掉。 * 工作区那份优先级更高(见 appGuide.ts::appManualProviders),所以复制过去 * 再改,效果就是「这台机器上的实测结论覆盖随包默认」。 */ async function saveVerification( input: SaveVerificationInput, signal?: AbortSignal, ): Promise { const dir = computerUseDiagnostics.manualDir(); const target = join(dir, `${input.source.name}.md`); let markdown = input.source.markdown; const flipped: string[] = []; const unflipped: string[] = []; for (const flowId of input.verifiedFlows) { const next = markFlowVerified(markdown, flowId); if (next) { markdown = next; flipped.push(flowId); } else { unflipped.push(flowId); } } markdown = appendFieldNotes(markdown, input.notes); if (!hasAskHandler()) { return { ok: false, error: '当前宿主没有可用的确认界面,未写盘。' }; } let approved = false; try { const answers = await requestUserChoice([{ header: '写入实测结论', question: `把这次验收的结论写到 ${target}?\n` + (input.source.inWorkspace ? '' : `(原文在 ${input.source.path},会复制到工作区再改,不动包内文件。)\n`) + `翻为已验证的流程:${flipped.join('、') || '(无)'}\n` + (unflipped.length > 0 ? `⚠️ 这些找不到可翻的 verified 行,只会记进实测记录:${unflipped.join('、')}\n` : '') + `新增实测记录 ${input.notes.length} 行。`, options: [ { label: '取消 (推荐)', description: '不写盘。结论已打印,你可以自己整理。' }, { label: '写入', description: `更新 ${target}` }, ], }], signal); approved = answers[0]?.selected.some((label) => label.startsWith('写入')) === true; } catch { return { ok: false, error: '确认过程被中断,未写盘。' }; } if (!approved) return { ok: false, error: '你取消了写入。' }; try { await mkdir(dir, { recursive: true }); const temp = join(dir, `.${input.source.name}.${process.pid}.${randomUUID()}.tmp`); await writeFile(temp, markdown, { mode: 0o600 }); await rename(temp, target); return { ok: true, path: target }; } catch (error) { return { ok: false, error: `写入失败:${error instanceof Error ? error.message : String(error)}`, }; } } // ============================================================ // 草稿采集 // ============================================================ /** AX 树里值得写进说明书的控件候选上限。再多就不是「关键控件」了。 */ const MAX_CONTROL_CANDIDATES = 15; const MAX_WINDOW_LINES = 10; interface AxCandidate { role: string; names: string[]; focused: boolean; } /** * 从一次观测生成说明书草稿。 * * ★ **草稿里不出现任何 rect。** 窗口位置与控件 bounds 是「这一秒屏幕长什么样」, * 不是「这个应用怎么用」——窗口能拉伸、能全屏、能换显示器。把一次观测的坐标 * 写成 schema 里的稳定事实,等于制造一批看着像已验证、实际下一次就失准的数据。 * 稳定的是 **AX role + name 锚点**,所以草稿只出这个。 * * ★ `layout` 与 `flows` 留空:它们要靠实机与使用逐步沉淀,编不出来。 */ async function captureDraft( requestedName: string | undefined, signal?: AbortSignal, ): Promise { if (!ComputerUseService.platformSupported()) { return `当前平台是 ${process.platform},Computer Use 只支持 macOS,无法采集。`; } const response = await computerUseService.request( diagnosticRun(), { action: 'observe' }, signal, { internalObserve: true }, ); if (!response.ok || !response.state) { return `采集失败:${response.error?.code ?? 'failed'}: ${response.error?.message ?? '未知错误'}`; } const state = response.state; const app = state.activeApp; if (!app?.id && !app?.name) { return '拿不到前台应用身份,无法采集。先把目标应用切到前台再试。'; } const warnings: string[] = []; const name = sanitizeName(requestedName ?? app?.id?.split('.').pop() ?? app?.name ?? 'unknown'); const { guides } = await loadAllAppManuals(); const existing = matchGuide(guides, { id: app?.id, name: app?.name }); if (existing) { warnings.push( `已有说明书「${existing.guide.name}」认领这个应用(${existing.guide.path})——` + '草稿仅供对照,不要直接盖掉已沉淀的内容。', ); } if (state.accessibility?.truncated === true) { warnings.push( '无障碍树不完整(权限不足或元素过多),控件候选会很少甚至为空。' + '自绘界面(Electron / Qt / 跨端客户端)本来就是这样——那不是采集失败。', ); } const candidates = collectAxCandidates(state); const focus = deriveFocusSnapshot(state); return { name, markdown: renderDraft({ name, state, candidates, focus }), warnings }; } function sanitizeName(raw: string): string { const cleaned = raw.trim().toLowerCase().replace(/[^a-z0-9._-]+/g, '-').replace(/^-+|-+$/g, ''); return cleaned || 'unknown'; } function collectAxCandidates(state: ComputerState): AxCandidate[] { const byRole = new Map(); const walk = (node: { role?: string; name?: string; focused?: boolean; children?: unknown[] } | undefined): void => { if (!node) return; const role = node.role?.trim(); if (role) { const entry = byRole.get(role) ?? { role, names: [], focused: false }; const label = node.name?.trim(); if (label && !entry.names.includes(label) && entry.names.length < 5) entry.names.push(label); if (node.focused === true) entry.focused = true; byRole.set(role, entry); } for (const child of (node.children ?? []) as typeof node[]) walk(child); }; walk(state.accessibility?.root as never); return [...byRole.values()].slice(0, MAX_CONTROL_CANDIDATES); } function renderDraft(input: { name: string; state: ComputerState; candidates: AxCandidate[]; focus: ReturnType; }): string { const app = input.state.activeApp; const today = new Date().toISOString().slice(0, 10); const quoted = (value: string): string => JSON.stringify(value); const controls = input.candidates.length > 0 ? input.candidates.map((candidate) => [ ` - id: ${sanitizeName(candidate.role)}`, ` ax: { role: ${candidate.role}${candidate.names.length > 0 ? `, name: [${candidate.names.map(quoted).join(', ')}]` : ''} }`, ` desc: 采集自实机 AX 树${candidate.focused ? '(采集时持有焦点)' : ''}`, ' verified: false', ].join('\n')).join('\n') : ''; const windows = input.state.windows.slice(0, MAX_WINDOW_LINES) .map((window) => `- ${window.title ?? '(无标题)'}`); return [ '---', 'schemaVersion: 2', 'guideVersion: 1', 'status: draft', `platforms: [${process.platform === 'darwin' ? 'macOS' : process.platform}]`, 'match:', ` bundleId: [${app?.id ? quoted(app.id) : ''}]`, ` processName: [${app?.name ? quoted(app.name) : ''}]`, ` displayName: [${app?.name ? quoted(app.name) : ''}]`, '', '# 不可逆动作:**必须人工补全**。采集看不出「哪个动作收不回来」——', '# 那是产品语义,不是屏幕上的像素。留空等于这个应用没有任何不可逆防护。', 'irreversible: []', '', '# 界面分区留空:一次观测的窗口位置不是稳定的应用知识(窗口能拉伸、能全屏)。', 'layout: []', '', controls ? 'controls:' : 'controls: []', ...(controls ? [controls] : []), '', '# 典型流程留空:靠实机与使用逐步沉淀,采集编不出来。', 'flows: {}', '', 'verification:', ` environment: ${process.platform} · 采集于 ${today}(应用版本未知)`, ` verifiedAt: ${today}`, ' verifiedItems: [identity]', ' unverifiedItems: [layout, controls, flows]', '---', '', `# ${input.name} App Guide(自动采集草稿)`, '', '> 本文由 `/computeruse capture` 从**一次真实观测**生成。身份是实测的;', '> 控件候选来自当时的 AX 树,**未经验证**;分区与流程需要人来写。', '', '## 观测候选', '', `- 前台应用:${app?.name ?? '未知'}(${app?.id ?? '无标识'})`, `- 无障碍树:${input.state.accessibility ? (input.state.accessibility.truncated ? '不完整' : '可用') : '无'}`, `- 焦点:${input.focus ? `${input.focus.role ?? '未知控件'}(L${input.focus.level})` : '不可用'}`, '', '### 当时的窗口', '', ...(windows.length > 0 ? windows : ['- (没有可见窗口)']), '', '## 实测记录', '', '> 说明书与实况不符时,把**观察到的事实**追加到这里,一条一行,带日期与版本。', '> 只写观察到的,不写推测。', '', '- (暂无)', '', ].join('\n'); } // ============================================================ // 受控写盘 // ============================================================ /** * 把草稿写进工作区说明书目录。 * * 三条边界: * ① **必须有人确认** —— 无 ask handler 就不写。这是往用户项目里放文件。 * ② **不覆盖** —— 已存在就拒绝,让用户自己合并。自动合并两份说明书是赌博。 * ③ **原子写** —— 同目录 temp + rename,避免半截文件被当成合法说明书加载。 */ async function writeManualDraft( draft: ManualDraft, signal?: AbortSignal, ): Promise { const dir = computerUseDiagnostics.manualDir(); const target = join(dir, `${draft.name}.md`); if (existsSync(target)) { return { ok: false, error: `${target} 已存在。不自动覆盖——请自己对照合并,或换一个名字重跑。`, }; } if (!hasAskHandler()) { return { ok: false, error: '当前宿主没有可用的确认界面,未写盘。草稿见上方输出。' }; } let approved = false; try { const answers = await requestUserChoice([{ header: '写入说明书', question: `把采集到的草稿写到 ${target}?\n` + '它是**未验证**的起点,不是成品;写入后请自己核对并补全不可逆动作清单。', options: [ { label: '取消 (推荐)', description: '不写盘。草稿已经打印出来,你可以自己保存。' }, { label: '写入', description: `在 ${dir} 下新建 ${draft.name}.md` }, ], }], signal); approved = answers[0]?.selected.some((label) => label.startsWith('写入')) === true; } catch { return { ok: false, error: '确认过程被中断,未写盘。' }; } if (!approved) return { ok: false, error: '你取消了写入。' }; try { await mkdir(dir, { recursive: true }); const temp = join(dirname(target), `.${draft.name}.${process.pid}.${randomUUID()}.tmp`); await writeFile(temp, draft.markdown, { mode: 0o600 }); await rename(temp, target); return { ok: true, path: target }; } catch (error) { // 只读目录、磁盘满都会走到这里。报出来,不抛异常——采集本身是成功的。 return { ok: false, error: `写入失败:${error instanceof Error ? error.message : String(error)}`, }; } }