File size: 7,680 Bytes
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
import { readFileSync, writeFileSync, existsSync, mkdirSync } from "node:fs";
import { resolve, dirname, join } from "node:path";
import { homedir } from "node:os";

/**
 * One-click installer: detects installed AI agents on this machine and writes
 * the AgentLens MCP config into each one, so its tools appear directly in
 * their settings/tool lists after a restart.
 *
 * Supported agents:
 *   claude    — Claude Code / Claude Desktop (~/.claude/settings.json, mcpServers)
 *   cursor    — Cursor (.cursor/mcp.json, mcpServers)
 *   codex     — Codex / generic MCP (.mcp.json, mcpServers)
 *   zcode     — ZCode (~/.zcode/mcp.json, mcpServers)
 *   workbuddy — WorkBuddy (~/.workbuddy/mcp.json, mcpServers)
 *   mimo      — MiMo Desktop (~/.config/mimocode/mimocode.jsonc, mcp key)
 */

interface Detection {
  key: string;
  label: string;
  configPath: string;
  detectDirs: string[];
  format: "mcpServers" | "mimocode";
  /** Where the AgentLens skill (SKILL.md) is installed, if the app supports skills. */
  skillsDir?: string;
}

export function detectAgents(): Detection[] {
  const home = homedir();
  const cwd = process.cwd();
  return [
    {
      key: "claude",
      label: "Claude Code / Claude Desktop",
      configPath: join(home, ".claude", "settings.json"),
      detectDirs: [join(home, ".claude")],
      format: "mcpServers",
      skillsDir: join(home, ".claude", "skills"),
    },
    {
      key: "cursor",
      label: "Cursor",
      configPath: join(cwd, ".cursor", "mcp.json"),
      detectDirs: [join(home, "Library", "Application Support", "Cursor"), join(home, ".cursor")],
      format: "mcpServers",
    },
    {
      key: "codex",
      label: "Codex / 通用 MCP 客户端",
      configPath: join(cwd, ".mcp.json"),
      detectDirs: [cwd],
      format: "mcpServers",
      skillsDir: join(home, ".codex", "skills"),
    },
    {
      key: "zcode",
      label: "ZCode",
      configPath: join(home, ".zcode", "mcp.json"),
      detectDirs: [join(home, ".zcode")],
      format: "mcpServers",
      skillsDir: join(home, ".zcode", "skills"),
    },
    {
      key: "workbuddy",
      label: "WorkBuddy",
      configPath: join(home, ".workbuddy", "mcp.json"),
      detectDirs: [join(home, ".workbuddy"), join(home, ".workbuddy-ai")],
      format: "mcpServers",
      skillsDir: join(home, ".workbuddy", "skills"),
    },
    {
      key: "mimo",
      label: "MiMo Desktop",
      configPath: join(home, ".config", "mimocode", "mimocode.jsonc"),
      detectDirs: [join(home, ".config", "mimocode"), join(home, "Library", "Application Support", "Xiaomi MiMo")],
      format: "mimocode",
      skillsDir: join(home, ".agents", "skills"),
    },
  ];
}

/** Resolve the agentlens entry command: local dist if available, else npx. */
export function resolveEntry(): { command: string; args: string[] } {
  // When running from a local checkout, prefer the built CLI (agentlens may not
  // be published to npm yet).
  const here = dirname(new URL(import.meta.url).pathname);
  const localDist = resolve(here, "../../../dist/cli/index.js");
  if (existsSync(localDist)) {
    return { command: process.execPath, args: [localDist, "mcp"] };
  }
  return { command: "npx", args: ["-y", "agentlens", "mcp"] };
}

function writeMcpServersConfig(configPath: string, serverName = "agentlens"): void {
  let config: Record<string, unknown> = {};
  if (existsSync(configPath)) {
    try {
      config = JSON.parse(readFileSync(configPath, "utf-8"));
    } catch {
      // invalid JSON — leave the file untouched and report
      throw new Error(`无法解析 ${configPath}(不是有效 JSON),请手动添加配置`);
    }
  }
  const mcpServers = (config.mcpServers as Record<string, unknown>) ?? {};
  const entry = resolveEntry();
  mcpServers[serverName] = {
    command: entry.command,
    args: entry.args,
  };
  config.mcpServers = mcpServers;
  mkdirSync(dirname(configPath), { recursive: true });
  writeFileSync(configPath, JSON.stringify(config, null, 2) + "\n", "utf-8");
}

