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.
- package/README.md +300 -185
- package/SKILL.md +114 -98
- package/adev.js +1319 -1285
- package/autofix/agents/antigravity.js +379 -0
- package/autofix/agents/claude.js +147 -0
- package/autofix/agents/codex.js +179 -0
- package/autofix/agents/exec.js +230 -0
- package/autofix/agents/index.js +400 -0
- package/autofix/agents/opencode.js +233 -0
- package/autofix/agents/pi.js +247 -0
- package/autofix/agiledev.js +98 -0
- package/autofix/bridge.js +371 -0
- package/autofix/cli.js +712 -0
- package/autofix/context.js +152 -0
- package/autofix/conversation.js +302 -0
- package/autofix/coordinator.js +2892 -0
- package/autofix/git.js +459 -0
- package/autofix/policy.js +230 -0
- package/autofix/profile.js +578 -0
- package/autofix/public/app.js +3668 -0
- package/autofix/public/i18n-id.js +282 -0
- package/autofix/public/index.html +32 -0
- package/autofix/public/style.css +2463 -0
- package/autofix/queue.js +146 -0
- package/autofix/scheduler.js +994 -0
- package/autofix/scope.js +32 -0
- package/autofix/service.js +1940 -0
- package/autofix/store.js +375 -0
- package/autofix/workspace.js +298 -0
- package/autofix/worktree.js +379 -0
- package/docs/autofix-design.md +801 -0
- package/docs/autofix-profiles.example.json +65 -0
- package/imgs/Bug/350/247/243/345/206/263/345/244/207/346/263/250.png +0 -0
- package/imgs/logo.png +0 -0
- package/imgs//344/277/256/346/224/271Bug/347/212/266/346/200/201.png +0 -0
- package/imgs//345/270/256/346/210/221/344/277/256/345/244/215Bug-20260922-010.png +0 -0
- 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
- 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
- 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
- package/package.json +39 -36
|
@@ -0,0 +1,379 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Antigravity 适配器(本机命令 `agy`)。
|
|
3
|
+
*
|
|
4
|
+
* 非交互调用:`agy -p "<prompt>" --output-format stream-json --dangerously-skip-permissions`,
|
|
5
|
+
* 用 `--conversation <id>` 续接会话,`--model` 指定模型。
|
|
6
|
+
*
|
|
7
|
+
* MCP 注入的限制:Antigravity 只从全局 `~/.gemini/config/mcp_config.json` 读取 MCP,
|
|
8
|
+
* `--settings` 不接受 mcpServers。因此这里采用“受控合并 + 用完还原”的方式:
|
|
9
|
+
* - 运行前把 adev-autofix 条目合并进配置(保留用户已有条目);
|
|
10
|
+
* - 运行结束后只有文件仍是我们写入的内容时才还原,避免覆盖用户同时做的修改;
|
|
11
|
+
* - 并发运行时用引用计数,最后一个结束才还原。
|
|
12
|
+
*
|
|
13
|
+
* 因为配置是静态的,main/worker 无法按进程切换角色,条目统一使用 --role all
|
|
14
|
+
* (暴露全部工具),由各自的提示词约束使用范围。
|
|
15
|
+
*/
|
|
16
|
+
import fs from "node:fs";
|
|
17
|
+
import os from "node:os";
|
|
18
|
+
import path from "node:path";
|
|
19
|
+
import { spawnAgent, killChild } from "./exec.js";
|
|
20
|
+
|
|
21
|
+
export const AGENT_ID = "antigravity";
|
|
22
|
+
|
|
23
|
+
/** CLI 命令候选:官方安装名是 agy,部分环境可能叫 antigravity。 */
|
|
24
|
+
export const COMMANDS = ["agy", "antigravity"];
|
|
25
|
+
|
|
26
|
+
const SERVER_NAME = "adev-autofix";
|
|
27
|
+
// 路径必须延迟计算:测试会把 HOME 指向临时目录,模块加载时固定会写进真实用户配置
|
|
28
|
+
function configDir() {
|
|
29
|
+
return path.join(os.homedir(), ".gemini", "config");
|
|
30
|
+
}
|
|
31
|
+
function configFile() {
|
|
32
|
+
return path.join(configDir(), "mcp_config.json");
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const activeRuns = new Set();
|
|
36
|
+
|
|
37
|
+
export function abortAll() {
|
|
38
|
+
for (const child of activeRuns) killChild(child);
|
|
39
|
+
activeRuns.clear();
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
let commandCache = null;
|
|
43
|
+
|
|
44
|
+
export function clearCommandCache() {
|
|
45
|
+
commandCache = null;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function probe(cmd) {
|
|
49
|
+
return new Promise((resolve) => {
|
|
50
|
+
let child;
|
|
51
|
+
try {
|
|
52
|
+
child = spawnAgent(cmd, ["--version"], { windowsHide: true });
|
|
53
|
+
} catch {
|
|
54
|
+
resolve(false);
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
let done = false;
|
|
58
|
+
const finish = (ok) => {
|
|
59
|
+
if (done) return;
|
|
60
|
+
done = true;
|
|
61
|
+
clearTimeout(timer);
|
|
62
|
+
resolve(ok);
|
|
63
|
+
};
|
|
64
|
+
const timer = setTimeout(() => {
|
|
65
|
+
try { child.kill(); } catch { /* 已退出 */ }
|
|
66
|
+
finish(false);
|
|
67
|
+
}, 8000);
|
|
68
|
+
child.on("error", () => finish(false));
|
|
69
|
+
child.on("close", code => finish(code === 0));
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** 解析实际可用的 CLI 命令;探测结果缓存,安装后由 refreshAgentCache 清空。 */
|
|
74
|
+
export async function resolveCli() {
|
|
75
|
+
if (commandCache) return commandCache;
|
|
76
|
+
for (const cmd of COMMANDS) {
|
|
77
|
+
if (await probe(cmd)) {
|
|
78
|
+
commandCache = cmd;
|
|
79
|
+
return cmd;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
return COMMANDS[0];
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export function buildArgs({ prompt, sessionId, model }) {
|
|
86
|
+
const args = ["-p", prompt, "--output-format", "stream-json", "--dangerously-skip-permissions"];
|
|
87
|
+
if (sessionId) args.push("--conversation", sessionId);
|
|
88
|
+
if (model) args.push("--model", model);
|
|
89
|
+
return args;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** 从 stream-json 行里抽取文本、工具调用、会话 ID 与最终结果。 */
|
|
93
|
+
export function parseStreamJson(text) {
|
|
94
|
+
const out = { texts: [], toolCalls: [], result: null, sessionId: null, isError: false, error: null, model: null, raw: [] };
|
|
95
|
+
for (const line of String(text || "").split(/\r?\n/)) {
|
|
96
|
+
const t = line.trim();
|
|
97
|
+
if (!t.startsWith("{")) continue;
|
|
98
|
+
let obj;
|
|
99
|
+
try { obj = JSON.parse(t); } catch { continue; }
|
|
100
|
+
out.raw.push(obj);
|
|
101
|
+
|
|
102
|
+
const event = obj.event || obj.type;
|
|
103
|
+
const payload = event && obj[event] && typeof obj[event] === "object" ? obj[event] : obj;
|
|
104
|
+
|
|
105
|
+
const sid = obj.conversation_id || payload?.conversation_id || obj.init?.conversation_id;
|
|
106
|
+
if (typeof sid === "string" && sid) out.sessionId = sid;
|
|
107
|
+
|
|
108
|
+
if (event === "init") {
|
|
109
|
+
if (obj.init?.model) out.model = obj.init.model;
|
|
110
|
+
continue;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
if (event === "result") {
|
|
114
|
+
const r = payload || {};
|
|
115
|
+
out.result = typeof r.response === "string" ? r.response : (r.result ?? null);
|
|
116
|
+
out.isError = String(r.status || "").toUpperCase() === "ERROR" || !!r.error;
|
|
117
|
+
if (r.error) out.error = String(r.error);
|
|
118
|
+
continue;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
if (event === "step_update") {
|
|
122
|
+
const step = payload?.step || payload || {};
|
|
123
|
+
const kind = String(step.step_type || step.type || "");
|
|
124
|
+
// 不同版本字段名不完全一致:tool_info / toolInfo / tool_call 都兼容
|
|
125
|
+
const info = step.tool_info || step.toolInfo || step.tool_call || step.toolCall || null;
|
|
126
|
+
const name = info?.name || info?.tool_name || step.tool_name || step.tool || null;
|
|
127
|
+
if (info || /tool/i.test(kind) || /tool/i.test(String(name || ""))) {
|
|
128
|
+
if (name) out.toolCalls.push({ name: String(name), input: info?.input ?? step.input ?? null });
|
|
129
|
+
continue;
|
|
130
|
+
}
|
|
131
|
+
const piece = [step.text, step.delta, step.content]
|
|
132
|
+
.find(v => typeof v === "string" && v.trim());
|
|
133
|
+
if (piece) out.texts.push(piece);
|
|
134
|
+
continue;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
if (typeof obj.text === "string" && obj.text.trim()) out.texts.push(obj.text);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// 最终回答以 result.response 为准:流式 step 文本可能是累计快照,
|
|
141
|
+
// 直接拼接会把同一段内容重复带进复核与提示词。
|
|
142
|
+
const finalText = typeof out.result === "string" ? out.result.trim() : "";
|
|
143
|
+
out.text = finalText || out.texts.join("\n").trim();
|
|
144
|
+
return out;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/* ======================== MCP 配置注入 ======================== */
|
|
148
|
+
|
|
149
|
+
function bridgeFromMcpConfig(mcpConfig) {
|
|
150
|
+
const server = mcpConfig?.mcpServers?.[SERVER_NAME];
|
|
151
|
+
if (!server) return null;
|
|
152
|
+
const args = Array.isArray(server.args) ? server.args : [];
|
|
153
|
+
const get = (flag) => {
|
|
154
|
+
const i = args.indexOf(flag);
|
|
155
|
+
return i >= 0 ? args[i + 1] : null;
|
|
156
|
+
};
|
|
157
|
+
const bridgePath = args.find(a => /bridge\.js$/i.test(String(a))) || args[0] || null;
|
|
158
|
+
const endpoint = get("--endpoint") || server.env?.ADEV_AUTOFIX_ENDPOINT || null;
|
|
159
|
+
const token = get("--token") || server.env?.ADEV_AUTOFIX_TOKEN || null;
|
|
160
|
+
if (!bridgePath || !endpoint || !token) return null;
|
|
161
|
+
return { bridgePath, endpoint, token };
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** 去掉 JSONC 的注释与尾随逗号;失败时抛错交给调用方降级。 */
|
|
165
|
+
export function parseJsonc(text) {
|
|
166
|
+
let out = "";
|
|
167
|
+
let inString = false;
|
|
168
|
+
let escape = false;
|
|
169
|
+
for (let i = 0; i < text.length; i += 1) {
|
|
170
|
+
const ch = text[i];
|
|
171
|
+
const next = text[i + 1];
|
|
172
|
+
if (inString) {
|
|
173
|
+
out += ch;
|
|
174
|
+
if (escape) escape = false;
|
|
175
|
+
else if (ch === "\\") escape = true;
|
|
176
|
+
else if (ch === '"') inString = false;
|
|
177
|
+
continue;
|
|
178
|
+
}
|
|
179
|
+
if (ch === '"') {
|
|
180
|
+
inString = true;
|
|
181
|
+
out += ch;
|
|
182
|
+
continue;
|
|
183
|
+
}
|
|
184
|
+
if (ch === "/" && next === "/") {
|
|
185
|
+
while (i < text.length && text[i] !== "\n") i += 1;
|
|
186
|
+
out += "\n";
|
|
187
|
+
continue;
|
|
188
|
+
}
|
|
189
|
+
if (ch === "/" && next === "*") {
|
|
190
|
+
i += 2;
|
|
191
|
+
while (i < text.length && !(text[i] === "*" && text[i + 1] === "/")) i += 1;
|
|
192
|
+
i += 1;
|
|
193
|
+
continue;
|
|
194
|
+
}
|
|
195
|
+
out += ch;
|
|
196
|
+
}
|
|
197
|
+
return JSON.parse(out.replace(/,\s*([}\]])/g, "$1"));
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function readConfigText() {
|
|
201
|
+
try {
|
|
202
|
+
return { exists: true, text: fs.readFileSync(configFile(), "utf8") };
|
|
203
|
+
} catch {
|
|
204
|
+
return { exists: false, text: "" };
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
function writeConfigText(text) {
|
|
209
|
+
fs.mkdirSync(configDir(), { recursive: true });
|
|
210
|
+
const tmp = `${configFile()}.${process.pid}.tmp`;
|
|
211
|
+
fs.writeFileSync(tmp, text, { mode: 0o600 });
|
|
212
|
+
fs.renameSync(tmp, configFile());
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
function mergedConfigText(base, info) {
|
|
216
|
+
const servers = base?.mcpServers && typeof base.mcpServers === "object" && !Array.isArray(base.mcpServers)
|
|
217
|
+
? { ...base.mcpServers }
|
|
218
|
+
: {};
|
|
219
|
+
servers[SERVER_NAME] = {
|
|
220
|
+
command: process.execPath,
|
|
221
|
+
// endpoint/token 同时写进 args 与 env:不同版本的 Antigravity 对 env 支持不一致,
|
|
222
|
+
// bridge 又优先读命令行参数,这样两种配置都能跑通。
|
|
223
|
+
args: [info.bridgePath, "--role", "all", "--endpoint", info.endpoint, "--token", info.token],
|
|
224
|
+
env: {
|
|
225
|
+
ADEV_AUTOFIX_ENDPOINT: info.endpoint,
|
|
226
|
+
ADEV_AUTOFIX_TOKEN: info.token,
|
|
227
|
+
},
|
|
228
|
+
disabled: false,
|
|
229
|
+
};
|
|
230
|
+
return `${JSON.stringify({ ...base, mcpServers: servers }, null, 2)}\n`;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
// 串行化配置读写,避免并发运行互相覆盖
|
|
234
|
+
let queue = Promise.resolve();
|
|
235
|
+
function serialized(task) {
|
|
236
|
+
const next = queue.then(task, task);
|
|
237
|
+
queue = next.then(() => {}, () => {});
|
|
238
|
+
return next;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
let mcpState = null;
|
|
242
|
+
|
|
243
|
+
/** 合并 MCP 条目;返回是否注入成功(失败时降级为无 MCP 运行)。 */
|
|
244
|
+
export function acquireMcp(mcpConfig) {
|
|
245
|
+
const info = bridgeFromMcpConfig(mcpConfig);
|
|
246
|
+
if (!info) {
|
|
247
|
+
console.error("[antigravity] 无法解析 bridge 路径或 endpoint/token,本次运行不带 adev-autofix 工具");
|
|
248
|
+
return Promise.resolve(false);
|
|
249
|
+
}
|
|
250
|
+
return serialized(() => {
|
|
251
|
+
try {
|
|
252
|
+
const current = readConfigText();
|
|
253
|
+
const base = current.exists && current.text.trim() ? parseJsonc(current.text) : {};
|
|
254
|
+
const written = mergedConfigText(base, info);
|
|
255
|
+
writeConfigText(written);
|
|
256
|
+
if (mcpState) {
|
|
257
|
+
mcpState.count += 1;
|
|
258
|
+
mcpState.written = written;
|
|
259
|
+
mcpState.info = info;
|
|
260
|
+
} else {
|
|
261
|
+
mcpState = { count: 1, original: current, written, info };
|
|
262
|
+
}
|
|
263
|
+
return true;
|
|
264
|
+
} catch (e) {
|
|
265
|
+
// 配置损坏时不能中断运行:降级为无 MCP 继续,但必须留下线索方便排查
|
|
266
|
+
console.error(`[antigravity] 写入全局 MCP 配置失败,本次运行降级为无工具:${String(e?.message || e)}`);
|
|
267
|
+
return false;
|
|
268
|
+
}
|
|
269
|
+
});
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/** 运行结束还原配置;只有文件仍是我们写入的内容时才还原。 */
|
|
273
|
+
export function releaseMcp() {
|
|
274
|
+
return serialized(() => {
|
|
275
|
+
if (!mcpState) return;
|
|
276
|
+
mcpState.count -= 1;
|
|
277
|
+
if (mcpState.count > 0) return;
|
|
278
|
+
const state = mcpState;
|
|
279
|
+
mcpState = null;
|
|
280
|
+
try {
|
|
281
|
+
const current = readConfigText();
|
|
282
|
+
if (current.exists && current.text === state.written) {
|
|
283
|
+
if (state.original.exists) writeConfigText(state.original.text);
|
|
284
|
+
else fs.rmSync(configFile(), { force: true });
|
|
285
|
+
}
|
|
286
|
+
} catch { /* 还原失败不影响主流程 */ }
|
|
287
|
+
});
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/* ======================== 运行 ======================== */
|
|
291
|
+
|
|
292
|
+
export async function run({ prompt, cwd, sessionId, model, mcpConfig, env, onEvent, onSpawn, signal, timeoutMs = 60 * 60 * 1000, idleTimeoutMs = 15 * 60 * 1000 }) {
|
|
293
|
+
const injected = mcpConfig ? await acquireMcp(mcpConfig) : false;
|
|
294
|
+
const command = await resolveCli();
|
|
295
|
+
|
|
296
|
+
return new Promise((resolve) => {
|
|
297
|
+
const release = () => { if (injected) releaseMcp().catch(() => {}); };
|
|
298
|
+
let child;
|
|
299
|
+
try {
|
|
300
|
+
child = spawnAgent(command, buildArgs({ prompt, sessionId, model }), {
|
|
301
|
+
cwd,
|
|
302
|
+
env: env ?? process.env,
|
|
303
|
+
windowsHide: true,
|
|
304
|
+
onSpawn,
|
|
305
|
+
});
|
|
306
|
+
} catch (e) {
|
|
307
|
+
release();
|
|
308
|
+
resolve({
|
|
309
|
+
ok: false,
|
|
310
|
+
exitCode: null,
|
|
311
|
+
signal: null,
|
|
312
|
+
timedOut: false,
|
|
313
|
+
idleTimeoutMs,
|
|
314
|
+
sessionId: sessionId || null,
|
|
315
|
+
text: "",
|
|
316
|
+
result: "",
|
|
317
|
+
toolCalls: [],
|
|
318
|
+
stderr: String(e?.message || e),
|
|
319
|
+
stdout: "",
|
|
320
|
+
});
|
|
321
|
+
return;
|
|
322
|
+
}
|
|
323
|
+
activeRuns.add(child);
|
|
324
|
+
if (signal?.aborted) {
|
|
325
|
+
killChild(child);
|
|
326
|
+
} else if (signal) {
|
|
327
|
+
signal.addEventListener("abort", () => killChild(child), { once: true });
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
let stdout = "";
|
|
331
|
+
let stderr = "";
|
|
332
|
+
let settled = false;
|
|
333
|
+
let timedOut = false;
|
|
334
|
+
const hardTimer = setTimeout(() => {
|
|
335
|
+
timedOut = true;
|
|
336
|
+
killChild(child);
|
|
337
|
+
}, timeoutMs);
|
|
338
|
+
let idleTimer = null;
|
|
339
|
+
const resetIdle = () => {
|
|
340
|
+
clearTimeout(idleTimer);
|
|
341
|
+
idleTimer = setTimeout(() => {
|
|
342
|
+
timedOut = true;
|
|
343
|
+
killChild(child);
|
|
344
|
+
}, idleTimeoutMs);
|
|
345
|
+
};
|
|
346
|
+
resetIdle();
|
|
347
|
+
|
|
348
|
+
child.stdout.on("data", d => { stdout += d.toString(); resetIdle(); onEvent?.({ type: "raw", chunk: d.toString() }); });
|
|
349
|
+
child.stderr.on("data", d => { stderr += d.toString(); resetIdle(); });
|
|
350
|
+
|
|
351
|
+
const finish = (code, signal) => {
|
|
352
|
+
if (settled) return;
|
|
353
|
+
settled = true;
|
|
354
|
+
activeRuns.delete(child);
|
|
355
|
+
clearTimeout(hardTimer);
|
|
356
|
+
clearTimeout(idleTimer);
|
|
357
|
+
release();
|
|
358
|
+
const parsed = parseStreamJson(stdout);
|
|
359
|
+
onEvent?.({ type: "result", parsed });
|
|
360
|
+
const errorText = parsed.error || (/AGY_ERROR:\s*(\{.*\})/s.exec(stderr)?.[0] || "");
|
|
361
|
+
resolve({
|
|
362
|
+
ok: code === 0 && !parsed.isError && !timedOut,
|
|
363
|
+
exitCode: code,
|
|
364
|
+
signal,
|
|
365
|
+
timedOut,
|
|
366
|
+
idleTimeoutMs,
|
|
367
|
+
sessionId: parsed.sessionId || sessionId || null,
|
|
368
|
+
text: parsed.text,
|
|
369
|
+
result: parsed.result,
|
|
370
|
+
toolCalls: parsed.toolCalls,
|
|
371
|
+
stderr: (errorText || stderr).slice(-4000),
|
|
372
|
+
stdout: stdout.slice(-20000),
|
|
373
|
+
});
|
|
374
|
+
};
|
|
375
|
+
|
|
376
|
+
child.on("error", e => { stderr += String(e?.message || e); finish(null, null); });
|
|
377
|
+
child.on("close", (code, signal) => finish(code, signal));
|
|
378
|
+
});
|
|
379
|
+
}
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Claude Code 适配器。
|
|
3
|
+
*
|
|
4
|
+
* 全部通过 `claude -p` 非交互调用,使用原生 session ID 支持恢复。
|
|
5
|
+
* 默认带 --dangerously-skip-permissions(用户明确要求最大权限)。
|
|
6
|
+
*
|
|
7
|
+
* 注意:这里的“最大权限”只跳过工具权限弹窗,不等于授权业务决策、提交、
|
|
8
|
+
* 推送或部署——那些仍由调度器按人工决策规则处理。
|
|
9
|
+
*/
|
|
10
|
+
import fs from "node:fs";
|
|
11
|
+
import os from "node:os";
|
|
12
|
+
import path from "node:path";
|
|
13
|
+
import { spawnAgent, killChild } from "./exec.js";
|
|
14
|
+
|
|
15
|
+
export const AGENT_ID = "claude";
|
|
16
|
+
|
|
17
|
+
/** 正在运行的 CLI 进程;重启服务或切换模型时统一中断。 */
|
|
18
|
+
const activeRuns = new Set();
|
|
19
|
+
|
|
20
|
+
export function abortAll() {
|
|
21
|
+
for (const child of activeRuns) killChild(child);
|
|
22
|
+
activeRuns.clear();
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** 从 ~/.claude/settings.json 的 env 补齐认证信息,避免子进程因缺凭证失败。 */
|
|
26
|
+
export function prepareEnv(env = process.env) {
|
|
27
|
+
const next = { ...env };
|
|
28
|
+
if (!next.ANTHROPIC_AUTH_TOKEN && !next.ANTHROPIC_API_KEY) {
|
|
29
|
+
const settingsDir = env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), ".claude");
|
|
30
|
+
const settingsFile = path.join(settingsDir, "settings.json");
|
|
31
|
+
try {
|
|
32
|
+
const parsed = JSON.parse(fs.readFileSync(settingsFile, "utf8"));
|
|
33
|
+
const fileEnv = parsed?.env || {};
|
|
34
|
+
if (!next.ANTHROPIC_AUTH_TOKEN && fileEnv.ANTHROPIC_AUTH_TOKEN) next.ANTHROPIC_AUTH_TOKEN = fileEnv.ANTHROPIC_AUTH_TOKEN;
|
|
35
|
+
if (!next.ANTHROPIC_BASE_URL && fileEnv.ANTHROPIC_BASE_URL) next.ANTHROPIC_BASE_URL = fileEnv.ANTHROPIC_BASE_URL;
|
|
36
|
+
if (!next.ANTHROPIC_API_KEY && fileEnv.ANTHROPIC_API_KEY) next.ANTHROPIC_API_KEY = fileEnv.ANTHROPIC_API_KEY;
|
|
37
|
+
} catch { /* 没有 settings.json 或不可读:交给 CLI 自己处理 */ }
|
|
38
|
+
}
|
|
39
|
+
return next;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function buildArgs({ prompt, sessionId, model, mcpConfig }) {
|
|
43
|
+
const args = ["-p", prompt, "--output-format", "stream-json", "--verbose", "--dangerously-skip-permissions"];
|
|
44
|
+
if (sessionId) args.push("--resume", sessionId);
|
|
45
|
+
if (model) args.push("--model", model);
|
|
46
|
+
if (mcpConfig) args.push("--mcp-config", JSON.stringify(mcpConfig));
|
|
47
|
+
return args;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** 解析 stream-json 行,抽取文本、工具调用与最终结果。 */
|
|
51
|
+
export function parseStreamJson(text) {
|
|
52
|
+
const out = { texts: [], toolCalls: [], result: null, sessionId: null, isError: false, raw: [] };
|
|
53
|
+
for (const line of String(text || "").split("\n")) {
|
|
54
|
+
const t = line.trim();
|
|
55
|
+
if (!t.startsWith("{")) continue;
|
|
56
|
+
let obj;
|
|
57
|
+
try { obj = JSON.parse(t); } catch { continue; }
|
|
58
|
+
out.raw.push(obj);
|
|
59
|
+
if (obj.session_id) out.sessionId = obj.session_id;
|
|
60
|
+
if (obj.type === "assistant" && obj.message?.content) {
|
|
61
|
+
for (const c of obj.message.content) {
|
|
62
|
+
if (c.type === "text" && c.text) out.texts.push(c.text);
|
|
63
|
+
else if (c.type === "tool_use") out.toolCalls.push({ name: c.name, input: c.input });
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
if (obj.type === "result") {
|
|
67
|
+
out.result = obj.result ?? null;
|
|
68
|
+
out.isError = obj.is_error === true || obj.subtype === "error_during_execution";
|
|
69
|
+
if (obj.session_id) out.sessionId = obj.session_id;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
out.text = out.texts.join("\n").trim();
|
|
73
|
+
return out;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* 启动一轮 claude 调用。
|
|
78
|
+
* onEvent 收到 {type:"text"|"tool"|"result"} 增量,用于界面实时展示。
|
|
79
|
+
*/
|
|
80
|
+
export function run({ prompt, cwd, sessionId, model, mcpConfig, env, onEvent, onSpawn, signal, timeoutMs = 60 * 60 * 1000, idleTimeoutMs = 15 * 60 * 1000 }) {
|
|
81
|
+
return new Promise((resolve) => {
|
|
82
|
+
const child = spawnAgent("claude", buildArgs({ prompt, sessionId, model, mcpConfig }), {
|
|
83
|
+
cwd,
|
|
84
|
+
env: prepareEnv(env),
|
|
85
|
+
windowsHide: true,
|
|
86
|
+
onSpawn,
|
|
87
|
+
});
|
|
88
|
+
activeRuns.add(child);
|
|
89
|
+
if (signal?.aborted) {
|
|
90
|
+
killChild(child);
|
|
91
|
+
} else if (signal) {
|
|
92
|
+
signal.addEventListener("abort", () => killChild(child), { once: true });
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
let stdout = "";
|
|
96
|
+
let stderr = "";
|
|
97
|
+
let settled = false;
|
|
98
|
+
let timedOut = false;
|
|
99
|
+
const hardTimer = setTimeout(() => {
|
|
100
|
+
timedOut = true;
|
|
101
|
+
killChild(child);
|
|
102
|
+
}, timeoutMs);
|
|
103
|
+
// 空闲看门狗:长时间没有任何输出说明会话已卡死,直接中断交给上层重试
|
|
104
|
+
let idleTimer = null;
|
|
105
|
+
const resetIdle = () => {
|
|
106
|
+
clearTimeout(idleTimer);
|
|
107
|
+
idleTimer = setTimeout(() => {
|
|
108
|
+
timedOut = true;
|
|
109
|
+
killChild(child);
|
|
110
|
+
}, idleTimeoutMs);
|
|
111
|
+
};
|
|
112
|
+
resetIdle();
|
|
113
|
+
|
|
114
|
+
child.stdout.on("data", d => { stdout += d.toString(); resetIdle(); onEvent?.({ type: "raw", chunk: d.toString() }); });
|
|
115
|
+
child.stderr.on("data", d => { stderr += d.toString(); resetIdle(); });
|
|
116
|
+
|
|
117
|
+
const finish = (code, signal) => {
|
|
118
|
+
if (settled) return;
|
|
119
|
+
settled = true;
|
|
120
|
+
activeRuns.delete(child);
|
|
121
|
+
clearTimeout(hardTimer);
|
|
122
|
+
clearTimeout(idleTimer);
|
|
123
|
+
const parsed = parseStreamJson(stdout);
|
|
124
|
+
onEvent?.({ type: "result", parsed });
|
|
125
|
+
resolve({
|
|
126
|
+
ok: code === 0 && !parsed.isError && !timedOut,
|
|
127
|
+
exitCode: code,
|
|
128
|
+
signal,
|
|
129
|
+
timedOut,
|
|
130
|
+
idleTimeoutMs,
|
|
131
|
+
sessionId: parsed.sessionId || sessionId || null,
|
|
132
|
+
text: parsed.text,
|
|
133
|
+
result: parsed.result,
|
|
134
|
+
toolCalls: parsed.toolCalls,
|
|
135
|
+
stderr: stderr.slice(-4000),
|
|
136
|
+
stdout: stdout.slice(-20000),
|
|
137
|
+
});
|
|
138
|
+
};
|
|
139
|
+
|
|
140
|
+
child.on("error", e => { stderr += String(e?.message || e); finish(null, null); });
|
|
141
|
+
child.on("close", (code, signal) => finish(code, signal));
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
export function isAvailable() {
|
|
146
|
+
return true;
|
|
147
|
+
}
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OpenAI Codex CLI 适配器(`codex exec`)。
|
|
3
|
+
*
|
|
4
|
+
* 非交互调用:codex exec --json --dangerously-bypass-approvals-and-sandbox,
|
|
5
|
+
* 会话用 `codex exec resume <thread_id>` 续接,模型用 -m/--model。
|
|
6
|
+
*
|
|
7
|
+
* MCP 注入不写用户的 ~/.codex/config.toml:Codex 支持 `-c mcp_servers.<name>.<key>=<TOML>`
|
|
8
|
+
* 单次覆盖,把 adev-autofix 桥作为 stdio server 直接通过命令行参数传入即可,
|
|
9
|
+
* 运行结束不留任何痕迹。
|
|
10
|
+
*
|
|
11
|
+
* 输出是 JSONL 事件流(thread.started / item.* / turn.completed / error ...);
|
|
12
|
+
* 这里解析成与 claude.js 一致的 { ok, text, sessionId, toolCalls, ... }。
|
|
13
|
+
*/
|
|
14
|
+
import { spawnAgent, killChild } from "./exec.js";
|
|
15
|
+
|
|
16
|
+
export const AGENT_ID = "codex";
|
|
17
|
+
/** 命令名候选:npm 包 @openai/codex 的 bin 就是 codex。 */
|
|
18
|
+
export const COMMANDS = ["codex"];
|
|
19
|
+
|
|
20
|
+
const activeRuns = new Set();
|
|
21
|
+
|
|
22
|
+
export function abortAll() {
|
|
23
|
+
for (const child of activeRuns) killChild(child);
|
|
24
|
+
activeRuns.clear();
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** TOML 字符串字面量:JSON.stringify 恰好也是合法 TOML 基本字符串。 */
|
|
28
|
+
function tomlString(value) {
|
|
29
|
+
return JSON.stringify(String(value ?? ""));
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* 把 bridge.buildMcpConfig 的 mcpServers.adev-autofix 转成 -c 覆盖参数。
|
|
34
|
+
* server 名用下划线:带连字符的 key 在 TOML 里会被当成减法表达式。
|
|
35
|
+
* Codex 允许 MCP server 名含连字符,但用 -c 注入时下划线最稳妥。
|
|
36
|
+
*/
|
|
37
|
+
export function buildMcpOverrides(mcpConfig) {
|
|
38
|
+
const server = mcpConfig?.mcpServers?.["adev-autofix"];
|
|
39
|
+
if (!server) return [];
|
|
40
|
+
const command = server.command || process.execPath;
|
|
41
|
+
const args = Array.isArray(server.args) ? server.args : [];
|
|
42
|
+
const base = `mcp_servers.adev_autofix`;
|
|
43
|
+
return [
|
|
44
|
+
"-c", `${base}.command=${tomlString(command)}`,
|
|
45
|
+
"-c", `${base}.args=[${args.map(tomlString).join(", ")}]`,
|
|
46
|
+
];
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* 构造 codex exec 的参数。
|
|
51
|
+
* 注意 `codex exec resume` 的选项集合比 `codex exec` 少:不支持 -C / --color,
|
|
52
|
+
* 工作目录改由 child_process 的 cwd 传入;-c / --json / --skip-git-repo-check 均支持。
|
|
53
|
+
*/
|
|
54
|
+
export function buildArgs({ prompt, sessionId, model, mcpConfig, cwd }) {
|
|
55
|
+
const common = [
|
|
56
|
+
...buildMcpOverrides(mcpConfig),
|
|
57
|
+
"--json",
|
|
58
|
+
"--skip-git-repo-check",
|
|
59
|
+
"--dangerously-bypass-approvals-and-sandbox",
|
|
60
|
+
];
|
|
61
|
+
if (model) common.push("-m", model);
|
|
62
|
+
|
|
63
|
+
if (sessionId) {
|
|
64
|
+
return ["exec", "resume", ...common, sessionId, prompt];
|
|
65
|
+
}
|
|
66
|
+
// 仅首次执行支持 -C / --color;cwd 同时由 child_process 传入,双保险
|
|
67
|
+
const first = ["exec", ...common, "--color", "never"];
|
|
68
|
+
if (cwd) first.push("-C", cwd);
|
|
69
|
+
return [...first, prompt];
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** 解析 codex --json 事件流。 */
|
|
73
|
+
export function parseStreamJson(text) {
|
|
74
|
+
const out = { texts: [], toolCalls: [], result: null, sessionId: null, isError: false, error: null };
|
|
75
|
+
for (const line of String(text || "").split(/\r?\n/)) {
|
|
76
|
+
const t = line.trim();
|
|
77
|
+
if (!t.startsWith("{")) continue;
|
|
78
|
+
let obj;
|
|
79
|
+
try { obj = JSON.parse(t); } catch { continue; }
|
|
80
|
+
|
|
81
|
+
if (obj.type === "thread.started" && obj.thread_id) out.sessionId = obj.thread_id;
|
|
82
|
+
if (obj.type === "error" || obj.type === "turn.failed") {
|
|
83
|
+
out.isError = true;
|
|
84
|
+
out.error = String(obj.message || obj.error?.message || "");
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const item = obj.item;
|
|
88
|
+
if (!item || typeof item !== "object") continue;
|
|
89
|
+
const type = String(item.type || "");
|
|
90
|
+
if (type === "agent_message" && item.text) out.texts.push(String(item.text));
|
|
91
|
+
if (type === "command_execution") {
|
|
92
|
+
out.toolCalls.push({ name: "bash", input: { command: item.command || "", output: item.aggregated_output || "" } });
|
|
93
|
+
}
|
|
94
|
+
if (type === "file_change") {
|
|
95
|
+
out.toolCalls.push({ name: "edit", input: { path: (item.changes || [])[0]?.path || "" } });
|
|
96
|
+
}
|
|
97
|
+
if (type === "mcp_tool_call" || type === "function_call") {
|
|
98
|
+
out.toolCalls.push({ name: item.name || item.tool || "tool", input: item.arguments || item.input || {} });
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
out.text = out.texts.join("\n").trim();
|
|
102
|
+
out.result = out.text || null;
|
|
103
|
+
return out;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* 启动一轮 codex 调用。
|
|
108
|
+
* onEvent 的 raw chunk 供 coordinator 实时展示与识别任务阶段。
|
|
109
|
+
*/
|
|
110
|
+
export function run({ prompt, cwd, sessionId, model, mcpConfig, env, onEvent, onSpawn, signal, timeoutMs = 60 * 60 * 1000, idleTimeoutMs = 15 * 60 * 1000 }) {
|
|
111
|
+
return new Promise((resolve) => {
|
|
112
|
+
const args = buildArgs({ prompt, sessionId, model, mcpConfig, cwd });
|
|
113
|
+
const child = spawnAgent("codex", args, {
|
|
114
|
+
cwd,
|
|
115
|
+
env: env || process.env,
|
|
116
|
+
windowsHide: true,
|
|
117
|
+
onSpawn,
|
|
118
|
+
// 必须给一个已关闭的 stdin:codex 在未检测到管道时会打印
|
|
119
|
+
// "Reading additional input from stdin..." 并等待输入。
|
|
120
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
121
|
+
});
|
|
122
|
+
activeRuns.add(child);
|
|
123
|
+
if (signal?.aborted) {
|
|
124
|
+
killChild(child);
|
|
125
|
+
} else if (signal) {
|
|
126
|
+
signal.addEventListener("abort", () => killChild(child), { once: true });
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
let stdout = "";
|
|
130
|
+
let stderr = "";
|
|
131
|
+
let settled = false;
|
|
132
|
+
let timedOut = false;
|
|
133
|
+
const hardTimer = setTimeout(() => {
|
|
134
|
+
timedOut = true;
|
|
135
|
+
killChild(child);
|
|
136
|
+
}, timeoutMs);
|
|
137
|
+
let idleTimer = null;
|
|
138
|
+
const resetIdle = () => {
|
|
139
|
+
clearTimeout(idleTimer);
|
|
140
|
+
idleTimer = setTimeout(() => {
|
|
141
|
+
timedOut = true;
|
|
142
|
+
killChild(child);
|
|
143
|
+
}, idleTimeoutMs);
|
|
144
|
+
};
|
|
145
|
+
resetIdle();
|
|
146
|
+
|
|
147
|
+
child.stdout.on("data", d => {
|
|
148
|
+
stdout += d.toString();
|
|
149
|
+
resetIdle();
|
|
150
|
+
onEvent?.({ type: "raw", chunk: d.toString() });
|
|
151
|
+
});
|
|
152
|
+
child.stderr.on("data", d => { stderr += d.toString(); resetIdle(); });
|
|
153
|
+
|
|
154
|
+
const finish = (code) => {
|
|
155
|
+
if (settled) return;
|
|
156
|
+
settled = true;
|
|
157
|
+
activeRuns.delete(child);
|
|
158
|
+
clearTimeout(hardTimer);
|
|
159
|
+
clearTimeout(idleTimer);
|
|
160
|
+
const parsed = parseStreamJson(stdout);
|
|
161
|
+
onEvent?.({ type: "result", parsed });
|
|
162
|
+
resolve({
|
|
163
|
+
ok: code === 0 && !parsed.isError && !timedOut,
|
|
164
|
+
exitCode: code,
|
|
165
|
+
timedOut,
|
|
166
|
+
idleTimeoutMs,
|
|
167
|
+
sessionId: parsed.sessionId || sessionId || null,
|
|
168
|
+
text: parsed.text,
|
|
169
|
+
result: parsed.result,
|
|
170
|
+
toolCalls: parsed.toolCalls,
|
|
171
|
+
stderr: stderr.slice(-4000),
|
|
172
|
+
stdout: stdout.slice(-20000),
|
|
173
|
+
});
|
|
174
|
+
};
|
|
175
|
+
|
|
176
|
+
child.on("error", e => { stderr += String(e?.message || e); finish(null); });
|
|
177
|
+
child.on("close", code => finish(code));
|
|
178
|
+
});
|
|
179
|
+
}
|