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,233 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OpenCode 适配器。
|
|
3
|
+
*
|
|
4
|
+
* 使用 `opencode run` 非交互调用,--session 续接同一会话,--auto 自动批准权限。
|
|
5
|
+
*
|
|
6
|
+
* 关键点:
|
|
7
|
+
* - `--standalone` 让每次调用使用独立进程内配置。否则 run 会连到后台常驻服务,
|
|
8
|
+
* 后台服务读的是磁盘配置,本次注入的 MCP 工具不会生效。
|
|
9
|
+
* - OpenCode v2 的 MCP 配置结构是 `{ mcp: { servers: { name: {...} } } }`,
|
|
10
|
+
* 通过 OPENCODE_CONFIG_CONTENT 作为虚拟配置源合并进现有配置。
|
|
11
|
+
* - 输出为 NDJSON 实时流,事件顶层带 sessionID,用它保存会话才能续接。
|
|
12
|
+
*/
|
|
13
|
+
import { spawnAgent, killChild } from "./exec.js";
|
|
14
|
+
|
|
15
|
+
export const AGENT_ID = "opencode";
|
|
16
|
+
|
|
17
|
+
/** MCP 服务器在配置里的名字,必须和 bridge.buildMcpConfig 保持一致。 */
|
|
18
|
+
export const MCP_SERVER_NAME = "adev-autofix";
|
|
19
|
+
|
|
20
|
+
/** 正在运行的 CLI 进程;重启服务或切换模型时统一中断。 */
|
|
21
|
+
const activeRuns = new Set();
|
|
22
|
+
|
|
23
|
+
export function abortAll() {
|
|
24
|
+
for (const child of activeRuns) killChild(child);
|
|
25
|
+
activeRuns.clear();
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function buildArgs({ prompt, sessionId, model, auto = true }) {
|
|
29
|
+
const args = ["run", "--standalone", "--format", "json"];
|
|
30
|
+
if (auto) args.push("--auto");
|
|
31
|
+
if (sessionId) args.push("--session", sessionId);
|
|
32
|
+
if (model) args.push("--model", model);
|
|
33
|
+
args.push(prompt);
|
|
34
|
+
return args;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** 把 bridge.buildMcpConfig 的结果转换成 OpenCode v2 的 MCP 条目。 */
|
|
38
|
+
function mcpServerFromConfig(mcpConfig) {
|
|
39
|
+
const server = mcpConfig?.mcpServers?.[MCP_SERVER_NAME];
|
|
40
|
+
if (!server) return null;
|
|
41
|
+
const command = Array.isArray(server.command)
|
|
42
|
+
? server.command
|
|
43
|
+
: [server.command || process.execPath, ...(server.args || [])];
|
|
44
|
+
if (!command.length || !command[0]) return null;
|
|
45
|
+
return {
|
|
46
|
+
type: "local",
|
|
47
|
+
command,
|
|
48
|
+
environment: server.env && typeof server.env === "object" ? server.env : {},
|
|
49
|
+
disabled: false,
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* 构造子进程环境变量:在用户已有 OPENCODE_CONFIG_CONTENT 之上合并 MCP 配置。
|
|
55
|
+
* 解析失败时保留用户原值,绝不静默覆盖。
|
|
56
|
+
*/
|
|
57
|
+
export function buildEnv({ env = process.env, mcpConfig } = {}) {
|
|
58
|
+
const next = { ...env };
|
|
59
|
+
const server = mcpServerFromConfig(mcpConfig);
|
|
60
|
+
if (!server) return next;
|
|
61
|
+
|
|
62
|
+
let base = {};
|
|
63
|
+
if (next.OPENCODE_CONFIG_CONTENT) {
|
|
64
|
+
try {
|
|
65
|
+
const parsed = JSON.parse(next.OPENCODE_CONFIG_CONTENT);
|
|
66
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) base = parsed;
|
|
67
|
+
} catch {
|
|
68
|
+
// 用户配置不是合法 JSON:不碰它,避免把原有配置弄坏
|
|
69
|
+
return next;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const config = { ...base };
|
|
74
|
+
config.mcp = { ...(base.mcp && typeof base.mcp === "object" ? base.mcp : {}) };
|
|
75
|
+
config.mcp.servers = {
|
|
76
|
+
...(config.mcp.servers && typeof config.mcp.servers === "object" ? config.mcp.servers : {}),
|
|
77
|
+
[MCP_SERVER_NAME]: server,
|
|
78
|
+
};
|
|
79
|
+
next.OPENCODE_CONFIG_CONTENT = JSON.stringify(config);
|
|
80
|
+
return next;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function eventSessionId(obj) {
|
|
84
|
+
const candidates = [
|
|
85
|
+
obj?.sessionID,
|
|
86
|
+
obj?.session_id,
|
|
87
|
+
obj?.part?.sessionID,
|
|
88
|
+
obj?.properties?.sessionID,
|
|
89
|
+
obj?.message?.sessionID,
|
|
90
|
+
];
|
|
91
|
+
for (const v of candidates) if (typeof v === "string" && v) return v;
|
|
92
|
+
return null;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** 从 OpenCode 的 NDJSON / 纯文本输出中抽取结果文本、工具调用与会话 ID。 */
|
|
96
|
+
export function parseOutput(stdout) {
|
|
97
|
+
const raw = String(stdout || "").trim();
|
|
98
|
+
if (!raw) return { text: "", events: [], toolCalls: [], sessionId: null, ok: true };
|
|
99
|
+
|
|
100
|
+
const events = [];
|
|
101
|
+
const chunks = [];
|
|
102
|
+
const toolCalls = [];
|
|
103
|
+
let ok = true;
|
|
104
|
+
let sessionId = null;
|
|
105
|
+
|
|
106
|
+
const push = (obj) => {
|
|
107
|
+
if (!obj || typeof obj !== "object") return;
|
|
108
|
+
events.push(obj);
|
|
109
|
+
const sid = eventSessionId(obj);
|
|
110
|
+
if (sid) sessionId = sid;
|
|
111
|
+
|
|
112
|
+
// 错误事件优先:即便后面还有半截文本,也不能当成功
|
|
113
|
+
if (obj.type === "error" || obj.error) ok = false;
|
|
114
|
+
|
|
115
|
+
const part = obj.part;
|
|
116
|
+
// 只收正文:reasoning(思考)块不进入最终回答
|
|
117
|
+
if (obj.type === "text" && typeof part?.text === "string") chunks.push(part.text);
|
|
118
|
+
else if (obj.type === "text" && typeof obj.text === "string") chunks.push(obj.text);
|
|
119
|
+
else if (part?.type === "text" && typeof part.text === "string") chunks.push(part.text);
|
|
120
|
+
else if (typeof obj.message?.content === "string") chunks.push(obj.message.content);
|
|
121
|
+
else if (typeof obj.content === "string" && !part) chunks.push(obj.content);
|
|
122
|
+
|
|
123
|
+
if (obj.type === "tool_use" || part?.type === "tool") {
|
|
124
|
+
const name = part?.tool || part?.name || obj.name || obj.tool || "tool";
|
|
125
|
+
toolCalls.push({ name, input: part?.state?.input ?? obj.input ?? null });
|
|
126
|
+
}
|
|
127
|
+
};
|
|
128
|
+
|
|
129
|
+
for (const line of raw.split(/\r?\n/)) {
|
|
130
|
+
const t = line.trim();
|
|
131
|
+
if (!t.startsWith("{") && !t.startsWith("[")) continue;
|
|
132
|
+
try {
|
|
133
|
+
const obj = JSON.parse(t);
|
|
134
|
+
if (Array.isArray(obj)) obj.forEach(push);
|
|
135
|
+
else push(obj);
|
|
136
|
+
} catch {
|
|
137
|
+
// 整段就是一个 JSON 文档(多行格式化输出)
|
|
138
|
+
try {
|
|
139
|
+
const obj = JSON.parse(raw);
|
|
140
|
+
if (Array.isArray(obj)) obj.forEach(push);
|
|
141
|
+
else push(obj);
|
|
142
|
+
} catch { /* 纯文本输出 */ }
|
|
143
|
+
break;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
const joined = chunks.join("\n").trim();
|
|
148
|
+
if (events.length) return { text: joined, events, toolCalls, sessionId, ok };
|
|
149
|
+
return { text: raw, events, toolCalls, sessionId, ok };
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
export function run({ prompt, cwd, sessionId, model, mcpConfig, env, onEvent, onSpawn, signal, timeoutMs = 60 * 60 * 1000, idleTimeoutMs = 15 * 60 * 1000 }) {
|
|
153
|
+
return new Promise((resolve) => {
|
|
154
|
+
let child;
|
|
155
|
+
try {
|
|
156
|
+
child = spawnAgent("opencode", buildArgs({ prompt, sessionId, model }), {
|
|
157
|
+
cwd,
|
|
158
|
+
env: buildEnv({ env: env ?? process.env, mcpConfig }),
|
|
159
|
+
windowsHide: true,
|
|
160
|
+
onSpawn,
|
|
161
|
+
});
|
|
162
|
+
} catch (e) {
|
|
163
|
+
resolve({
|
|
164
|
+
ok: false,
|
|
165
|
+
exitCode: null,
|
|
166
|
+
signal: null,
|
|
167
|
+
timedOut: false,
|
|
168
|
+
idleTimeoutMs,
|
|
169
|
+
sessionId: sessionId || null,
|
|
170
|
+
text: "",
|
|
171
|
+
result: "",
|
|
172
|
+
toolCalls: [],
|
|
173
|
+
stderr: String(e?.message || e),
|
|
174
|
+
stdout: "",
|
|
175
|
+
});
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
activeRuns.add(child);
|
|
179
|
+
if (signal?.aborted) {
|
|
180
|
+
killChild(child);
|
|
181
|
+
} else if (signal) {
|
|
182
|
+
signal.addEventListener("abort", () => killChild(child), { once: true });
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
let stdout = "";
|
|
186
|
+
let stderr = "";
|
|
187
|
+
let settled = false;
|
|
188
|
+
let timedOut = false;
|
|
189
|
+
const hardTimer = setTimeout(() => {
|
|
190
|
+
timedOut = true;
|
|
191
|
+
killChild(child);
|
|
192
|
+
}, timeoutMs);
|
|
193
|
+
// 空闲看门狗:长时间没有任何输出说明会话已卡死
|
|
194
|
+
let idleTimer = null;
|
|
195
|
+
const resetIdle = () => {
|
|
196
|
+
clearTimeout(idleTimer);
|
|
197
|
+
idleTimer = setTimeout(() => {
|
|
198
|
+
timedOut = true;
|
|
199
|
+
killChild(child);
|
|
200
|
+
}, idleTimeoutMs);
|
|
201
|
+
};
|
|
202
|
+
resetIdle();
|
|
203
|
+
|
|
204
|
+
child.stdout.on("data", d => { stdout += d.toString(); resetIdle(); onEvent?.({ type: "raw", chunk: d.toString() }); });
|
|
205
|
+
child.stderr.on("data", d => { stderr += d.toString(); resetIdle(); });
|
|
206
|
+
|
|
207
|
+
const finish = (code, signal) => {
|
|
208
|
+
if (settled) return;
|
|
209
|
+
settled = true;
|
|
210
|
+
activeRuns.delete(child);
|
|
211
|
+
clearTimeout(hardTimer);
|
|
212
|
+
clearTimeout(idleTimer);
|
|
213
|
+
const parsed = parseOutput(stdout);
|
|
214
|
+
onEvent?.({ type: "result", parsed });
|
|
215
|
+
resolve({
|
|
216
|
+
ok: code === 0 && parsed.ok !== false && !timedOut,
|
|
217
|
+
exitCode: code,
|
|
218
|
+
signal,
|
|
219
|
+
timedOut,
|
|
220
|
+
idleTimeoutMs,
|
|
221
|
+
sessionId: parsed.sessionId || sessionId || null,
|
|
222
|
+
text: parsed.text,
|
|
223
|
+
result: parsed.text,
|
|
224
|
+
toolCalls: parsed.toolCalls,
|
|
225
|
+
stderr: stderr.slice(-4000),
|
|
226
|
+
stdout: stdout.slice(-20000),
|
|
227
|
+
});
|
|
228
|
+
};
|
|
229
|
+
|
|
230
|
+
child.on("error", e => { stderr += String(e?.message || e); finish(null, null); });
|
|
231
|
+
child.on("close", (code, signal) => finish(code, signal));
|
|
232
|
+
});
|
|
233
|
+
}
|
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pi coding agent 适配器(`pi -p --mode json`)。
|
|
3
|
+
*
|
|
4
|
+
* 非交互调用:`pi -p --mode json --model <id> --session-id <id> -- <prompt>`。
|
|
5
|
+
* JSON 模式输出 JSONL 事件(session / message_end / turn_end / tool_execution_* / agent_settled),
|
|
6
|
+
* 这里解析成与 claude.js 一致的 { ok, text, sessionId, toolCalls, ... }。
|
|
7
|
+
*
|
|
8
|
+
* MCP 注入:Pi 从 `<agent-dir>/mcp.json` 读 MCP server。为避免改动用户全局配置,
|
|
9
|
+
* 每次运行创建一个临时 agent dir,只把 adev-autofix 写进 mcp.json;用户的
|
|
10
|
+
* auth.json / models.json / models-store.json / trust.json 通过符号链接(Windows
|
|
11
|
+
* 上降级为复制)复用,这样登录态、自定义模型与项目信任都保持有效。
|
|
12
|
+
* 临时目录在进程结束后删除。
|
|
13
|
+
*
|
|
14
|
+
* 会话不能放在这个临时目录里(删掉后 --session-id 就续接不上了),
|
|
15
|
+
* 因此用 PI_CODING_AGENT_SESSION_DIR 指回用户真实的 sessions 目录。
|
|
16
|
+
*/
|
|
17
|
+
import fs from "node:fs";
|
|
18
|
+
import os from "node:os";
|
|
19
|
+
import path from "node:path";
|
|
20
|
+
import crypto from "node:crypto";
|
|
21
|
+
import { spawnAgent, killChild } from "./exec.js";
|
|
22
|
+
|
|
23
|
+
export const AGENT_ID = "pi";
|
|
24
|
+
/** 命令名候选:官方安装器提供的 bin 就是 pi。 */
|
|
25
|
+
export const COMMANDS = ["pi"];
|
|
26
|
+
|
|
27
|
+
const activeRuns = new Set();
|
|
28
|
+
|
|
29
|
+
export function abortAll() {
|
|
30
|
+
for (const child of activeRuns) killChild(child);
|
|
31
|
+
activeRuns.clear();
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** 从 buildMcpConfig 的结果转成 pi 的 mcpServers 条目。 */
|
|
35
|
+
export function mcpServerFromConfig(mcpConfig) {
|
|
36
|
+
const server = mcpConfig?.mcpServers?.["adev-autofix"];
|
|
37
|
+
if (!server) return null;
|
|
38
|
+
return {
|
|
39
|
+
command: server.command || process.execPath,
|
|
40
|
+
args: Array.isArray(server.args) ? server.args : [],
|
|
41
|
+
...(server.env && typeof server.env === "object" ? { env: server.env } : {}),
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* 创建一次性 agent dir:只写 mcp.json,其它配置尽量复用用户的。
|
|
47
|
+
* 返回 { dir, cleanup };dir 为 null 时表示无法隔离(调用方会退回用户配置)。
|
|
48
|
+
*/
|
|
49
|
+
export function prepareAgentDir(mcpConfig, env = process.env) {
|
|
50
|
+
const server = mcpServerFromConfig(mcpConfig);
|
|
51
|
+
const base = env.PI_CODING_AGENT_DIR || path.join(os.homedir(), ".pi", "agent");
|
|
52
|
+
if (!server) return { dir: null, sessionDir: null, cleanup: () => {} };
|
|
53
|
+
|
|
54
|
+
const sessionDir = env.PI_CODING_AGENT_SESSION_DIR || path.join(base, "sessions");
|
|
55
|
+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "adev-pi-agent-"));
|
|
56
|
+
try {
|
|
57
|
+
fs.writeFileSync(path.join(dir, "mcp.json"), JSON.stringify({
|
|
58
|
+
mcpServers: { "adev-autofix": server },
|
|
59
|
+
}, null, 2));
|
|
60
|
+
// 登录凭证、模型目录、项目信任、用户设置都不该因为一次派工而丢失
|
|
61
|
+
for (const name of ["auth.json", "models.json", "models-store.json", "trust.json", "settings.json"]) {
|
|
62
|
+
const src = path.join(base, name);
|
|
63
|
+
if (!fs.existsSync(src)) continue;
|
|
64
|
+
try {
|
|
65
|
+
fs.symlinkSync(src, path.join(dir, name), "file");
|
|
66
|
+
} catch {
|
|
67
|
+
// 非管理员的 Windows 创建符号链接可能失败,退化为复制
|
|
68
|
+
try { fs.copyFileSync(src, path.join(dir, name)); } catch { /* 单个文件失败不阻断 */ }
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
// 用户自己安装的扩展/技能:目录级链接,失败时忽略(不影响派工)
|
|
72
|
+
for (const name of ["extensions", "skills"]) {
|
|
73
|
+
const src = path.join(base, name);
|
|
74
|
+
if (!fs.existsSync(src)) continue;
|
|
75
|
+
try { fs.symlinkSync(src, path.join(dir, name), "dir"); } catch { /* 忽略 */ }
|
|
76
|
+
}
|
|
77
|
+
} catch (e) {
|
|
78
|
+
try { fs.rmSync(dir, { recursive: true, force: true }); } catch { /* 忽略 */ }
|
|
79
|
+
return { dir: null, sessionDir: null, cleanup: () => {} };
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
return {
|
|
83
|
+
dir,
|
|
84
|
+
sessionDir,
|
|
85
|
+
cleanup: () => {
|
|
86
|
+
try { fs.rmSync(dir, { recursive: true, force: true }); } catch { /* 忽略 */ }
|
|
87
|
+
},
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* 构造参数。prompt 放在 `--` 之后,避免以 - 开头的提示词被当成选项。
|
|
93
|
+
* 始终带 --session-id:首轮由调用方生成,后续原样续接,避免 --no-session
|
|
94
|
+
* 产生的一次性会话无法在下一轮恢复。
|
|
95
|
+
*/
|
|
96
|
+
export function buildArgs({ prompt, sessionId, model }) {
|
|
97
|
+
const args = ["-p", "--mode", "json"];
|
|
98
|
+
if (model) args.push("--model", model);
|
|
99
|
+
args.push("--session-id", sessionId || "adev-autofix");
|
|
100
|
+
args.push("--", prompt);
|
|
101
|
+
return args;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** 从 message.content 数组里抽取文本。 */
|
|
105
|
+
function contentText(message) {
|
|
106
|
+
const content = message?.content;
|
|
107
|
+
if (typeof content === "string") return content;
|
|
108
|
+
if (!Array.isArray(content)) return "";
|
|
109
|
+
return content
|
|
110
|
+
.filter(b => b && b.type === "text" && typeof b.text === "string")
|
|
111
|
+
.map(b => b.text)
|
|
112
|
+
.join("");
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** 解析 pi 的 JSONL 事件流。 */
|
|
116
|
+
export function parseStreamJson(text) {
|
|
117
|
+
const out = { texts: [], toolCalls: [], result: null, sessionId: null, isError: false, error: null };
|
|
118
|
+
let finalText = "";
|
|
119
|
+
|
|
120
|
+
for (const line of String(text || "").split(/\r?\n/)) {
|
|
121
|
+
const t = line.trim();
|
|
122
|
+
if (!t.startsWith("{")) continue;
|
|
123
|
+
let obj;
|
|
124
|
+
try { obj = JSON.parse(t); } catch { continue; }
|
|
125
|
+
|
|
126
|
+
if (obj.type === "session" && obj.id) out.sessionId = obj.id;
|
|
127
|
+
|
|
128
|
+
if (obj.type === "message_end" && obj.message?.role === "assistant") {
|
|
129
|
+
const msg = obj.message;
|
|
130
|
+
const piece = contentText(msg);
|
|
131
|
+
if (piece) out.texts.push(piece);
|
|
132
|
+
const stop = String(msg.stopReason || "");
|
|
133
|
+
if (stop === "error" || stop === "aborted") {
|
|
134
|
+
out.isError = true;
|
|
135
|
+
out.error = String(msg.errorMessage || stop);
|
|
136
|
+
}
|
|
137
|
+
if (Array.isArray(msg.content)) {
|
|
138
|
+
for (const block of msg.content) {
|
|
139
|
+
if (block?.type === "toolCall") {
|
|
140
|
+
out.toolCalls.push({ name: block.name || "tool", input: block.arguments || {} });
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
if (obj.type === "turn_end" && obj.message?.role === "assistant") {
|
|
147
|
+
finalText = contentText(obj.message) || finalText;
|
|
148
|
+
const stop = String(obj.message.stopReason || "");
|
|
149
|
+
if (stop === "error" || stop === "aborted") {
|
|
150
|
+
out.isError = true;
|
|
151
|
+
out.error = out.error || String(obj.message.errorMessage || stop);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
if (obj.type === "tool_execution_start") {
|
|
156
|
+
out.toolCalls.push({ name: obj.toolName || "tool", input: obj.args || {} });
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// turn_end 的 message 是权威最终回答,避免把每一轮的中间文本全部拼进去
|
|
161
|
+
out.text = (finalText || out.texts.join("\n")).trim();
|
|
162
|
+
out.result = out.text || null;
|
|
163
|
+
return out;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* 启动一轮 pi 调用。
|
|
168
|
+
*/
|
|
169
|
+
export function run({ prompt, cwd, sessionId, model, mcpConfig, env, onEvent, onSpawn, signal, timeoutMs = 60 * 60 * 1000, idleTimeoutMs = 15 * 60 * 1000 }) {
|
|
170
|
+
return new Promise((resolve) => {
|
|
171
|
+
const baseEnv = env || process.env;
|
|
172
|
+
const prepared = prepareAgentDir(mcpConfig, baseEnv);
|
|
173
|
+
// Pi 的 --session-id 要求以字母/数字开头结尾;首轮生成一个供后续续接
|
|
174
|
+
const effectiveSessionId = sessionId || `adev-${crypto.randomBytes(6).toString("hex")}`;
|
|
175
|
+
const childEnv = prepared.dir
|
|
176
|
+
? {
|
|
177
|
+
...baseEnv,
|
|
178
|
+
PI_CODING_AGENT_DIR: prepared.dir,
|
|
179
|
+
PI_CODING_AGENT_SESSION_DIR: prepared.sessionDir,
|
|
180
|
+
}
|
|
181
|
+
: baseEnv;
|
|
182
|
+
const child = spawnAgent("pi", buildArgs({ prompt, sessionId: effectiveSessionId, model }), {
|
|
183
|
+
cwd,
|
|
184
|
+
env: childEnv,
|
|
185
|
+
windowsHide: true,
|
|
186
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
187
|
+
onSpawn,
|
|
188
|
+
});
|
|
189
|
+
activeRuns.add(child);
|
|
190
|
+
if (signal?.aborted) {
|
|
191
|
+
killChild(child);
|
|
192
|
+
} else if (signal) {
|
|
193
|
+
signal.addEventListener("abort", () => killChild(child), { once: true });
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
let stdout = "";
|
|
197
|
+
let stderr = "";
|
|
198
|
+
let settled = false;
|
|
199
|
+
let timedOut = false;
|
|
200
|
+
const hardTimer = setTimeout(() => {
|
|
201
|
+
timedOut = true;
|
|
202
|
+
killChild(child);
|
|
203
|
+
}, timeoutMs);
|
|
204
|
+
let idleTimer = null;
|
|
205
|
+
const resetIdle = () => {
|
|
206
|
+
clearTimeout(idleTimer);
|
|
207
|
+
idleTimer = setTimeout(() => {
|
|
208
|
+
timedOut = true;
|
|
209
|
+
killChild(child);
|
|
210
|
+
}, idleTimeoutMs);
|
|
211
|
+
};
|
|
212
|
+
resetIdle();
|
|
213
|
+
|
|
214
|
+
child.stdout.on("data", d => {
|
|
215
|
+
stdout += d.toString();
|
|
216
|
+
resetIdle();
|
|
217
|
+
onEvent?.({ type: "raw", chunk: d.toString() });
|
|
218
|
+
});
|
|
219
|
+
child.stderr.on("data", d => { stderr += d.toString(); resetIdle(); });
|
|
220
|
+
|
|
221
|
+
const finish = (code) => {
|
|
222
|
+
if (settled) return;
|
|
223
|
+
settled = true;
|
|
224
|
+
activeRuns.delete(child);
|
|
225
|
+
clearTimeout(hardTimer);
|
|
226
|
+
clearTimeout(idleTimer);
|
|
227
|
+
prepared.cleanup();
|
|
228
|
+
const parsed = parseStreamJson(stdout);
|
|
229
|
+
onEvent?.({ type: "result", parsed });
|
|
230
|
+
resolve({
|
|
231
|
+
ok: code === 0 && !parsed.isError && !timedOut,
|
|
232
|
+
exitCode: code,
|
|
233
|
+
timedOut,
|
|
234
|
+
idleTimeoutMs,
|
|
235
|
+
sessionId: parsed.sessionId || effectiveSessionId || null,
|
|
236
|
+
text: parsed.text,
|
|
237
|
+
result: parsed.result,
|
|
238
|
+
toolCalls: parsed.toolCalls,
|
|
239
|
+
stderr: stderr.slice(-4000),
|
|
240
|
+
stdout: stdout.slice(-20000),
|
|
241
|
+
});
|
|
242
|
+
};
|
|
243
|
+
|
|
244
|
+
child.on("error", e => { stderr += String(e?.message || e); finish(null); });
|
|
245
|
+
child.on("close", code => finish(code));
|
|
246
|
+
});
|
|
247
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AgileDev 只读/写接口适配层。
|
|
3
|
+
*
|
|
4
|
+
* 复用 adev.js 已有的 HTTP 层与鉴权配置,不另起进程、不解析终端表格。
|
|
5
|
+
* 依赖注入便于测试时替换成假 API。
|
|
6
|
+
*/
|
|
7
|
+
import { loadConfig, api, post, asItems } from "../adev.js";
|
|
8
|
+
|
|
9
|
+
export const BUG_STATUS = Object.freeze({
|
|
10
|
+
PENDING: "Pending",
|
|
11
|
+
IN_PROGRESS: "InProgress",
|
|
12
|
+
TO_VERIFY: "ToVerify",
|
|
13
|
+
REOPENED: "Reopened",
|
|
14
|
+
REJECTED: "Rejected",
|
|
15
|
+
CLOSED: "Closed",
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
/** 只处理分配给我、且处于待处理或重开状态的缺陷。 */
|
|
19
|
+
export const WATCH_STATUSES = [BUG_STATUS.PENDING, BUG_STATUS.REOPENED];
|
|
20
|
+
|
|
21
|
+
/* ======================== 依赖注入的默认实现 ======================== */
|
|
22
|
+
|
|
23
|
+
export function createApi(deps = {}) {
|
|
24
|
+
const cfg = deps.config ?? loadConfig();
|
|
25
|
+
const get = deps.api ?? ((p, params) => api(cfg, p, params));
|
|
26
|
+
const send = deps.post ?? ((p, body) => post(cfg, p, body));
|
|
27
|
+
|
|
28
|
+
return {
|
|
29
|
+
config: cfg,
|
|
30
|
+
|
|
31
|
+
async whoami() {
|
|
32
|
+
return get("/auth/me");
|
|
33
|
+
},
|
|
34
|
+
|
|
35
|
+
async listProjects() {
|
|
36
|
+
const data = await get("/projects/simple");
|
|
37
|
+
return Array.isArray(data) ? data : asItems(data);
|
|
38
|
+
},
|
|
39
|
+
|
|
40
|
+
/** 拉取某项目下分配给我的指定状态缺陷,完整分页。 */
|
|
41
|
+
async listMyBugs({ projectId, statuses = WATCH_STATUSES, pageSize = 100 }) {
|
|
42
|
+
const me = await get("/auth/me");
|
|
43
|
+
const all = [];
|
|
44
|
+
const seen = new Set();
|
|
45
|
+
for (const status of statuses) {
|
|
46
|
+
let page = 1;
|
|
47
|
+
for (;;) {
|
|
48
|
+
const data = await get("/bugs", {
|
|
49
|
+
page,
|
|
50
|
+
page_size: pageSize,
|
|
51
|
+
project_id: projectId,
|
|
52
|
+
status,
|
|
53
|
+
assignee_id: me.id,
|
|
54
|
+
});
|
|
55
|
+
const items = asItems(data);
|
|
56
|
+
for (const b of items) {
|
|
57
|
+
if (b?.id == null || seen.has(b.id)) continue;
|
|
58
|
+
seen.add(b.id);
|
|
59
|
+
all.push(b);
|
|
60
|
+
}
|
|
61
|
+
const total = Number(data?.total ?? 0);
|
|
62
|
+
if (!items.length || all.length >= total || items.length < pageSize) break;
|
|
63
|
+
page += 1;
|
|
64
|
+
if (page > 50) break; // 安全上限,避免异常分页拖死轮询
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return all;
|
|
68
|
+
},
|
|
69
|
+
|
|
70
|
+
async getBug(id) {
|
|
71
|
+
return get(`/bugs/${id}`);
|
|
72
|
+
},
|
|
73
|
+
|
|
74
|
+
async listComments(id) {
|
|
75
|
+
const data = await get(`/bugs/${id}/comments`);
|
|
76
|
+
return asItems(data);
|
|
77
|
+
},
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* 给缺陷加评论。
|
|
81
|
+
* 交付时用来写"面向测试的验证要点",让测试同学知道该点哪里。
|
|
82
|
+
*/
|
|
83
|
+
async comment(id, content) {
|
|
84
|
+
const text = String(content || "").trim();
|
|
85
|
+
if (!text) throw new Error("评论内容不能为空");
|
|
86
|
+
return send(`/bugs/${id}/comments`, { content: text });
|
|
87
|
+
},
|
|
88
|
+
|
|
89
|
+
/** 状态流转:写前由调用方复查最新状态。 */
|
|
90
|
+
async transition(id, { toStatus, resolution, notes, assigneeId }) {
|
|
91
|
+
const body = { to_status: toStatus };
|
|
92
|
+
if (resolution) body.resolution = resolution;
|
|
93
|
+
if (notes) body.resolution_notes = notes;
|
|
94
|
+
if (assigneeId != null) body.assignee_id = assigneeId;
|
|
95
|
+
return send(`/bugs/${id}/transition`, body);
|
|
96
|
+
},
|
|
97
|
+
};
|
|
98
|
+
}
|