/** * @local/agentlens — Host half. * * Registers four model-facing tools plus two local HTTP routes that back the * client UI (composer chip + Settings panel): * * tools: agentlens_scan / agentlens_move / agentlens_drift / agentlens_check * routes: GET /agentlens/scan?path=… * POST /agentlens/migrate {path, from, to} * * Everything shells out to the AgentLens CLI on this machine; nothing leaves it. */ import { execFile } from "node:child_process"; import { promisify } from "node:util"; import { existsSync, accessSync, constants, readFileSync } from "node:fs"; const execFileAsync = promisify(execFile); export const inject = ["tools", "webServer"]; const DEFAULT_ENTRY = '/Users/apple/agentlens/dist/cli/index.js'; const HOME = process.env.HOME || "/Users/apple"; /** * Read recent workspace paths from DSH's own storage so the panel can default * to a real project instead of the profile directory (the host's cwd). */ function recentWorkspaces() { const paths = []; try { const raw = readFileSync(joinHome(".dsh", "storages", "workspace.json"), "utf8"); const data = JSON.parse(raw); const workspaces = data?.tables?.workspaces ?? {}; for (const entry of Object.values(workspaces)) { const p = entry?.path; if (typeof p === "string" && p && !paths.includes(p)) paths.push(p); } } catch { // storage missing or not JSON — fall through } return paths; } function joinHome(...parts) { return [HOME, ...parts].join("/"); } /** Pick a sensible default project root: first DSH workspace, else home. */ function defaultProjectPath() { const workspaces = recentWorkspaces(); return workspaces[0] || HOME; } /** * Resolve a real Node.js binary. Inside the Electron host `process.execPath` * points at the app bundle, which cannot run a CLI script — prefer PATH and * well-known install locations. */ function resolveNodeBinary() { if (process.env.AGENTLENS_NODE) return process.env.AGENTLENS_NODE; for (const candidate of ["/usr/local/bin/node", "/opt/homebrew/bin/node", "/usr/bin/node"]) { try { accessSync(candidate, constants.X_OK); return candidate; } catch { // try next } } return "node"; } function resolveEntry(config) { return config?.entry || process.env.AGENTLENS_ENTRY || DEFAULT_ENTRY; } /** Run the agentlens CLI and return its combined output. */ async function runAgentlens(entry, args, cwd) { try { const { stdout, stderr } = await execFileAsync(resolveNodeBinary(), [entry, ...args], { cwd, timeout: 120_000, maxBuffer: 4 * 1024 * 1024, }); return (stdout || "") + (stderr ? `\n${stderr}` : ""); } catch (err) { throw new Error(`AgentLens 执行失败: ${err?.message ?? String(err)}`); } } /** Shared output contract: tools return { text } and render it as text content. */ const TEXT_OUTPUT = { schema: { type: "object", properties: { text: { type: "string" } }, required: ["text"], additionalProperties: false }, render: (_args, value) => text(value?.text ?? ""), }; /** Wrap a runAgentlens result into the { text } output shape. */ async function runTool(entry, args, cwd) { return { text: await runAgentlens(entry, args, cwd) }; } /** Exact-path route that never throws past registration. */ function mountRoutes(server, entry, fallbackCwd) { const json = (res, status, body) => { res.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" }); res.end(JSON.stringify(body)); }; const scanRoute = { kind: "exact", path: "/agentlens/scan", async handler(req, res) { try { const url = new URL(req.url ?? "/agentlens/scan", "http://127.0.0.1"); const path = url.searchParams.get("path") || fallbackCwd; const text = await runAgentlens(entry, ["scan", "--path", path], path); json(res, 200, { ok: true, text }); } catch (error) { json(res, 500, { ok: false, error: String((error && error.message) || error) }); } }, }; const migrateRoute = { kind: "exact", path: "/agentlens/migrate", async handler(req, res) { try { const body = await new Promise((resolve) => { let raw = ""; req.on("data", (chunk) => { raw += chunk; }); req.on("end", () => resolve(raw)); }); const payload = body ? JSON.parse(body) : {}; const path = String(payload.path || fallbackCwd); const from = String(payload.from || ""); const to = String(payload.to || ""); if (!from || !to) { json(res, 400, { ok: false, error: "缺少 from / to 参数" }); return; } const text = await runAgentlens(entry, ["move", "--from", from, "--to", to, "--path", path], path); json(res, 200, { ok: true, text }); } catch (error) { json(res, 500, { ok: false, error: String((error && error.message) || error) }); } }, }; const importRoute = { kind: "exact", path: "/agentlens/import", async handler(req, res) { try { const body = await new Promise((resolve) => { let raw = ""; req.on("data", (chunk) => { raw += chunk; }); req.on("end", () => resolve(raw)); }); const payload = body ? JSON.parse(body) : {}; const target = String(payload.target || "codex"); const args = ["import", "--from", "dsh", "--to", target]; if (payload.out) args.push("--out", String(payload.out)); const text = await runAgentlens(entry, args, process.cwd()); json(res, 200, { ok: true, text }); } catch (error) { json(res, 500, { ok: false, error: String((error && error.message) || error) }); } }, }; const exportRoute = { kind: "exact", path: "/agentlens/export", async handler(req, res) { try { const body = await new Promise((resolve) => { let raw = ""; req.on("data", (chunk) => { raw += chunk; }); req.on("end", () => resolve(raw)); }); const payload = body ? JSON.parse(body) : {}; const out = String(payload.out || joinHome("dsh-export")); const text = await runAgentlens(entry, ["export", "--from", "dsh", "--out", out], process.cwd()); json(res, 200, { ok: true, text }); } catch (error) { json(res, 500, { ok: false, error: String((error && error.message) || error) }); } }, }; const workspacesRoute = { kind: "exact", path: "/agentlens/workspaces", async handler(req, res) { try { json(res, 200, { ok: true, workspaces: recentWorkspaces(), fallback: fallbackCwd }); } catch (error) { json(res, 500, { ok: false, error: String((error && error.message) || error) }); } }, }; const installRoute = { kind: "exact", path: "/agentlens/install", async handler(req, res) { try { const text = await runAgentlens(entry, ["install", "--target", "all"], process.cwd()); json(res, 200, { ok: true, text }); } catch (error) { json(res, 500, { ok: false, error: String((error && error.message) || error) }); } }, }; const disposers = []; for (const route of [scanRoute, migrateRoute, installRoute, workspacesRoute, exportRoute, importRoute]) { try { disposers.push(server.register(route)); } catch (error) { console.warn?.("agentlens: route %s was not registered: %s", route.path, error?.message ?? error); } } return () => disposers.forEach((dispose) => dispose?.()); } /** * @param ctx - owning Host context. * @param config - { entry?: string } optional CLI entry override. */ export function apply(ctx, config = {}) { const entry = resolveEntry(config); const fallbackCwd = defaultProjectPath(); // --- Local HTTP routes for the client UI --- ctx.effect(() => { const server = ctx.get("webServer"); if (!server) return; return mountRoutes(server, entry, fallbackCwd); }, "agentlens: local routes"); // --- Model-facing tools --- ctx.effect(() => { const tools = ctx.get("tools"); if (tools === void 0) return; const disposers = [ tools.register({ name: "agentlens_scan", description: "Scan the current project for AI agent config files (CLAUDE.md, .cursor/rules, AGENTS.md, .windsurfrules, copilot-instructions) and summarize the rules found. Read-only.", parameters: { type: "object", properties: { path: { type: "string", description: "Project root path (defaults to cwd)." }, }, additionalProperties: false, }, output: TEXT_OUTPUT, async execute(args) { const path = typeof args?.path === "string" ? args.path : fallbackCwd; return runTool(entry, ["scan", "--path", path], path); }, }), tools.register({ name: "agentlens_move", description: "Migrate AI agent rules from one format to another (e.g. claude → cursor, cursor → codex). Parses into a unified model and re-generates the target format. Writes the target config file.", parameters: { type: "object", properties: { from: { type: "string", description: "Source agent: claude | cursor | codex | windsurf | copilot" }, to: { type: "string", description: "Target agent: claude | cursor | codex | windsurf | copilot" }, path: { type: "string", description: "Project root path (defaults to cwd)." }, }, required: ["from", "to"], additionalProperties: false, }, output: TEXT_OUTPUT, async execute(args) { const path = typeof args?.path === "string" ? args.path : fallbackCwd; const cmd = ["move", "--from", String(args.from), "--to", String(args.to), "--path", path]; return runTool(entry, cmd, path); }, }), tools.register({ name: "agentlens_drift", description: "Detect config drift across agent rule files: similar rules with different wording, and rule categories present in one agent but missing in another. Read-only.", parameters: { type: "object", properties: { path: { type: "string", description: "Project root path (defaults to cwd)." }, }, additionalProperties: false, }, output: TEXT_OUTPUT, async execute(args) { const path = typeof args?.path === "string" ? args.path : fallbackCwd; return runTool(entry, ["drift", "--path", path], path); }, }), tools.register({ name: "agentlens_check", description: "Adversarial code QA: check a file or a git diff range for security issues (injection, hardcoded secrets, XSS), correctness bugs (empty catch, loose null comparison), style problems and performance smells. Read-only.", parameters: { type: "object", properties: { target: { type: "string", description: "File path or git diff range (e.g. HEAD~1..HEAD). Defaults to HEAD~1..HEAD." }, path: { type: "string", description: "Project root path (defaults to cwd)." }, }, additionalProperties: false, }, output: TEXT_OUTPUT, async execute(args) { const path = typeof args?.path === "string" ? args.path : fallbackCwd; const target = typeof args?.target === "string" ? args.target : "HEAD~1..HEAD"; return runTool(entry, ["check", target, "--path", path], path); }, }), ]; return () => { for (const dispose of disposers) { try { dispose?.(); } catch { // best-effort unregister } } }; }, "agentlens: tools"); }