import * as vscode from "vscode"; import { readFileSync, existsSync, readdirSync, statSync, mkdirSync, writeFileSync } from "node:fs"; import { resolve, join, dirname } from "node:path"; import { homedir } from "node:os"; import { parsers, generateConfig, outputFileFor, detectDriftEntries, findMissingRules, generateReport, type Rule, } from "../../../src/index.js"; let panel: vscode.WebviewPanel | undefined; let outputChannel: vscode.OutputChannel; function findAgentFiles(root: string, agent: string): string[] { const parser = parsers[agent]; if (!parser) return []; const files: string[] = []; for (const pattern of parser.filePatterns) { if (pattern.includes("*")) { const parts = pattern.split("/"); const dirParts = parts.slice(0, -1); const filePattern = parts[parts.length - 1]; const dir = resolve(root, ...dirParts); if (existsSync(dir) && statSync(dir).isDirectory()) { const regex = new RegExp("^" + filePattern.replace(/\*/g, ".*") + "$"); for (const f of readdirSync(dir)) { if (regex.test(f)) files.push(join(dir, f)); } } } else { const filePath = resolve(root, pattern); if (existsSync(filePath)) files.push(filePath); } } return files; } function collectRules(root: string): Array<{ agent: string; rules: Rule[]; files: string[] }> { const results: Array<{ agent: string; rules: Rule[]; files: string[] }> = []; for (const [agentName, parser] of Object.entries(parsers)) { const files = findAgentFiles(root, agentName); if (files.length === 0) continue; const rules: Rule[] = []; for (const file of files) { rules.push(...parser.parse(readFileSync(file, "utf-8"), file)); } results.push({ agent: agentName, rules, files }); } return results; } function getWorkspaceRoot(): string | undefined { return vscode.workspace.workspaceFolders?.[0]?.uri.fsPath; } export function activate(context: vscode.ExtensionContext) { outputChannel = vscode.window.createOutputChannel("AgentLens"); context.subscriptions.push(outputChannel); // === Scan === context.subscriptions.push( vscode.commands.registerCommand("agentlens.scan", async () => { const root = getWorkspaceRoot(); if (!root) { vscode.window.showWarningMessage("AgentLens: 请先打开一个项目文件夹"); return; } const results = collectRules(root); outputChannel.clear(); outputChannel.appendLine(`扫描 ${root}`); outputChannel.appendLine(""); if (results.length === 0) { outputChannel.appendLine("未发现 Agent 配置。"); vscode.window.showInformationMessage("AgentLens: 未发现 Agent 配置"); return; } for (const r of results) { const cats = new Map(); for (const rule of r.rules) cats.set(rule.category, (cats.get(rule.category) ?? 0) + 1); const catStr = [...cats.entries()].map(([c, n]) => `${c}(${n})`).join(", "); outputChannel.appendLine(`✅ ${r.agent.toUpperCase()} — ${r.rules.length} 条规则 [${catStr}]`); for (const f of r.files) outputChannel.appendLine(` 📄 ${f.replace(root, ".")}`); } outputChannel.show(); vscode.window.showInformationMessage( `AgentLens: 发现 ${results.length} 个 Agent 配置,共 ${results.reduce((a, r) => a + r.rules.length, 0)} 条规则` ); updatePanelContent(root); }) ); // === Move (quick pick flow) === context.subscriptions.push( vscode.commands.registerCommand("agentlens.move", async () => { const root = getWorkspaceRoot(); if (!root) { vscode.window.showWarningMessage("AgentLens: 请先打开一个项目文件夹"); return; } const found = collectRules(root); if (found.length === 0) { vscode.window.showWarningMessage("AgentLens: 未发现任何 Agent 配置"); return; } const from = await vscode.window.showQuickPick( found.map((f) => f.agent), { placeHolder: "从哪个 Agent 迁移规则?" } ); if (!from) return; const allAgents = Object.keys(parsers); const to = await vscode.window.showQuickPick( allAgents.filter((a) => a !== from), { placeHolder: "迁移到哪个 Agent?" } ); if (!to) return; const sourceRules = found.find((f) => f.agent === from)?.rules ?? []; const content = generateConfig(sourceRules, to as any); const outPath = resolve(root, outputFileFor(to as any)); mkdirSync(dirname(outPath), { recursive: true }); writeFileSync(outPath, content, "utf-8"); vscode.window.showInformationMessage( `AgentLens: ${sourceRules.length} 条规则已迁移 ${from} → ${to}(${outPath.replace(root, ".")})` ); outputChannel.appendLine(`迁移完成: ${from} → ${to}, ${sourceRules.length} 条规则 → ${outPath}`); }) ); // === Drift === context.subscriptions.push( vscode.commands.registerCommand("agentlens.drift", async () => { const root = getWorkspaceRoot(); if (!root) { vscode.window.showWarningMessage("AgentLens: 请先打开一个项目文件夹"); return; } const found = collectRules(root); const allRules = found.flatMap((f) => f.rules); if (allRules.length === 0) { vscode.window.showInformationMessage("AgentLens: 没有可比较的规则"); return; } const drifts = detectDriftEntries(allRules); if (found.length >= 2) { const base = found[0]; for (let i = 1; i < found.length; i++) { drifts.push(...findMissingRules(base.rules, found[i].rules, base.agent as any, found[i].agent as any)); } } outputChannel.clear(); if (drifts.length === 0) { outputChannel.appendLine("✅ 未发现配置漂移"); vscode.window.showInformationMessage("AgentLens: 未发现配置漂移"); } else { outputChannel.appendLine(`⚠ 发现 ${drifts.length} 处漂移:`); for (const d of drifts) { outputChannel.appendLine(`[${d.type}] ${d.description}`); } vscode.window.showWarningMessage(`AgentLens: 发现 ${drifts.length} 处配置漂移`); } outputChannel.show(); updatePanelContent(root); }) ); // === Check current file === context.subscriptions.push( vscode.commands.registerCommand("agentlens.checkFile", async () => { const editor = vscode.window.activeTextEditor; if (!editor) { vscode.window.showWarningMessage("AgentLens: 没有打开的文件"); return; } const filePath = editor.document.uri.fsPath; const content = editor.document.getText(); const ext = filePath.split(".").pop()?.toLowerCase(); const langMap: Record = { ts: "typescript", tsx: "typescript", js: "javascript", jsx: "javascript", py: "python", go: "go", rs: "rust", java: "java", }; const report = generateReport([{ path: filePath, content, language: ext ? langMap[ext] : undefined }]); outputChannel.clear(); outputChannel.appendLine(`体检: ${filePath}`); outputChannel.appendLine(`🔴 ${report.summary.critical} critical 🟡 ${report.summary.warning} warning ⚪ ${report.summary.info} info`); outputChannel.appendLine(""); for (const f of report.findings) { outputChannel.appendLine(`[${f.severity}] ${f.file}:${f.line ?? "?"} — ${f.message}`); if (f.suggestion) outputChannel.appendLine(` 💡 ${f.suggestion}`); } outputChannel.show(); if (report.summary.critical > 0) { vscode.window.showErrorMessage(`AgentLens: ${report.summary.critical} 个严重问题!`); } else if (report.summary.warning > 0) { vscode.window.showWarningMessage(`AgentLens: ${report.summary.warning} 个警告`); } else { vscode.window.showInformationMessage("AgentLens: 体检通过 ✅"); } }) ); // === Check workspace changes === context.subscriptions.push( vscode.commands.registerCommand("agentlens.checkWorkspace", async () => { const root = getWorkspaceRoot(); if (!root) { vscode.window.showWarningMessage("AgentLens: 请先打开一个项目文件夹"); return; } const { execSync } = await import("node:child_process"); let files: string[] = []; try { files = execSync("git diff --name-only HEAD", { cwd: root, encoding: "utf-8" }) .trim() .split("\n") .filter(Boolean); } catch { vscode.window.showWarningMessage("AgentLens: 无法读取 git 变更"); return; } if (files.length === 0) { vscode.window.showInformationMessage("AgentLens: 没有未提交的变更"); return; } outputChannel.clear(); outputChannel.appendLine(`体检工作区变更 (${files.length} 个文件)`); let totalCritical = 0; let totalWarning = 0; for (const f of files) { const full = resolve(root, f); if (!existsSync(full)) continue; const ext = f.split(".").pop()?.toLowerCase(); const langMap: Record = { ts: "typescript", tsx: "typescript", js: "javascript", jsx: "javascript", py: "python", go: "go", rs: "rust", java: "java", }; const report = generateReport([{ path: f, content: readFileSync(full, "utf-8"), language: ext ? langMap[ext] : undefined }]); totalCritical += report.summary.critical; totalWarning += report.summary.warning; for (const finding of report.findings) { outputChannel.appendLine(`[${finding.severity}] ${finding.file}:${finding.line ?? "?"} — ${finding.message}`); } } outputChannel.show(); if (totalCritical > 0) { vscode.window.showErrorMessage(`AgentLens: ${totalCritical} 个严重问题!`); } else if (totalWarning > 0) { vscode.window.showWarningMessage(`AgentLens: ${totalWarning} 个警告`); } else { vscode.window.showInformationMessage("AgentLens: 变更体检通过 ✅"); } }) ); // === Open settings panel === context.subscriptions.push( vscode.commands.registerCommand("agentlens.openPanel", async () => { if (panel) { panel.reveal(); } else { panel = vscode.window.createWebviewPanel( "agentlens.panel", "AgentLens 设置", vscode.ViewColumn.One, { enableScripts: true } ); panel.onDidDispose(() => { panel = undefined; }); panel.webview.html = getPanelHtml(); // Wire the panel buttons to real commands — without this the buttons do nothing. panel.webview.onDidReceiveMessage(async (msg) => { switch (msg?.command) { case "scan": await vscode.commands.executeCommand("agentlens.scan"); break; case "move": await vscode.commands.executeCommand("agentlens.move"); break; case "drift": await vscode.commands.executeCommand("agentlens.drift"); break; case "check": await vscode.commands.executeCommand("agentlens.checkFile"); break; case "install": await vscode.commands.executeCommand("agentlens.installAll"); break; default: break; } }); const root = getWorkspaceRoot(); if (root) updatePanelContent(root); } }) ); // === One-click install into every detected AI app === context.subscriptions.push( vscode.commands.registerCommand("agentlens.installAll", async () => { const { execFile } = await import("node:child_process"); const { promisify } = await import("node:util"); const execFileAsync = promisify(execFile); const entry = (context as any).extensionPath ? resolve((context as any).extensionPath, "agentlens-cli", "index.js") : undefined; const cli = entry && existsSync(entry) ? entry : join(homedir(), "Downloads", "mimo", "agentlens", "dist", "cli", "index.js"); if (!existsSync(cli)) { vscode.window.showWarningMessage("AgentLens: 找不到安装器入口(需要先构建 agentlens 项目)"); return; } try { let nodeBin = process.env.AGENTLENS_NODE || ""; if (!nodeBin) { for (const c of ["/usr/local/bin/node", "/opt/homebrew/bin/node", "/usr/bin/node"]) { if (existsSync(c)) { nodeBin = c; break; } } } if (!nodeBin) nodeBin = "node"; const { stdout, stderr } = await execFileAsync(nodeBin, [cli, "install", "--target", "all"], { timeout: 120_000 }); outputChannel.clear(); outputChannel.appendLine(stdout || ""); if (stderr) outputChannel.appendLine(stderr); outputChannel.show(); vscode.window.showInformationMessage("AgentLens: 已接入所有检测到的 AI 工具(重启对应 App 生效)"); } catch (err: any) { vscode.window.showErrorMessage(`AgentLens 接入失败: ${err?.message ?? err}`); } }) ); // === Auto check on save (if enabled) === context.subscriptions.push( vscode.workspace.onDidSaveTextDocument(async (doc) => { const config = vscode.workspace.getConfiguration("agentlens"); if (config.get("autoCheckOnSave")) { await vscode.commands.executeCommand("agentlens.checkFile"); } }) ); outputChannel.appendLine("AgentLens 已激活。命令面板输入 'AgentLens' 查看所有命令。"); } async function updatePanelContent(root: string) { if (!panel) return; const results = collectRules(root); panel.webview.postMessage({ type: "scanResult", results: results.map((r) => ({ agent: r.agent, ruleCount: r.rules.length, files: r.files.map((f) => f.replace(root, ".")), })) }); } function getPanelHtml(): string { return `

🔍 AgentLens

AI 编程 Agent 规则迁移 + 代码体检

点击「扫描配置」开始

`; } export function deactivate() {}