function writeMimocodeConfig(configPath: string, serverName = "agentlens"): void {
  let config: Record<string, unknown> = {};
  if (existsSync(configPath)) {
    try {
      config = JSON.parse(readFileSync(configPath, "utf-8"));
    } catch {
      throw new Error(`无法解析 ${configPath},请手动添加 mcp 配置`);
    }
  }
  const mcp = (config.mcp as Record<string, unknown>) ?? {};
  const entry = resolveEntry();
  mcp[serverName] = {
    type: "local",
    command: [entry.command, ...entry.args],
    enabled: true,
  };
  config.mcp = mcp;
  // Write as JSON (jsonc accepts plain JSON — comments would be lost, so back up first)
  if (existsSync(configPath)) {
    const backup = configPath + ".bak-agentlens";
    if (!existsSync(backup)) {
      writeFileSync(backup, readFileSync(configPath, "utf-8"));
    }
  }
  mkdirSync(dirname(configPath), { recursive: true });
  writeFileSync(configPath, JSON.stringify(config, null, 2) + "\n", "utf-8");
}

/** Locate the bundled SKILL.md (repo ext/skill or installed copy). */
function bundledSkillPath(): string | undefined {
  const here = dirname(new URL(import.meta.url).pathname);
  const candidates = [
    resolve(here, "../../../ext/skill/SKILL.md"),
    resolve(here, "../../../../ext/skill/SKILL.md"),
  ];
  for (const p of candidates) {
    if (existsSync(p)) return p;
  }
  return undefined;
}

/** Install the AgentLens skill into an app's skills root. */
function installSkill(d: Detection): string | undefined {
  if (!d.skillsDir) return undefined;
  const src = bundledSkillPath();
  if (!src) return undefined;
  const dest = join(d.skillsDir, "agentlens", "SKILL.md");
  mkdirSync(dirname(dest), { recursive: true });
  writeFileSync(dest, readFileSync(src, "utf-8"), "utf-8");
  return dest;
}

export async function installTo(target: string): Promise<void> {
  console.log("AgentLens 安装器\n");

  const detections = detectAgents();

  const installOne = (d: Detection): boolean => {
    try {
      if (d.format === "mimocode") {
        writeMimocodeConfig(d.configPath);
      } else {
        writeMcpServersConfig(d.configPath);
      }
      const skillPath = installSkill(d);
      console.log(`  ✅ ${d.label} → ${d.configPath}${skillPath ? ` (+skill: ${skillPath})` : ""}`);
      return true;
    } catch (err: any) {
      console.log(`  ❌ ${d.label}: ${err.message}`);
      return false;
    }
  };

  if (target !== "all") {
    const one = detections.find((d) => d.key === target);
    if (!one) {
      console.log(`未知目标: ${target}`);
      console.log(`支持: ${detections.map((d) => d.key).join(", ")}, all`);
      return;
    }
    installOne(one);
    console.log(`\n  重启应用后,在 MCP / 工具设置中即可看到 AgentLens。`);
    return;
  }

  console.log("检测到以下已安装的 AI 工具:\n");
  let count = 0;
  for (const d of detections) {
    const isInstalled = d.detectDirs.some((dir) => existsSync(dir));
    if (!isInstalled) continue;
    if (installOne(d)) count++;
  }

  if (count === 0) {
    console.log("  未检测到已安装的 AI 工具。");
    console.log("  手动指定目标: agentlens install --target claude|cursor|codex|zcode|workbuddy|mimo");
    return;
  }

  console.log(`\n配置完成: ${count} 个工具已写入 AgentLens MCP。`);
  console.log("重启对应应用后,在 MCP/工具设置里即可看到:");
  console.log("  · agentlens_scan   扫描 Agent 配置");
  console.log("  · agentlens_move   迁移规则");
  console.log("  · agentlens_drift  检测配置漂移");
  console.log("  · agentlens_check  代码体检");
}