agiledev-cli 0.1.5 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +300 -185
  2. package/SKILL.md +114 -98
  3. package/adev.js +1319 -1285
  4. package/autofix/agents/antigravity.js +379 -0
  5. package/autofix/agents/claude.js +147 -0
  6. package/autofix/agents/codex.js +179 -0
  7. package/autofix/agents/exec.js +230 -0
  8. package/autofix/agents/index.js +400 -0
  9. package/autofix/agents/opencode.js +233 -0
  10. package/autofix/agents/pi.js +247 -0
  11. package/autofix/agiledev.js +98 -0
  12. package/autofix/bridge.js +371 -0
  13. package/autofix/cli.js +712 -0
  14. package/autofix/context.js +152 -0
  15. package/autofix/conversation.js +302 -0
  16. package/autofix/coordinator.js +2892 -0
  17. package/autofix/git.js +459 -0
  18. package/autofix/policy.js +230 -0
  19. package/autofix/profile.js +578 -0
  20. package/autofix/public/app.js +3668 -0
  21. package/autofix/public/i18n-id.js +282 -0
  22. package/autofix/public/index.html +32 -0
  23. package/autofix/public/style.css +2463 -0
  24. package/autofix/queue.js +146 -0
  25. package/autofix/scheduler.js +994 -0
  26. package/autofix/scope.js +32 -0
  27. package/autofix/service.js +1940 -0
  28. package/autofix/store.js +375 -0
  29. package/autofix/workspace.js +298 -0
  30. package/autofix/worktree.js +379 -0
  31. package/docs/autofix-design.md +801 -0
  32. package/docs/autofix-profiles.example.json +65 -0
  33. package/imgs/Bug/350/247/243/345/206/263/345/244/207/346/263/250.png +0 -0
  34. package/imgs/logo.png +0 -0
  35. package/imgs//344/277/256/346/224/271Bug/347/212/266/346/200/201.png +0 -0
  36. package/imgs//345/270/256/346/210/221/344/277/256/345/244/215Bug-20260922-010.png +0 -0
  37. package/imgs//346/237/245/347/234/213/345/271/266/345/210/206/346/236/220/351/234/200/346/261/202/346/226/207/346/241/243.png +0 -0
  38. package/imgs//347/234/213/344/270/200/344/270/213/346/210/221/347/216/260/345/234/250/346/234/211/345/223/252/344/272/233/345/274/200/345/217/221/344/273/273/345/212/241.png +0 -0
  39. package/imgs//347/234/213/344/270/200/344/270/213/346/210/221/350/277/230/346/234/211/345/223/252/344/272/233Bug/346/234/252/350/247/243/345/206/263.png +0 -0
  40. package/package.json +39 -36
