File size: 11,167 Bytes
7bedc79
2b46b80
7bedc79
2b46b80
 
7bedc79
2b46b80
 
 
 
 
7bedc79
 
 
0fc6e34
7bedc79
 
 
2b46b80
 
031fd6d
0fc6e34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7bedc79
cd52889
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2b46b80
 
7bedc79
 
 
2b46b80
7bedc79
cd52889
7bedc79
 
 
 
 
 
2b46b80
7bedc79
 
 
2b46b80
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12880e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36277c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0fc6e34
 
 
 
 
 
 
 
 
 
 
 
30b24ad
 
 
 
 
 
 
 
 
 
 
 
 
2b46b80
12880e4
2b46b80
 
 
 
 
 
 
 
 
7bedc79
 
2b46b80
7bedc79
 
2b46b80
0fc6e34
2b46b80
 
 
 
 
 
 
7bedc79
2b46b80
7bedc79
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2b46b80
7bedc79
2b46b80
 
7bedc79
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2b46b80
7bedc79
2b46b80
7bedc79
2b46b80
7bedc79
 
 
 
 
 
 
 
 
 
 
 
 
2b46b80
7bedc79
2b46b80
 
7bedc79
 
 
 
 
 
 
 
 
 
 
 
 
 
2b46b80
7bedc79
2b46b80
7bedc79
2b46b80
7bedc79
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
/**
 * @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");
}