@@ -0,0 +1,230 @@
1
+ /**
2
+ * Agent CLI 启动辅助。
3
+ *
4
+ * Windows 上通过 npm 全局安装的 CLI 通常是 .cmd 包装脚本,
5
+ * child_process.spawn 直接执行 .cmd 会报 EINVAL。
6
+ * 这里先解析包装脚本指向的真实可执行文件,再以 shell:false 启动,
7
+ * 避免为了跑 .cmd 而把用户提示词交给 shell 解析。
8
+ */
9
+ import fs from "node:fs";
10
+ import path from "node:path";
11
+ import { execFileSync, spawn } from "node:child_process";
12
+
13
+ const resolved = new Map();
14
+ /** 命令名 -> 启动 JS 脚本时需要前置的参数(npm node-js shim)。 */
15
+ const prefixArgs = new Map();
16
+
17
+ /** 清空解析缓存;用户刚安装或升级 CLI 后重新探测时调用。 */
18
+ export function clearResolvedCommands() {
19
+ resolved.clear();
20
+ prefixArgs.clear();
21
+ }
22
+
23
+ /**
24
+ * 从 npm 的 .cmd/.bat 包装脚本中解析真实可执行文件路径。
25
+ * 只处理形如 `"%dp0%\node_modules\...\tool.exe" %*` 的常见 shim;
26
+ * 解析不到时返回 null,由调用方回退。
27
+ *
28
+ * 只在真正执行 CLI 的那行(带 %*)里找目标:codex.cmd 之类的脚本会在
29
+ * `SET "_prog=%dp0%\node.exe"` 里出现 node.exe,全文匹配会把解释器误当成 CLI。
30
+ */
31
+ export function parseCmdTarget(text, cmdPath) {
32
+ const lines = String(text || "").split(/\r?\n/);
33
+ const execLine = lines.find(l => l.includes("%*")) || "";
34
+ const raw = execLine || String(text || "");
35
+ const match = raw.match(/"([^"\r\n]*\.exe)"/i) || raw.match(/(?:^|\s)([^\s"'<>|]+\.exe)(?=\s|$)/i);
36
+ if (!match) return null;
37
+
38
+ const dir = path.win32.dirname(cmdPath);
39
+ let target = match[1].trim()
40
+ .replace(/%~dp0%?/gi, dir)
41
+ .replace(/%dp0%?/gi, dir)
42
+ .replace(/\//g, "\\");
43
+ if (!path.win32.isAbsolute(target)) target = path.win32.join(dir, target);
44
+ return path.win32.normalize(target);
45
+ }
46
+
47
+ /**
48
+ * 解析 npm 生成的 node-js shim(codex.cmd / pi.cmd 属于这一类):
49
+ * "%node%" "%~dp0\pi-launcher.js" %*
50
+ * "%_prog%" "%dp0%\node_modules\@openai\codex\bin\codex.js" %*
51
+ *
52
+ * 返回可直接 spawn 的 { command, prefixArgs };不是这类脚本时返回 null。
53
+ * 不能把里面的 node.exe 当成 CLI 本身——那样 `--version` 会恰好返回 node 版本
54
+ * 而被误判已安装,真正派工时却只是在跑一个不带参数的 node 进程。
55
+ */
56
+ export function parseNodeShim(text, cmdPath) {
57
+ const lines = String(text || "").split(/\r?\n/);
58
+ const dir = path.win32.dirname(cmdPath);
59
+ // %~dp0 / %dp0 展开时自带尾部反斜杠(`%dp0%\tool.js`),这里填不带结尾分隔符的
60
+ // 裸目录,展开后统一用 normalize 折叠可能出现的重复分隔符。
61
+ let launcher = null;
62
+ let nodeCommand = null;
63
+
64
+ for (const line of lines) {
65
+ const js = line.match(/"([^"\r\n]*\.js)"/i);
66
+ if (js) {
67
+ const expanded = js[1].trim()
68
+ .replace(/%~dp0%?/gi, dir)
69
+ .replace(/%dp0%?/gi, dir)
70
+ .replace(/\//g, "\\");
71
+ const full = path.win32.isAbsolute(expanded) ? expanded : path.win32.join(dir, expanded);
72
+ const candidate = path.win32.normalize(full);
73
+ if (fs.existsSync(candidate)) launcher = candidate;
74
+ }
75
+ // npm 的 .cmd 形如 IF EXIST "%~dp0\node.exe" (... SET "_prog=%~dp0\node.exe")
76
+ // ELSE (... SET "_prog=node")。两次赋值都匹配,必须取带路径的那次(走 PATH 的
77
+ // 裸 node 不是我们要的),所以先替换再判断,命中即停。
78
+ const exe = /SET\s+"?_prog=([^"\r\n]+)/i.exec(line);
79
+ if (exe) {
80
+ const candidate = path.win32.normalize(exe[1].trim().replace(/["'\s]+$/, "")
81
+ .replace(/%~dp0%?/gi, dir)
82
+ .replace(/%dp0%?/gi, dir)
83
+ .replace(/\//g, "\\"));
84
+ if (path.win32.isAbsolute(candidate)) nodeCommand = candidate;
85
+ }
86
+ }
87
+
88
+ // 必须真的存在 JS 入口才算 node shim(opencode.cmd 里没有 .js,不能误判)
89
+ if (!launcher) return null;
90
+ const command = nodeCommand && fs.existsSync(nodeCommand) ? nodeCommand : process.execPath;
91
+ return { command, prefixArgs: [launcher] };
92
+ }
93
+
94
+ /** 找到可直接 spawn 的命令路径;非 Windows 或解析失败时原样返回。 */
95
+ export function resolveCommand(name) {
96
+ if (resolved.has(name)) return resolved.get(name);
97
+
98
+ let command = name;
99
+ if (process.platform === "win32") {
100
+ command = resolveWindowsCommand(name);
101
+ }
102
+ resolved.set(name, command);
103
+ return command;
104
+ }
105
+
106
+ function resolveWindowsCommand(name) {
107
+ const candidates = where(name);
108
+
109
+ // 1. 原生 exe 优先
110
+ for (const candidate of candidates) {
111
+ if (/\.exe$/i.test(candidate) && fs.existsSync(candidate)) return candidate;
112
+ }
113
+
114
+ // 2. npm .cmd/.bat 包装脚本
115
+ for (const candidate of candidates) {
116
+ if (!/\.(cmd|bat)$/i.test(candidate)) continue;
117
+ let text;
118
+ try { text = fs.readFileSync(candidate, "utf8"); } catch { continue; }
119
+
120
+ // 2a. 指向 JS 入口的 shim(codex / pi):用 node 直接跑脚本。
121
+ // 必须先判断,否则 codex.cmd 会被 2b 误解析成 node.exe。
122
+ const shim = parseNodeShim(text, candidate);
123
+ if (shim) {
124
+ prefixArgs.set(name, shim.prefixArgs);
125
+ return shim.command;
126
+ }
127
+
128
+ // 2b. 指向真实 exe 的 shim(opencode 等)
129
+ const target = parseCmdTarget(text, candidate);
130
+ if (target && fs.existsSync(target)) return target;
131
+ }
132
+
133
+ // 3. 兜底:交给 CreateProcess 自己按 PATH 解析(原生 exe 仍可用)
134
+ return name;
135
+ }
136
+
137
+ function where(name) {
138
+ try {
139
+ const out = execFileSync("where", [name], {
140
+ windowsHide: true,
141
+ encoding: "utf8",
142
+ stdio: ["ignore", "pipe", "ignore"],
143
+ });
144
+ return out.split(/\r?\n/).map(line => line.trim()).filter(Boolean);
145
+ } catch {
146
+ return [];
147
+ }
148
+ }
149
+
150
+ /**
151
+ * spawn 一个 Agent CLI,自动处理 Windows 的 .cmd shim。
152
+ *
153
+ * onSpawn 用于把 pid 及时落盘:服务被强杀时,下一次启动才能找到并回收
154
+ * 仍在改文件的孤儿 Agent,避免它和新一轮修复同时写同一批文件。
155
+ */
156
+ export function spawnAgent(name, args, options = {}) {
157
+ const { onSpawn, ...spawnOptions } = options;
158
+ const command = resolveCommand(name);
159
+ const prefix = prefixArgs.get(name) || [];
160
+ const child = spawn(command, [...prefix, ...(args || [])], { shell: false, ...spawnOptions });
161
+ if (child?.pid) {
162
+ try { onSpawn?.(child.pid); } catch { /* 回调失败不影响启动 */ }
163
+ }
164
+ return child;
165
+ }
166
+
167
+ /**
168
+ * 结束 Agent 进程及其子进程。
169
+ * Windows 上 CLI 会再拉起工具进程,只杀父进程会留下孤儿进程继续占用额度。
170
+ */
171
+ export function killChild(child) {
172
+ if (!child || child.exitCode !== null) return;
173
+ if (process.platform === "win32" && child.pid) {
174
+ try {
175
+ spawn("taskkill", ["/pid", String(child.pid), "/T", "/F"], {
176
+ windowsHide: true,
177
+ stdio: "ignore",
178
+ });
179
+ return;
180
+ } catch { /* 继续尝试普通 kill */ }
181
+ }
182
+ try { child.kill("SIGTERM"); } catch { /* 已退出 */ }
183
+ }
184
+
185
+ /** 读取进程命令行;读不到时返回 null(无法确认身份时宁可不动它)。 */
186
+ export function processCommandLine(pid) {
187
+ if (!pid) return null;
188
+ try {
189
+ if (process.platform === "win32") {
190
+ const out = execFileSync(
191
+ "powershell",
192
+ ["-NoProfile", "-NonInteractive", "-Command",
193
+ `(Get-CimInstance Win32_Process -Filter "ProcessId=${Number(pid)}").CommandLine`],
194
+ { windowsHide: true, encoding: "utf8", timeout: 5000, stdio: ["ignore", "pipe", "ignore"] },
195
+ );
196
+ return String(out || "").trim() || null;
197
+ }
198
+ const out = execFileSync("ps", ["-p", String(pid), "-o", "command="], {
199
+ encoding: "utf8", timeout: 5000, stdio: ["ignore", "pipe", "ignore"],
200
+ });
201
+ return String(out || "").trim() || null;
202
+ } catch {
203
+ return null;
204
+ }
205
+ }
206
+
207
+ /** 按 pid 结束整棵进程树;用于服务重启后回收上一次留下的 Agent。 */
208
+ export function killPidTree(pid) {
209
+ if (!pid) return false;
210
+ if (process.platform === "win32") {
211
+ try {
212
+ execFileSync("taskkill", ["/pid", String(pid), "/T", "/F"], {
213
+ windowsHide: true, timeout: 15000, stdio: "ignore",
214
+ });
215
+ return true;
216
+ } catch {
217
+ return false;
218
+ }
219
+ }
220
+ let signalled = false;
221
+ for (const signal of ["SIGTERM", "SIGKILL"]) {
222
+ try {
223
+ process.kill(pid, signal);
224
+ signalled = true;
225
+ } catch {
226
+ /* 已退出或没有权限:换下一个信号 */
227
+ }
228
+ }
229
+ return signalled;
230
+ }
@@ -0,0 +1,400 @@
1
+ /**
2
+ * Agent 适配层:按名称分发到具体 CLI 实现。
3
+ */
4
+ import fs from "node:fs";
5
+ import os from "node:os";
6
+ import path from "node:path";
7
+ import * as claude from "./claude.js";
8
+ import * as opencode from "./opencode.js";
9
+ import * as antigravity from "./antigravity.js";
10
+ import * as codex from "./codex.js";
11
+ import * as pi from "./pi.js";
12
+ import { spawnAgent, clearResolvedCommands } from "./exec.js";
13
+
14
+ const ADAPTERS = {
15
+ [claude.AGENT_ID]: claude,
16
+ [opencode.AGENT_ID]: opencode,
17
+ [antigravity.AGENT_ID]: antigravity,
18
+ [codex.AGENT_ID]: codex,
19
+ [pi.AGENT_ID]: pi,
20
+ };
21
+
22
+ export const SUPPORTED_AGENTS = Object.keys(ADAPTERS);
23
+
24
+ const DEFAULT_MODEL = { value: "", label: "默认模型(CLI 登录后的默认)" };
25
+
26
+ /** 原生 Claude Code 未配置 modelPicker 时使用的内置别名。 */
27
+ const CLAUDE_ALIASES = [
28
+ { value: "opus", label: "Opus · 最强推理,适合复杂缺陷" },
29
+ { value: "sonnet", label: "Sonnet · 质量与速度均衡" },
30
+ { value: "haiku", label: "Haiku · 最快,适合简单缺陷" },
31
+ ];
32
+
33
+ /**
34
+ * 控制台启动页展示的 Agent 元数据。
35
+ *
36
+ * Claude Code 的模型列表以 ~/.claude/settings.json 为准(见 modelsFromClaudeSettings),
37
+ * 这里只保留没有 modelPicker 配置时的内置别名作为兜底。
38
+ */
39
+ export const AGENT_META = Object.freeze({
40
+ claude: {
41
+ id: "claude",
42
+ name: "Claude Code",
43
+ description: "擅长读代码、改代码与跑测试;支持原生会话续接。",
44
+ models: [DEFAULT_MODEL, ...CLAUDE_ALIASES],
45
+ },
46
+ opencode: {
47
+ id: "opencode",
48
+ name: "OpenCode",
49
+ description: "支持本地会话、自动批准权限,可接入不同模型提供方。",
50
+ models: [DEFAULT_MODEL],
51
+ },
52
+ antigravity: {
53
+ id: "antigravity",
54
+ name: "Antigravity",
55
+ description: "Google Antigravity CLI(agy),支持 stream-json 与会话续接。",
56
+ models: [DEFAULT_MODEL],
57
+ },
58
+ codex: {
59
+ id: "codex",
60
+ name: "Codex",
61
+ description: "OpenAI Codex CLI(codex exec),仅在本机安装后显示。",
62
+ models: [DEFAULT_MODEL],
63
+ },
64
+ pi: {
65
+ id: "pi",
66
+ name: "Pi",
67
+ description: "Pi coding agent(pi -p --mode json),仅在本机安装后显示。",
68
+ models: [DEFAULT_MODEL],
69
+ },
70
+ });
71
+
72
+ /**
73
+ * 把 ~/.claude/settings.json 的 modelPicker 配置转成页面可用的模型列表。
74
+ *
75
+ * Magpie 等代理会把可用模型写进 modelPicker.options(含 label/description),
76
+ * 这正是 Claude Code 自己的 /model 列表来源;必须读它,不能只给四个内置别名。
77
+ */
78
+ export function modelsFromClaudeSettings(settings) {
79
+ const options = Array.isArray(settings?.modelPicker?.options) ? settings.modelPicker.options : [];
80
+ const out = [{ ...DEFAULT_MODEL }];
81
+ const seen = new Set([""]);
82
+
83
+ for (const option of options) {
84
+ const value = String(option?.model ?? "").trim();
85
+ if (!value || seen.has(value)) continue;
86
+ seen.add(value);
87
+ // label 必须与 Claude Code 的 /model 列表完全一致,不能再拼接 description,
88
+ // 否则界面显示的“模型名”和真实名称对不上。
89
+ const label = String(option?.label ?? "").trim() || value;
90
+ const description = String(option?.description ?? "").trim();
91
+ out.push({ value, label, description: description || null });
92
+ }
93
+
94
+ // 没有 modelPicker(原生 Claude Code)或配置里没有有效模型时退回内置别名。
95
+ if (out.length === 1) {
96
+ for (const alias of CLAUDE_ALIASES) {
97
+ if (seen.has(alias.value)) continue;
98
+ seen.add(alias.value);
99
+ out.push({ ...alias });
100
+ }
101
+ }
102
+ return out;
103
+ }
104
+
105
+ function readClaudeModels() {
106
+ try {
107
+ const dir = process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), ".claude");
108
+ const file = path.join(dir, "settings.json");
109
+ return modelsFromClaudeSettings(JSON.parse(fs.readFileSync(file, "utf8")));
110
+ } catch {
111
+ return modelsFromClaudeSettings(null);
112
+ }
113
+ }
114
+
115
+ /**
116
+ * 从 ~/.config/opencode/opencode.json 读取 provider 下配置的真实模型友好名称。
117
+ * 例如:{ provider: { magpie: { models: { "antigravity/claude-opus-4-6-thinking": { name: "Claude Opus 4.6..." } } } } }
118
+ * 这样 opencode CLI 输出的标识符 `magpie/antigravity/claude-opus-4-6-thinking` 就能对应到真实显示名。
119
+ */
120
+ export function readOpencodeConfigNames() {
121
+ const map = new Map();
122
+ const candidates = [
123
+ path.join(os.homedir(), ".config", "opencode", "opencode.json"),
124
+ path.join(os.homedir(), ".opencode", "opencode.json"),
125
+ process.env.APPDATA ? path.join(process.env.APPDATA, "opencode", "opencode.json") : null,
126
+ process.env.LOCALAPPDATA ? path.join(process.env.LOCALAPPDATA, "opencode", "opencode.json") : null,
127
+ ].filter(Boolean);
128
+
129
+ for (const file of candidates) {
130
+ try {
131
+ if (!fs.existsSync(file)) continue;
132
+ const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
133
+ const providers = parsed?.provider && typeof parsed.provider === "object" ? parsed.provider : {};
134
+ for (const [providerId, provider] of Object.entries(providers)) {
135
+ const models = provider?.models && typeof provider.models === "object" ? provider.models : {};
136
+ for (const [modelKey, modelInfo] of Object.entries(models)) {
137
+ const friendlyName = String(modelInfo?.name || "").trim();
138
+ if (!friendlyName) continue;
139
+ // 匹配规则:同时记录完整路径与纯模型 key,确保无论 CLI 输出格式怎样都能命中
140
+ map.set(`${providerId}/${modelKey}`, friendlyName);
141
+ map.set(modelKey, friendlyName);
142
+ }
143
+ }
144
+ if (map.size) break;
145
+ } catch { /* 忽略单个配置解析失败 */ }
146
+ }
147
+ return map;
148
+ }
149
+
150
+ /** 解析 `opencode models` 的文本输出;忽略 ANSI、表格边框和标题行。配合 opencode.json 解析友好名称。 */
151
+ export function parseOpencodeModels(stdout, nameMap = new Map()) {
152
+ const out = [];
153
+ const seen = new Set();
154
+ for (const raw of String(stdout || "").split(/\r?\n/)) {
155
+ const line = raw
156
+ .replace(/\x1b\[[0-9;]*m/g, "")
157
+ .trim()
158
+ .replace(/^[│|\s*+-]+/, "")
159
+ .replace(/[│|\s]+$/, "");
160
+ if (!line || line.length > 200) continue;
161
+ if (!/^[^\s/]+\/\S+$/.test(line)) continue;
162
+ if (seen.has(line)) continue;
163
+ seen.add(line);
164
+ const friendlyName = nameMap.get(line) || nameMap.get(line.replace(/^[^\/]+\//, "")) || line;
165
+ out.push({ value: line, label: friendlyName });
166
+ }
167
+ return out;
168
+ }
169
+
170
+ async function opencodeModels() {
171
+ const nameMap = readOpencodeConfigNames();
172
+ const stdout = await collectStdout("opencode", ["models"], 20000);
173
+ return [{ ...DEFAULT_MODEL }, ...parseOpencodeModels(stdout, nameMap)];
174
+ }
175
+
176
+ /** 缓存模型列表:CLI 查询较慢,控制台每次刷新都调用不能重复等待。 */
177
+ const MODEL_CACHE_TTL_MS = 5 * 60 * 1000;
178
+ const modelCache = new Map();
179
+
180
+ async function cachedModels(key, loader) {
181
+ const hit = modelCache.get(key);
182
+ if (hit && Date.now() - hit.at < MODEL_CACHE_TTL_MS) return hit.models.map(m => ({ ...m }));
183
+ const models = await loader();
184
+ modelCache.set(key, { at: Date.now(), models });
185
+ return models.map(m => ({ ...m }));
186
+ }
187
+
188
+ /** 解析 `agy models` 的文本输出(ID 与显示名以制表符分隔)。 */
189
+ export function parseAntigravityModels(stdout) {
190
+ const out = [];
191
+ const seen = new Set();
192
+ for (const raw of String(stdout || "").split(/\r?\n/)) {
193
+ const line = raw.replace(/\x1b\[[0-9;]*m/g, "").trim();
194
+ if (!line || /^fetching/i.test(line)) continue;
195
+ let id = "";
196
+ let label = "";
197
+ if (line.includes("\t")) {
198
+ [id, label] = line.split("\t");
199
+ } else {
200
+ const m = line.match(/^([A-Za-z0-9._:/-]+)\s{2,}(.+)$/);
201
+ if (m) [, id, label] = m;
202
+ }
203
+ id = String(id || "").trim();
204
+ label = String(label || "").trim();
205
+ if (!id || seen.has(id)) continue;
206
+ seen.add(id);
207
+ out.push({ value: id, label: label || id });
208
+ }
209
+ return out;
210
+ }
211
+
212
+ async function antigravityModels() {
213
+ const command = await antigravity.resolveCli();
214
+ const stdout = await collectStdout(command, ["models"], 20000);
215
+ return [{ ...DEFAULT_MODEL }, ...parseAntigravityModels(stdout)];
216
+ }
217
+
218
+ /**
219
+ * 解析 `pi --list-models` 的表格输出(provider/model/context/...)。
220
+ * 值用 provider/id,和 --model 参数一致;没有 provider 的行忽略。
221
+ */
222
+ export function parsePiModels(stdout) {
223
+ const out = [];
224
+ const seen = new Set();
225
+ for (const raw of String(stdout || "").split(/\r?\n/)) {
226
+ const line = raw.replace(/\x1b\[[0-9;]*m/g, "").trim();
227
+ if (!line || /^provider\s+model/i.test(line)) continue;
228
+ const m = line.match(/^(\S+)\s+(\S+)(?:\s|$)/);
229
+ if (!m) continue;
230
+ const value = `${m[1]}/${m[2]}`;
231
+ if (seen.has(value)) continue;
232
+ seen.add(value);
233
+ out.push({ value, label: value });
234
+ }
235
+ return out;
236
+ }
237
+
238
+ async function piModels() {
239
+ const stdout = await collectStdout("pi", ["--list-models"], 20000);
240
+ return [{ ...DEFAULT_MODEL }, ...parsePiModels(stdout)];
241
+ }
242
+
243
+ /** Codex 没有列出全部模型的命令:给默认模型 + config.toml 里配置的当前模型。 */
244
+ async function codexModels() {
245
+ const models = [{ ...DEFAULT_MODEL }];
246
+ try {
247
+ const file = path.join(process.env.CODEX_HOME || path.join(os.homedir(), ".codex"), "config.toml");
248
+ const m = fs.readFileSync(file, "utf8").match(/^\s*model\s*=\s*["']([^"']+)["']/m);
249
+ if (m && m[1]) models.push({ value: m[1], label: `${m[1]}(config.toml)` });
250
+ } catch { /* 没有配置就用默认模型 */ }
251
+ return models;
252
+ }
253
+
254
+ function collectStdout(name, args, timeoutMs) {
255
+ return new Promise((resolve) => {
256
+ let child;
257
+ try {
258
+ child = spawnAgent(name, args, { windowsHide: true });
259
+ } catch {
260
+ resolve("");
261
+ return;
262
+ }
263
+ let stdout = "";
264
+ let settled = false;
265
+ const finish = () => {
266
+ if (settled) return;
267
+ settled = true;
268
+ clearTimeout(timer);
269
+ resolve(stdout);
270
+ };
271
+ const timer = setTimeout(() => {
272
+ try { child.kill(); } catch { /* 已退出 */ }
273
+ finish();
274
+ }, timeoutMs);
275
+ child.on("error", finish);
276
+ child.stdout?.on("data", d => { stdout += d.toString(); });
277
+ child.on("close", finish);
278
+ });
279
+ }
280
+
281
+ /** 列出某个 Agent 可选的模型;Claude 每次读取 settings,OpenCode / Antigravity 询问 CLI 并缓存。 */
282
+ export async function listModels(name) {
283
+ const meta = AGENT_META[name];
284
+ if (!meta) return [];
285
+ if (name === "claude") return readClaudeModels();
286
+ if (name === "opencode") return cachedModels("opencode", opencodeModels);
287
+ if (name === "antigravity") return cachedModels("antigravity", antigravityModels);
288
+ if (name === "pi") return cachedModels("pi", piModels);
289
+ if (name === "codex") return codexModels();
290
+ return meta.models.map(model => ({ ...model }));
291
+ }
292
+
293
+ /**
294
+ * 控制台需要的 Agent 清单。
295
+ *
296
+ * 只返回本机已安装的 Agent:Codex / Pi 这类可选 CLI 没装时不应该出现在
297
+ * 启动页的按钮里(用户明确要求「没安装就不显示」)。未安装的条目既不展示,
298
+ * 也不需要去查询模型,顺便省掉探测开销。
299
+ */
300
+ export async function describeAgents(detected) {
301
+ const found = detected || await detectAgents();
302
+ const ids = SUPPORTED_AGENTS.filter(id => found.includes(id));
303
+ // 并行查询模型:多个 CLI 串行会明显拖慢启动配置页
304
+ const models = await Promise.all(ids.map(id => listModels(id)));
305
+ return ids.map((id, i) => {
306
+ const meta = AGENT_META[id] || { id, name: id, description: "" };
307
+ return {
308
+ id,
309
+ name: meta.name,
310
+ description: meta.description,
311
+ available: true,
312
+ models: models[i],
313
+ };
314
+ });
315
+ }
316
+
317
+ export function getAdapter(name) {
318
+ return ADAPTERS[name] || null;
319
+ }
320
+
321
+ /** 探测本机已安装的 Agent CLI。Antigravity 的命令名是 agy,可能需要回退到 antigravity。 */
322
+ export async function detectAgents() {
323
+ const found = [];
324
+ await Promise.all(SUPPORTED_AGENTS.map(async (id) => {
325
+ if (await isAgentAvailable(id)) found.push(id);
326
+ }));
327
+ return SUPPORTED_AGENTS.filter(id => found.includes(id));
328
+ }
329
+
330
+ async function isAgentAvailable(id) {
331
+ const adapter = ADAPTERS[id];
332
+ const commands = Array.isArray(adapter?.COMMANDS) ? adapter.COMMANDS : [id];
333
+ for (const cmd of commands) {
334
+ if (await isExecutable(cmd)) return true;
335
+ }
336
+ return false;
337
+ }
338
+
339
+ /** 用户刚安装 CLI 后点「重新检测」时,清掉命令与模型的解析缓存。 */
340
+ export function refreshAgentCache() {
341
+ clearResolvedCommands();
342
+ modelCache.clear();
343
+ for (const adapter of Object.values(ADAPTERS)) adapter.clearCommandCache?.();
344
+ }
345
+
346
+ /** 中断所有正在运行的 Agent 进程(重启服务、切换模型或停止时使用)。 */
347
+ export function abortAgents() {
348
+ for (const adapter of Object.values(ADAPTERS)) adapter.abortAll?.();
349
+ }
350
+
351
+ async function isExecutable(cmd) {
352
+ return new Promise((resolve) => {
353
+ let child;
354
+ try {
355
+ child = spawnAgent(cmd, ["--version"], { windowsHide: true });
356
+ } catch {
357
+ resolve(false);
358
+ return;
359
+ }
360
+ let done = false;
361
+ const finish = (ok) => {
362
+ if (done) return;
363
+ done = true;
364
+ clearTimeout(timer);
365
+ resolve(ok);
366
+ };
367
+ const timer = setTimeout(() => {
368
+ try { child.kill(); } catch { /* 已退出 */ }
369
+ finish(false);
370
+ }, 8000);
371
+ child.on("error", () => finish(false));
372
+ child.on("close", code => finish(code === 0));
373
+ });
374
+ }
375
+
376
+ /**
377
+ * 解析本次要使用的 Agent:
378
+ * 本次参数 > 工作区记忆 > 全局 lastAgent > 探测结果。
379
+ */
380
+ export function resolveAgent({ requested, workspaceAgent, lastAgent, detected = [] }) {
381
+ if (requested) {
382
+ if (!ADAPTERS[requested]) {
383
+ return { agent: null, reason: `unknown_agent`, message: `未知的 Agent: ${requested}(支持 ${SUPPORTED_AGENTS.join(" / ")})` };
384
+ }
385
+ return { agent: requested, source: "argument" };
386
+ }
387
+ if (workspaceAgent && ADAPTERS[workspaceAgent]) return { agent: workspaceAgent, source: "workspace" };
388
+ if (lastAgent && ADAPTERS[lastAgent]) return { agent: lastAgent, source: "last" };
389
+ if (detected.length === 1) return { agent: detected[0], source: "detected" };
390
+ // 多个 Agent 同时存在时优先 Claude Code(兼容旧默认),
391
+ // 但没装 Claude 时不能盲选它,否则派工会失败。
392
+ if (detected.length > 1) {
393
+ return { agent: detected.includes("claude") ? "claude" : detected[0], source: "default" };
394
+ }
395
+ return {
396
+ agent: null,
397
+ reason: "agent_missing",
398
+ message: `未找到可用的 Agent CLI(${SUPPORTED_AGENTS.join(" / ")})。请安装后在 PATH 中配置后重试。`,
399
+ };
400
+ }