shoplazza-ai-dev-cli 0.1.21 → 0.1.22-snapshot.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/ThirdPartyNoticeText.txt +2 -48
- package/dist/_chunks/af.mjs +1653 -0
- package/dist/_chunks/commands.mjs +2265 -0
- package/dist/_chunks/executor.mjs +2554 -0
- package/dist/_chunks/heartbeat.mjs +910 -0
- package/dist/_chunks/libs/@clack/core.mjs +5 -10
- package/dist/_chunks/libs/@clack/prompts.mjs +6 -4
- package/dist/_chunks/libs/@kwsites/file-exists.mjs +2 -2
- package/dist/_chunks/libs/@kwsites/promise-deferred.mjs +2 -2
- package/dist/_chunks/libs/core-util-is.mjs +2 -2
- package/dist/_chunks/libs/immediate.mjs +2 -2
- package/dist/_chunks/libs/inherits.mjs +4 -2
- package/dist/_chunks/libs/isarray.mjs +2 -2
- package/dist/_chunks/libs/jszip.mjs +13 -9
- package/dist/_chunks/libs/simple-git.mjs +115 -92
- package/dist/_chunks/main.mjs +116 -0
- package/dist/_chunks/rolldown-runtime.mjs +2 -2
- package/dist/_chunks/run.mjs +289 -0
- package/dist/_chunks/session-forward.mjs +82 -0
- package/dist/_chunks/test.mjs +6 -9
- package/dist/cli.mjs +127 -62
- package/package.json +3 -1
- package/dist/THIRD-PARTY-LICENSES.md +0 -584
- package/dist/_chunks/libs/@simple-git/args-pathspec.mjs +0 -12
- package/dist/_chunks/libs/@simple-git/argv-parser.mjs +0 -465
|
@@ -0,0 +1,2554 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import { delimiter, dirname, extname, isAbsolute, join, relative } from "node:path";
|
|
3
|
+
import { spawn } from "node:child_process";
|
|
4
|
+
import os, { tmpdir } from "node:os";
|
|
5
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
6
|
+
import { access, chmod, cp, mkdir, mkdtemp, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
|
|
7
|
+
import { createServer } from "node:net";
|
|
8
|
+
var ApiError = class extends Error {
|
|
9
|
+
constructor(status, code, message) {
|
|
10
|
+
super(message);
|
|
11
|
+
this.status = status;
|
|
12
|
+
this.code = code;
|
|
13
|
+
this.name = "ApiError";
|
|
14
|
+
}
|
|
15
|
+
};
|
|
16
|
+
const ERR_LEASE_FENCED = "lease_fenced";
|
|
17
|
+
const INPUT_KIND_FILE = "file";
|
|
18
|
+
const INPUT_KIND_ATTACHMENT = "attachment";
|
|
19
|
+
function unwrap(res, what) {
|
|
20
|
+
if (res.status >= 200 && res.status < 300) return res.body?.data;
|
|
21
|
+
const code = res.body?.code ?? "http_" + res.status;
|
|
22
|
+
throw new ApiError(res.status, code, `${what} failed: status=${res.status} code=${code} ${res.body?.message ?? ""}`.trim());
|
|
23
|
+
}
|
|
24
|
+
var AttemptApi = class {
|
|
25
|
+
constructor(host) {
|
|
26
|
+
this.host = host;
|
|
27
|
+
}
|
|
28
|
+
async claim(req) {
|
|
29
|
+
const res = await this.host.http().request("POST", "/runner/claim", { body: req });
|
|
30
|
+
if (res.status === 204) return;
|
|
31
|
+
return unwrap(res, "claim");
|
|
32
|
+
}
|
|
33
|
+
async heartbeat(attemptId, lease, skillCalls) {
|
|
34
|
+
const res = await this.host.http().request("POST", `/attempts/${attemptId}:heartbeat`, {
|
|
35
|
+
body: skillCalls ? { skill_calls: skillCalls } : {},
|
|
36
|
+
leaseToken: lease
|
|
37
|
+
});
|
|
38
|
+
const out = unwrap(res, "heartbeat");
|
|
39
|
+
if (!out) throw new ApiError(res.status, "empty_body", "heartbeat returned no data");
|
|
40
|
+
return out;
|
|
41
|
+
}
|
|
42
|
+
async manifest(attemptId, lease) {
|
|
43
|
+
const res = await this.host.http().request("GET", `/attempts/${attemptId}/manifest`, { leaseToken: lease });
|
|
44
|
+
const out = unwrap(res, "manifest");
|
|
45
|
+
if (!out) throw new ApiError(res.status, "empty_body", "manifest returned no data");
|
|
46
|
+
return out;
|
|
47
|
+
}
|
|
48
|
+
async browser(attemptId, lease, command) {
|
|
49
|
+
const res = await this.host.http().request("POST", `/attempts/${encodeURIComponent(attemptId)}/browser`, {
|
|
50
|
+
leaseToken: lease,
|
|
51
|
+
body: command
|
|
52
|
+
});
|
|
53
|
+
const out = unwrap(res, "browser");
|
|
54
|
+
if (!out) throw new ApiError(res.status, "empty_body", "browser returned no data");
|
|
55
|
+
return out;
|
|
56
|
+
}
|
|
57
|
+
async skillPackage(digest) {
|
|
58
|
+
const res = await this.host.http().request("GET", `/runner/skills/${encodeURIComponent(digest)}`);
|
|
59
|
+
const out = unwrap(res, "skill package");
|
|
60
|
+
if (!out) throw new ApiError(res.status, "empty_body", "skill package returned no data");
|
|
61
|
+
return out;
|
|
62
|
+
}
|
|
63
|
+
async input(attemptId, lease, name) {
|
|
64
|
+
const res = await this.host.http().request("GET", `/attempts/${attemptId}/inputs/${encodeURIComponent(name)}`, { leaseToken: lease });
|
|
65
|
+
if (res.status >= 200 && res.status < 300) return typeof res.body === "string" ? res.body : JSON.stringify(res.body ?? "");
|
|
66
|
+
return unwrap(res, "input") ?? "";
|
|
67
|
+
}
|
|
68
|
+
async attachment(attemptId, lease, name) {
|
|
69
|
+
const res = await this.host.http().request("GET", `/attempts/${attemptId}/inputs/${encodeURIComponent(name)}`, { leaseToken: lease });
|
|
70
|
+
const out = unwrap(res, "input");
|
|
71
|
+
if (!out) throw new ApiError(res.status, "empty_body", "input returned no data");
|
|
72
|
+
return Buffer.from(out.content, "base64");
|
|
73
|
+
}
|
|
74
|
+
async image(attemptId, lease, ref) {
|
|
75
|
+
const res = await this.host.http().request("GET", `/attempts/${attemptId}/images/${ref}`, { leaseToken: lease });
|
|
76
|
+
const out = unwrap(res, "image");
|
|
77
|
+
if (!out) throw new ApiError(res.status, "empty_body", "image returned no data");
|
|
78
|
+
return {
|
|
79
|
+
contentType: out.content_type,
|
|
80
|
+
data: Buffer.from(out.content, "base64")
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
async output(attemptId, lease, schema, payload, idempotencyKey) {
|
|
84
|
+
unwrap(await this.host.http().request("POST", `/attempts/${attemptId}/output`, {
|
|
85
|
+
body: {
|
|
86
|
+
schema,
|
|
87
|
+
payload,
|
|
88
|
+
idempotency_key: idempotencyKey
|
|
89
|
+
},
|
|
90
|
+
leaseToken: lease
|
|
91
|
+
}), "output");
|
|
92
|
+
}
|
|
93
|
+
async chatReply(attemptId, lease, text) {
|
|
94
|
+
unwrap(await this.host.http().request("POST", `/attempts/${attemptId}/chat-reply`, {
|
|
95
|
+
body: { text },
|
|
96
|
+
leaseToken: lease
|
|
97
|
+
}), "chat reply");
|
|
98
|
+
}
|
|
99
|
+
async questions(attemptId, lease, items) {
|
|
100
|
+
return unwrap(await this.host.http().request("POST", `/attempts/${attemptId}/questions`, {
|
|
101
|
+
body: { items },
|
|
102
|
+
leaseToken: lease
|
|
103
|
+
}), "questions")?.question_id ?? "";
|
|
104
|
+
}
|
|
105
|
+
async uploadAttachment(attemptId, lease, contentType, data) {
|
|
106
|
+
return unwrap(await this.host.http().request("POST", `/attempts/${attemptId}/attachments`, {
|
|
107
|
+
body: {
|
|
108
|
+
content_type: contentType,
|
|
109
|
+
content: data.toString("base64")
|
|
110
|
+
},
|
|
111
|
+
leaseToken: lease
|
|
112
|
+
}), "attachment")?.ref ?? "";
|
|
113
|
+
}
|
|
114
|
+
async ciReport(attemptId, lease, repoId, checkKey) {
|
|
115
|
+
const q = new URLSearchParams({
|
|
116
|
+
repo_id: repoId,
|
|
117
|
+
check_key: checkKey
|
|
118
|
+
});
|
|
119
|
+
return unwrap(await this.host.http().request("GET", `/attempts/${attemptId}/ci-report?${q.toString()}`, { leaseToken: lease }), "ci-report") ?? {
|
|
120
|
+
state: "unavailable",
|
|
121
|
+
passed: false,
|
|
122
|
+
cases: []
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
async checkResults(attemptId, lease, results) {
|
|
126
|
+
unwrap(await this.host.http().request("POST", `/attempts/${attemptId}/check-results`, {
|
|
127
|
+
body: { results },
|
|
128
|
+
leaseToken: lease
|
|
129
|
+
}), "check-results");
|
|
130
|
+
}
|
|
131
|
+
async pushReport(attemptId, lease, report) {
|
|
132
|
+
const out = unwrap(await this.host.http().request("POST", `/attempts/${attemptId}/push-report`, {
|
|
133
|
+
body: report,
|
|
134
|
+
leaseToken: lease
|
|
135
|
+
}), "push-report");
|
|
136
|
+
return {
|
|
137
|
+
verified: out?.verified ?? false,
|
|
138
|
+
violations: out?.violations ?? []
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
async checkpoint(attemptId, lease, sessionRef, headSha) {
|
|
142
|
+
unwrap(await this.host.http().request("POST", `/attempts/${attemptId}/checkpoint`, {
|
|
143
|
+
body: {
|
|
144
|
+
session_ref: sessionRef,
|
|
145
|
+
head_sha: headSha
|
|
146
|
+
},
|
|
147
|
+
leaseToken: lease
|
|
148
|
+
}), "checkpoint");
|
|
149
|
+
}
|
|
150
|
+
async exit(attemptId, lease, reason, exitCode, message, skillCalls) {
|
|
151
|
+
unwrap(await this.host.http().request("POST", `/attempts/${attemptId}:exit`, {
|
|
152
|
+
body: {
|
|
153
|
+
reason,
|
|
154
|
+
exit_code: exitCode ?? null,
|
|
155
|
+
message: message ?? "",
|
|
156
|
+
...skillCalls ? { skill_calls: skillCalls } : {}
|
|
157
|
+
},
|
|
158
|
+
leaseToken: lease
|
|
159
|
+
}), "exit");
|
|
160
|
+
}
|
|
161
|
+
};
|
|
162
|
+
const AF_COMMAND = "af";
|
|
163
|
+
const AF_BIN_DIR = "bin";
|
|
164
|
+
const SHIM_MODE = 493;
|
|
165
|
+
function currentEntry() {
|
|
166
|
+
return {
|
|
167
|
+
execPath: process.execPath,
|
|
168
|
+
execArgv: process.execArgv,
|
|
169
|
+
script: process.argv[1] ?? ""
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
function afShimScript(entry) {
|
|
173
|
+
return `#!/bin/sh\nexec ${[
|
|
174
|
+
entry.execPath,
|
|
175
|
+
...entry.execArgv,
|
|
176
|
+
entry.script
|
|
177
|
+
].map(shQuote).join(" ")} ${AF_COMMAND} "$@"\n`;
|
|
178
|
+
}
|
|
179
|
+
async function writeAfShim(workDir, entry) {
|
|
180
|
+
const dir = join(workDir, AF_BIN_DIR);
|
|
181
|
+
const file = join(dir, AF_COMMAND);
|
|
182
|
+
await mkdir(dir, { recursive: true });
|
|
183
|
+
await writeFile(file, afShimScript(entry), "utf8");
|
|
184
|
+
await chmod(file, SHIM_MODE);
|
|
185
|
+
return dir;
|
|
186
|
+
}
|
|
187
|
+
function prependPath(dir, base) {
|
|
188
|
+
if (!dir) return base;
|
|
189
|
+
return base ? `${dir}${delimiter}${base}` : dir;
|
|
190
|
+
}
|
|
191
|
+
function shQuote(s) {
|
|
192
|
+
return `'${s.replace(/'/g, `'\\''`)}'`;
|
|
193
|
+
}
|
|
194
|
+
function inhibitCommand(platform, pid, mode = "always") {
|
|
195
|
+
switch (platform) {
|
|
196
|
+
case "darwin": return {
|
|
197
|
+
cmd: "caffeinate",
|
|
198
|
+
args: [
|
|
199
|
+
mode === "plugged" ? "-s" : "-i",
|
|
200
|
+
"-w",
|
|
201
|
+
String(pid)
|
|
202
|
+
]
|
|
203
|
+
};
|
|
204
|
+
case "linux": return {
|
|
205
|
+
cmd: "systemd-inhibit",
|
|
206
|
+
args: [
|
|
207
|
+
"--what=idle:sleep",
|
|
208
|
+
"--who=forge-runner",
|
|
209
|
+
"--why=forge 环节执行中",
|
|
210
|
+
"sleep",
|
|
211
|
+
"infinity"
|
|
212
|
+
]
|
|
213
|
+
};
|
|
214
|
+
default: return;
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
var RunAwake = class {
|
|
218
|
+
holders = 0;
|
|
219
|
+
stop;
|
|
220
|
+
constructor(proc, mode, platform = process.platform, pid = process.pid) {
|
|
221
|
+
this.proc = proc;
|
|
222
|
+
this.mode = mode;
|
|
223
|
+
this.platform = platform;
|
|
224
|
+
this.pid = pid;
|
|
225
|
+
}
|
|
226
|
+
hold() {
|
|
227
|
+
this.holders++;
|
|
228
|
+
if (this.holders === 1) this.begin();
|
|
229
|
+
let released = false;
|
|
230
|
+
return () => {
|
|
231
|
+
if (released) return;
|
|
232
|
+
released = true;
|
|
233
|
+
this.holders--;
|
|
234
|
+
if (this.holders === 0) {
|
|
235
|
+
this.stop?.abort();
|
|
236
|
+
this.stop = void 0;
|
|
237
|
+
}
|
|
238
|
+
};
|
|
239
|
+
}
|
|
240
|
+
active() {
|
|
241
|
+
return this.stop !== void 0;
|
|
242
|
+
}
|
|
243
|
+
begin() {
|
|
244
|
+
const mode = this.mode();
|
|
245
|
+
const cmd = inhibitCommand(this.platform, this.pid, mode);
|
|
246
|
+
if (!cmd || mode === "off") return;
|
|
247
|
+
const stop = new AbortController();
|
|
248
|
+
this.stop = stop;
|
|
249
|
+
this.proc.run({
|
|
250
|
+
...cmd,
|
|
251
|
+
signal: stop.signal
|
|
252
|
+
}).catch(() => void 0);
|
|
253
|
+
}
|
|
254
|
+
};
|
|
255
|
+
const NAME_SEP$1 = " › ";
|
|
256
|
+
const MESSAGE_LIMIT$1 = 2e3;
|
|
257
|
+
const RESULT_OF = {
|
|
258
|
+
pass: "passed",
|
|
259
|
+
fail: "failed",
|
|
260
|
+
skip: "skipped"
|
|
261
|
+
};
|
|
262
|
+
const OUTPUT_ACTIONS = new Set(["output", "build-output"]);
|
|
263
|
+
function parseGoTestJSON(text) {
|
|
264
|
+
const cases = [];
|
|
265
|
+
const outputs = /* @__PURE__ */ new Map();
|
|
266
|
+
const pkgHasCase = /* @__PURE__ */ new Set();
|
|
267
|
+
for (const line of text.split("\n")) {
|
|
268
|
+
const ev = parseLine(line);
|
|
269
|
+
if (!ev?.Action) continue;
|
|
270
|
+
const pkg = ev.Package ?? ev.ImportPath ?? "";
|
|
271
|
+
const key = ev.Test ? `${pkg}${NAME_SEP$1}${ev.Test}` : pkg;
|
|
272
|
+
if (OUTPUT_ACTIONS.has(ev.Action)) {
|
|
273
|
+
outputs.set(key, ((outputs.get(key) ?? "") + (ev.Output ?? "")).slice(-MESSAGE_LIMIT$1));
|
|
274
|
+
continue;
|
|
275
|
+
}
|
|
276
|
+
const status = RESULT_OF[ev.Action];
|
|
277
|
+
if (!status) continue;
|
|
278
|
+
if (!ev.Test) {
|
|
279
|
+
if (status === "failed" && !pkgHasCase.has(pkg)) {
|
|
280
|
+
const out = (ev.FailedBuild ? outputs.get(ev.FailedBuild) : "") ?? "";
|
|
281
|
+
cases.push(caseOf(pkg, status, ev.Elapsed, out + (outputs.get(key) ?? "")));
|
|
282
|
+
}
|
|
283
|
+
continue;
|
|
284
|
+
}
|
|
285
|
+
if (status === "failed") pkgHasCase.add(pkg);
|
|
286
|
+
cases.push(caseOf(key, status, ev.Elapsed, outputs.get(key)));
|
|
287
|
+
}
|
|
288
|
+
return cases;
|
|
289
|
+
}
|
|
290
|
+
function parseLine(line) {
|
|
291
|
+
const s = line.trim();
|
|
292
|
+
if (!s.startsWith("{")) return;
|
|
293
|
+
try {
|
|
294
|
+
return JSON.parse(s);
|
|
295
|
+
} catch {
|
|
296
|
+
return;
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
function caseOf(name, status, elapsed, output) {
|
|
300
|
+
return {
|
|
301
|
+
name,
|
|
302
|
+
status,
|
|
303
|
+
duration_ms: Number.isFinite(elapsed) ? Math.round((elapsed ?? 0) * 1e3) : 0,
|
|
304
|
+
message: status === "failed" ? (output ?? "").trim().slice(-MESSAGE_LIMIT$1) : "",
|
|
305
|
+
attachments: []
|
|
306
|
+
};
|
|
307
|
+
}
|
|
308
|
+
const NAME_SEP = " › ";
|
|
309
|
+
const MESSAGE_LIMIT = 2e3;
|
|
310
|
+
const TESTCASE_RE = /<testcase\b([^>]*?)(?:\/>|>([\s\S]*?)<\/testcase>)/g;
|
|
311
|
+
const ATTR_RE = /([\w:-]+)\s*=\s*("([^"]*)"|'([^']*)')/g;
|
|
312
|
+
const FAILURE_RE = /<(failure|error)\b([^>]*?)(?:\/>|>([\s\S]*?)<\/\1>)/;
|
|
313
|
+
const SKIPPED_RE = /<skipped\b/;
|
|
314
|
+
const SYSTEM_OUT_RE = /<system-out\b[^>]*>([\s\S]*?)<\/system-out>/g;
|
|
315
|
+
const ATTACHMENT_RE = /\[\[ATTACHMENT\|([^\]]+)\]\]/g;
|
|
316
|
+
const CDATA_RE = /<!\[CDATA\[([\s\S]*?)\]\]>/g;
|
|
317
|
+
function decodeEntities(s) {
|
|
318
|
+
return s.replace(/&(#x[0-9a-fA-F]+|#\d+|amp|lt|gt|quot|apos);/g, (_, e) => {
|
|
319
|
+
if (e.startsWith("#x")) return String.fromCodePoint(parseInt(e.slice(2), 16));
|
|
320
|
+
if (e.startsWith("#")) return String.fromCodePoint(parseInt(e.slice(1), 10));
|
|
321
|
+
return {
|
|
322
|
+
amp: "&",
|
|
323
|
+
lt: "<",
|
|
324
|
+
gt: ">",
|
|
325
|
+
quot: "\"",
|
|
326
|
+
apos: "'"
|
|
327
|
+
}[e] ?? "";
|
|
328
|
+
});
|
|
329
|
+
}
|
|
330
|
+
function textOf(raw) {
|
|
331
|
+
const parts = [];
|
|
332
|
+
let last = 0;
|
|
333
|
+
for (const m of raw.matchAll(CDATA_RE)) {
|
|
334
|
+
parts.push(decodeEntities(raw.slice(last, m.index)), m[1] ?? "");
|
|
335
|
+
last = (m.index ?? 0) + m[0].length;
|
|
336
|
+
}
|
|
337
|
+
parts.push(decodeEntities(raw.slice(last)));
|
|
338
|
+
return parts.join("");
|
|
339
|
+
}
|
|
340
|
+
function attrsOf(raw) {
|
|
341
|
+
const out = {};
|
|
342
|
+
for (const m of raw.matchAll(ATTR_RE)) out[m[1] ?? ""] = decodeEntities(m[3] ?? m[4] ?? "");
|
|
343
|
+
return out;
|
|
344
|
+
}
|
|
345
|
+
function parseJUnit(xml, reportDir) {
|
|
346
|
+
const cases = [];
|
|
347
|
+
for (const m of xml.matchAll(TESTCASE_RE)) {
|
|
348
|
+
const attrs = attrsOf(m[1] ?? "");
|
|
349
|
+
const body = m[2] ?? "";
|
|
350
|
+
const name = attrs.classname ? `${attrs.classname}${NAME_SEP}${attrs.name ?? ""}` : attrs.name ?? "";
|
|
351
|
+
const seconds = Number(attrs.time ?? "0");
|
|
352
|
+
let status = "passed";
|
|
353
|
+
let message = "";
|
|
354
|
+
const failure = FAILURE_RE.exec(body);
|
|
355
|
+
if (failure) {
|
|
356
|
+
status = "failed";
|
|
357
|
+
message = [attrsOf(failure[2] ?? "").message ?? "", textOf(failure[3] ?? "").trim()].filter(Boolean).join("\n");
|
|
358
|
+
} else if (SKIPPED_RE.test(body)) status = "skipped";
|
|
359
|
+
const attachments = [];
|
|
360
|
+
for (const out of body.matchAll(SYSTEM_OUT_RE)) for (const a of textOf(out[1] ?? "").matchAll(ATTACHMENT_RE)) {
|
|
361
|
+
const p = (a[1] ?? "").trim();
|
|
362
|
+
attachments.push(isAbsolute(p) ? p : join(reportDir, p));
|
|
363
|
+
}
|
|
364
|
+
cases.push({
|
|
365
|
+
name: name.trim(),
|
|
366
|
+
status,
|
|
367
|
+
duration_ms: Number.isFinite(seconds) ? Math.round(seconds * 1e3) : 0,
|
|
368
|
+
message: message.slice(0, MESSAGE_LIMIT),
|
|
369
|
+
attachments
|
|
370
|
+
});
|
|
371
|
+
}
|
|
372
|
+
return cases;
|
|
373
|
+
}
|
|
374
|
+
const KIND_MYSQL = "mysql";
|
|
375
|
+
const TEST_USER = "forge_test";
|
|
376
|
+
const READY_TIMEOUT_MS = 9e4;
|
|
377
|
+
const READY_POLL_MS = 1e3;
|
|
378
|
+
const CMD_TIMEOUT_MS = 12e4;
|
|
379
|
+
const MAX_SOCKET_PATH = 100;
|
|
380
|
+
const MYSQL_INSTALL_GUIDE = "本机没有可用的 MySQL:安装 Docker Desktop(推荐,按版本起一次性容器),或用 Homebrew 装同版本的 mysql(如 brew install mysql@8.0 并加入 PATH);也可以在仓库配置里给这项检查声明 ci_job,改读 CI 单测报告。";
|
|
381
|
+
const nodeLauncher = { async start(cmd, args) {
|
|
382
|
+
const child = spawn(cmd, args, {
|
|
383
|
+
detached: true,
|
|
384
|
+
stdio: "ignore"
|
|
385
|
+
});
|
|
386
|
+
const exited = new Promise((resolve) => child.once("exit", () => resolve()));
|
|
387
|
+
return async () => {
|
|
388
|
+
try {
|
|
389
|
+
if (child.pid) process.kill(-child.pid, "SIGTERM");
|
|
390
|
+
} catch {
|
|
391
|
+
child.kill("SIGTERM");
|
|
392
|
+
}
|
|
393
|
+
await Promise.race([exited, new Promise((r) => setTimeout(r, 3e4))]);
|
|
394
|
+
};
|
|
395
|
+
} };
|
|
396
|
+
function pickFreePort() {
|
|
397
|
+
return new Promise((resolve, reject) => {
|
|
398
|
+
const srv = createServer();
|
|
399
|
+
srv.once("error", reject);
|
|
400
|
+
srv.listen(0, "127.0.0.1", () => {
|
|
401
|
+
const addr = srv.address();
|
|
402
|
+
srv.close(() => typeof addr === "object" && addr ? resolve(addr.port) : reject(/* @__PURE__ */ new Error("no free port")));
|
|
403
|
+
});
|
|
404
|
+
});
|
|
405
|
+
}
|
|
406
|
+
async function hasDocker(d) {
|
|
407
|
+
const res = await d.proc.run({
|
|
408
|
+
cmd: "docker",
|
|
409
|
+
args: [
|
|
410
|
+
"info",
|
|
411
|
+
"--format",
|
|
412
|
+
"{{.ServerVersion}}"
|
|
413
|
+
],
|
|
414
|
+
timeoutMs: 15e3,
|
|
415
|
+
signal: d.signal
|
|
416
|
+
}).catch(() => void 0);
|
|
417
|
+
return res?.ended === "exit" && res.code === 0;
|
|
418
|
+
}
|
|
419
|
+
async function localMySQLVersion(d) {
|
|
420
|
+
const res = await d.proc.run({
|
|
421
|
+
cmd: "mysqld",
|
|
422
|
+
args: ["--version"],
|
|
423
|
+
timeoutMs: 15e3,
|
|
424
|
+
signal: d.signal
|
|
425
|
+
}).catch(() => void 0);
|
|
426
|
+
if (res?.ended !== "exit" || res.code !== 0) return "";
|
|
427
|
+
return /Ver\s+(\d+\.\d+\.\d+)/.exec(res.stdout)?.[1] ?? "";
|
|
428
|
+
}
|
|
429
|
+
async function chooseMySQL(d, want) {
|
|
430
|
+
if (await hasDocker(d)) return {
|
|
431
|
+
kind: "docker",
|
|
432
|
+
version: ""
|
|
433
|
+
};
|
|
434
|
+
const local = await localMySQLVersion(d);
|
|
435
|
+
if (local && local.startsWith(`${want}.`)) return {
|
|
436
|
+
kind: "local",
|
|
437
|
+
version: local
|
|
438
|
+
};
|
|
439
|
+
if (local) return `本机 mysqld 是 ${local},与要求的 ${want} 不一致,也没有 Docker`;
|
|
440
|
+
return `本机没有 Docker,也没有 mysqld(要求 MySQL ${want})`;
|
|
441
|
+
}
|
|
442
|
+
async function dockerMySQL(d, version) {
|
|
443
|
+
const password = randomBytes(12).toString("hex");
|
|
444
|
+
const run = await d.proc.run({
|
|
445
|
+
cmd: "docker",
|
|
446
|
+
args: [
|
|
447
|
+
"run",
|
|
448
|
+
"-d",
|
|
449
|
+
"--rm",
|
|
450
|
+
"-e",
|
|
451
|
+
`MYSQL_ROOT_PASSWORD=${password}`,
|
|
452
|
+
"-p",
|
|
453
|
+
"127.0.0.1::3306",
|
|
454
|
+
`mysql:${version}`
|
|
455
|
+
],
|
|
456
|
+
timeoutMs: 10 * 6e4,
|
|
457
|
+
signal: d.signal
|
|
458
|
+
});
|
|
459
|
+
const id = run.stdout.trim();
|
|
460
|
+
if (run.code !== 0 || !id) throw new Error(`docker run mysql:${version} failed: ${run.stderr.trim().slice(-500)}`);
|
|
461
|
+
const stop = async () => {
|
|
462
|
+
await d.proc.run({
|
|
463
|
+
cmd: "docker",
|
|
464
|
+
args: [
|
|
465
|
+
"rm",
|
|
466
|
+
"-f",
|
|
467
|
+
id
|
|
468
|
+
],
|
|
469
|
+
timeoutMs: 6e4
|
|
470
|
+
}).catch(() => void 0);
|
|
471
|
+
};
|
|
472
|
+
try {
|
|
473
|
+
const port = await d.proc.run({
|
|
474
|
+
cmd: "docker",
|
|
475
|
+
args: [
|
|
476
|
+
"port",
|
|
477
|
+
id,
|
|
478
|
+
"3306/tcp"
|
|
479
|
+
],
|
|
480
|
+
timeoutMs: 15e3
|
|
481
|
+
});
|
|
482
|
+
const hostPort = Number(/:(\d+)\s*$/m.exec(port.stdout)?.[1] ?? 0);
|
|
483
|
+
const exec = async (sql, database) => {
|
|
484
|
+
const res = await d.proc.run({
|
|
485
|
+
cmd: "docker",
|
|
486
|
+
args: [
|
|
487
|
+
"exec",
|
|
488
|
+
"-i",
|
|
489
|
+
"-e",
|
|
490
|
+
`MYSQL_PWD=${password}`,
|
|
491
|
+
id,
|
|
492
|
+
"mysql",
|
|
493
|
+
"-uroot",
|
|
494
|
+
...database ? [database] : []
|
|
495
|
+
],
|
|
496
|
+
stdin: sql,
|
|
497
|
+
timeoutMs: CMD_TIMEOUT_MS,
|
|
498
|
+
signal: d.signal
|
|
499
|
+
});
|
|
500
|
+
return {
|
|
501
|
+
ok: res.ended === "exit" && res.code === 0,
|
|
502
|
+
error: res.stderr.trim().slice(-500)
|
|
503
|
+
};
|
|
504
|
+
};
|
|
505
|
+
await waitReady(() => exec("SELECT 1"));
|
|
506
|
+
const ver = await d.proc.run({
|
|
507
|
+
cmd: "docker",
|
|
508
|
+
args: [
|
|
509
|
+
"exec",
|
|
510
|
+
id,
|
|
511
|
+
"mysqld",
|
|
512
|
+
"--version"
|
|
513
|
+
],
|
|
514
|
+
timeoutMs: 15e3
|
|
515
|
+
});
|
|
516
|
+
return {
|
|
517
|
+
host: "127.0.0.1",
|
|
518
|
+
port: hostPort,
|
|
519
|
+
rootPassword: password,
|
|
520
|
+
version: /Ver\s+(\d+\.\d+\.\d+)/.exec(ver.stdout)?.[1] ?? version,
|
|
521
|
+
exec,
|
|
522
|
+
stop
|
|
523
|
+
};
|
|
524
|
+
} catch (err) {
|
|
525
|
+
await stop();
|
|
526
|
+
throw err;
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
async function localMySQL(d, version) {
|
|
530
|
+
let dir = await mkdtemp(join(tmpdir(), "afm-"));
|
|
531
|
+
if (join(dir, "m.sock").length > MAX_SOCKET_PATH) {
|
|
532
|
+
await rm(dir, {
|
|
533
|
+
recursive: true,
|
|
534
|
+
force: true
|
|
535
|
+
});
|
|
536
|
+
dir = await mkdtemp("/tmp/afm-");
|
|
537
|
+
}
|
|
538
|
+
const port = await (d.freePort ?? pickFreePort)();
|
|
539
|
+
const tcp = [
|
|
540
|
+
"--protocol=TCP",
|
|
541
|
+
"-h127.0.0.1",
|
|
542
|
+
`-P${port}`,
|
|
543
|
+
"-uroot"
|
|
544
|
+
];
|
|
545
|
+
let stop = async () => void 0;
|
|
546
|
+
const cleanup = async () => {
|
|
547
|
+
await stop();
|
|
548
|
+
await rm(dir, {
|
|
549
|
+
recursive: true,
|
|
550
|
+
force: true
|
|
551
|
+
});
|
|
552
|
+
};
|
|
553
|
+
try {
|
|
554
|
+
const init = await d.proc.run({
|
|
555
|
+
cmd: "mysqld",
|
|
556
|
+
args: [
|
|
557
|
+
"--initialize-insecure",
|
|
558
|
+
`--datadir=${join(dir, "data")}`,
|
|
559
|
+
`--log-error=${join(dir, "init.err")}`
|
|
560
|
+
],
|
|
561
|
+
timeoutMs: CMD_TIMEOUT_MS,
|
|
562
|
+
signal: d.signal
|
|
563
|
+
});
|
|
564
|
+
if (init.code !== 0) throw new Error(`mysqld --initialize-insecure failed: ${init.stderr.trim().slice(-500)}`);
|
|
565
|
+
stop = await d.launcher.start("mysqld", [
|
|
566
|
+
`--datadir=${join(dir, "data")}`,
|
|
567
|
+
`--port=${port}`,
|
|
568
|
+
"--bind-address=127.0.0.1",
|
|
569
|
+
`--socket=${join(dir, "m.sock")}`,
|
|
570
|
+
`--pid-file=${join(dir, "m.pid")}`,
|
|
571
|
+
`--log-error=${join(dir, "error.log")}`,
|
|
572
|
+
"--mysqlx=OFF",
|
|
573
|
+
"--skip-log-bin"
|
|
574
|
+
]);
|
|
575
|
+
const exec = async (sql, database) => {
|
|
576
|
+
const res = await d.proc.run({
|
|
577
|
+
cmd: "mysql",
|
|
578
|
+
args: [...tcp, ...database ? [database] : []],
|
|
579
|
+
stdin: sql,
|
|
580
|
+
timeoutMs: CMD_TIMEOUT_MS,
|
|
581
|
+
signal: d.signal
|
|
582
|
+
});
|
|
583
|
+
return {
|
|
584
|
+
ok: res.ended === "exit" && res.code === 0,
|
|
585
|
+
error: res.stderr.trim().slice(-500)
|
|
586
|
+
};
|
|
587
|
+
};
|
|
588
|
+
await waitReady(() => exec("SELECT 1"));
|
|
589
|
+
return {
|
|
590
|
+
host: "127.0.0.1",
|
|
591
|
+
port,
|
|
592
|
+
rootPassword: "",
|
|
593
|
+
version,
|
|
594
|
+
exec,
|
|
595
|
+
stop: cleanup
|
|
596
|
+
};
|
|
597
|
+
} catch (err) {
|
|
598
|
+
await cleanup();
|
|
599
|
+
throw err;
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
async function waitReady(probe) {
|
|
603
|
+
const deadline = Date.now() + READY_TIMEOUT_MS;
|
|
604
|
+
let last = "";
|
|
605
|
+
while (Date.now() < deadline) {
|
|
606
|
+
const r = await probe();
|
|
607
|
+
if (r.ok) return;
|
|
608
|
+
last = r.error;
|
|
609
|
+
await new Promise((resolve) => setTimeout(resolve, READY_POLL_MS));
|
|
610
|
+
}
|
|
611
|
+
throw new Error(`mysql not ready: ${last}`);
|
|
612
|
+
}
|
|
613
|
+
function globRegExp(pattern) {
|
|
614
|
+
const esc = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, "[^/]*").replace(/\?/g, "[^/]");
|
|
615
|
+
return new RegExp(`^${esc}$`);
|
|
616
|
+
}
|
|
617
|
+
async function matchFiles(root, paths) {
|
|
618
|
+
const out = /* @__PURE__ */ new Set();
|
|
619
|
+
for (const p of paths) {
|
|
620
|
+
const slash = p.lastIndexOf("/");
|
|
621
|
+
const dir = slash >= 0 ? p.slice(0, slash) : "";
|
|
622
|
+
const re = globRegExp(slash >= 0 ? p.slice(slash + 1) : p);
|
|
623
|
+
const names = await readdir(join(root, dir)).catch(() => []);
|
|
624
|
+
for (const n of names) if (re.test(n)) out.add(join(root, dir, n));
|
|
625
|
+
}
|
|
626
|
+
return [...out].sort();
|
|
627
|
+
}
|
|
628
|
+
async function schemaRoot(d, cwd, schema) {
|
|
629
|
+
if (!schema.repo) return cwd;
|
|
630
|
+
const key = createHash("sha256").update(`${schema.repo}#${schema.ref ?? ""}`).digest("hex").slice(0, 16);
|
|
631
|
+
const dir = join(d.cacheDir, "schemas", key);
|
|
632
|
+
const git = (args, at) => d.proc.run({
|
|
633
|
+
cmd: "git",
|
|
634
|
+
args,
|
|
635
|
+
cwd: at,
|
|
636
|
+
timeoutMs: 5 * 6e4,
|
|
637
|
+
signal: d.signal
|
|
638
|
+
});
|
|
639
|
+
if (existsSync(join(dir, ".git"))) {
|
|
640
|
+
if ((await git([
|
|
641
|
+
"fetch",
|
|
642
|
+
"--depth",
|
|
643
|
+
"1",
|
|
644
|
+
"origin",
|
|
645
|
+
schema.ref ?? "HEAD"
|
|
646
|
+
], dir)).code === 0) await git([
|
|
647
|
+
"reset",
|
|
648
|
+
"--hard",
|
|
649
|
+
"FETCH_HEAD"
|
|
650
|
+
], dir);
|
|
651
|
+
return dir;
|
|
652
|
+
}
|
|
653
|
+
await mkdir(join(d.cacheDir, "schemas"), { recursive: true });
|
|
654
|
+
const res = await git([
|
|
655
|
+
"clone",
|
|
656
|
+
"--depth",
|
|
657
|
+
"1",
|
|
658
|
+
...schema.ref ? ["--branch", schema.ref] : [],
|
|
659
|
+
schema.repo,
|
|
660
|
+
dir
|
|
661
|
+
]);
|
|
662
|
+
if (res.code !== 0) throw new Error(`clone schema repo failed: ${res.stderr.trim().slice(-500)}`);
|
|
663
|
+
return dir;
|
|
664
|
+
}
|
|
665
|
+
async function provisionMySQL(d, svc, cwd, runtime) {
|
|
666
|
+
const inst = runtime.kind === "docker" ? await dockerMySQL(d, svc.version) : await localMySQL(d, runtime.version);
|
|
667
|
+
try {
|
|
668
|
+
const database = svc.database || "forge_test";
|
|
669
|
+
const password = randomBytes(12).toString("hex");
|
|
670
|
+
const setup = await inst.exec(`CREATE DATABASE IF NOT EXISTS \`${database}\`; CREATE USER '${TEST_USER}'@'%' IDENTIFIED BY '${password}'; GRANT ALL PRIVILEGES ON *.* TO '${TEST_USER}'@'%'; FLUSH PRIVILEGES;`);
|
|
671
|
+
if (!setup.ok) throw new Error(`create test database failed: ${setup.error}`);
|
|
672
|
+
const notes = [];
|
|
673
|
+
if (svc.schema) {
|
|
674
|
+
const root = await schemaRoot(d, cwd, svc.schema);
|
|
675
|
+
const files = await matchFiles(root, svc.schema.paths);
|
|
676
|
+
const failed = [];
|
|
677
|
+
for (const f of files) if (!(await inst.exec(await readFile(f, "utf8"), database)).ok) failed.push(f.slice(root.length + 1));
|
|
678
|
+
notes.push(`建表脚本 ${files.length} 个${failed.length ? `,执行失败 ${failed.length} 个:${failed.slice(0, 5).join("、")}` : ""}`);
|
|
679
|
+
}
|
|
680
|
+
const env = {};
|
|
681
|
+
const values = {
|
|
682
|
+
host: inst.host,
|
|
683
|
+
port: String(inst.port),
|
|
684
|
+
user: TEST_USER,
|
|
685
|
+
password,
|
|
686
|
+
database
|
|
687
|
+
};
|
|
688
|
+
for (const [k, name] of Object.entries(svc.env)) if (name) env[name] = values[k];
|
|
689
|
+
return {
|
|
690
|
+
env,
|
|
691
|
+
label: `mysql ${inst.version}`,
|
|
692
|
+
notes,
|
|
693
|
+
stop: () => inst.stop()
|
|
694
|
+
};
|
|
695
|
+
} catch (err) {
|
|
696
|
+
await inst.stop();
|
|
697
|
+
throw err;
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
async function provisionServices(d, services, cwd) {
|
|
701
|
+
const started = [];
|
|
702
|
+
let source = "local_service";
|
|
703
|
+
const teardown = async () => {
|
|
704
|
+
for (const s of started.reverse()) await s.stop().catch(() => void 0);
|
|
705
|
+
};
|
|
706
|
+
try {
|
|
707
|
+
for (const svc of services) {
|
|
708
|
+
if (svc.kind !== KIND_MYSQL) {
|
|
709
|
+
await teardown();
|
|
710
|
+
return {
|
|
711
|
+
ok: false,
|
|
712
|
+
reason: `不支持的服务种类 ${svc.kind}`
|
|
713
|
+
};
|
|
714
|
+
}
|
|
715
|
+
const runtime = await chooseMySQL(d, svc.version);
|
|
716
|
+
if (typeof runtime === "string") {
|
|
717
|
+
await teardown();
|
|
718
|
+
return {
|
|
719
|
+
ok: false,
|
|
720
|
+
reason: runtime
|
|
721
|
+
};
|
|
722
|
+
}
|
|
723
|
+
if (runtime.kind === "docker") source = "docker";
|
|
724
|
+
started.push(await provisionMySQL(d, svc, cwd, runtime));
|
|
725
|
+
}
|
|
726
|
+
} catch (err) {
|
|
727
|
+
await teardown();
|
|
728
|
+
return {
|
|
729
|
+
ok: false,
|
|
730
|
+
reason: `起测试服务失败:${err instanceof Error ? err.message : String(err)}`
|
|
731
|
+
};
|
|
732
|
+
}
|
|
733
|
+
return {
|
|
734
|
+
ok: true,
|
|
735
|
+
value: {
|
|
736
|
+
source,
|
|
737
|
+
env: Object.assign({}, ...started.map((s) => s.env)),
|
|
738
|
+
services: started.map((s) => s.label),
|
|
739
|
+
notes: started.flatMap((s) => s.notes),
|
|
740
|
+
teardown
|
|
741
|
+
}
|
|
742
|
+
};
|
|
743
|
+
}
|
|
744
|
+
function hostEnv(source, extra = {}) {
|
|
745
|
+
return {
|
|
746
|
+
source,
|
|
747
|
+
os: process.platform,
|
|
748
|
+
arch: process.arch,
|
|
749
|
+
...extra
|
|
750
|
+
};
|
|
751
|
+
}
|
|
752
|
+
const DEFAULT_CHECK_TIMEOUT_MIN = 30;
|
|
753
|
+
const FAILURE_TAIL = 2e3;
|
|
754
|
+
const PARSER_JUNIT = "junit";
|
|
755
|
+
const PARSER_GOTEST = "gotest";
|
|
756
|
+
const CONVENTION_PLAYWRIGHT = "playwright";
|
|
757
|
+
const IMAGE_TYPES = {
|
|
758
|
+
".png": "image/png",
|
|
759
|
+
".jpg": "image/jpeg",
|
|
760
|
+
".jpeg": "image/jpeg",
|
|
761
|
+
".webp": "image/webp"
|
|
762
|
+
};
|
|
763
|
+
const MAX_ATTACHMENT_BYTES = 5 << 20;
|
|
764
|
+
const MAX_CASE_ATTACHMENTS = 5;
|
|
765
|
+
const MAX_CHECK_ATTACHMENTS = 200;
|
|
766
|
+
const UPLOAD_CONCURRENCY = 4;
|
|
767
|
+
const PLAYWRIGHT_CONFIGS = [
|
|
768
|
+
"playwright.config.ts",
|
|
769
|
+
"playwright.config.mts",
|
|
770
|
+
"playwright.config.cts",
|
|
771
|
+
"playwright.config.js",
|
|
772
|
+
"playwright.config.mjs",
|
|
773
|
+
"playwright.config.cjs"
|
|
774
|
+
];
|
|
775
|
+
const PLAYWRIGHT_WRAPPER = "playwright.forge-autoflow.config.ts";
|
|
776
|
+
const PLAYWRIGHT_REPORT = ".forge/e2e/junit.xml";
|
|
777
|
+
const PLAYWRIGHT_OUTPUT = ".forge/e2e/output";
|
|
778
|
+
const INSTALL_BY_LOCK = [
|
|
779
|
+
["pnpm-lock.yaml", "pnpm install --frozen-lockfile"],
|
|
780
|
+
["yarn.lock", "yarn install --frozen-lockfile"],
|
|
781
|
+
["package-lock.json", "npm ci"]
|
|
782
|
+
];
|
|
783
|
+
const INSTALL_DEFAULT = "npm install";
|
|
784
|
+
function playwrightWrapper(configFile) {
|
|
785
|
+
return `// forge autoflow 自动生成:用仓库自带的 Playwright 配置跑 e2e,换成 junit 报告并开截图。
|
|
786
|
+
import imported from './${configFile}';
|
|
787
|
+
const raw: any = imported;
|
|
788
|
+
const base: any = raw && raw.default && !raw.testDir && !raw.projects ? raw.default : raw;
|
|
789
|
+
const forge = { screenshot: 'on' };
|
|
790
|
+
const cfg: any = { ...base, reporter: [['junit'], ['line']], use: { ...(base.use ?? {}), ...forge } };
|
|
791
|
+
if (base.projects) cfg.projects = base.projects.map((p: any) => ({ ...p, use: { ...(p.use ?? {}), ...forge } }));
|
|
792
|
+
export default cfg;
|
|
793
|
+
`;
|
|
794
|
+
}
|
|
795
|
+
async function resolvePlaywright(cwd) {
|
|
796
|
+
const configFile = PLAYWRIGHT_CONFIGS.find((f) => existsSync(join(cwd, f)));
|
|
797
|
+
if (!configFile) return;
|
|
798
|
+
await writeFile(join(cwd, PLAYWRIGHT_WRAPPER), playwrightWrapper(configFile), "utf8");
|
|
799
|
+
const install = existsSync(join(cwd, "node_modules")) ? "" : (INSTALL_BY_LOCK.find(([lock]) => existsSync(join(cwd, lock)))?.[1] ?? INSTALL_DEFAULT) + " && ";
|
|
800
|
+
const reportPath = join(cwd, PLAYWRIGHT_REPORT);
|
|
801
|
+
return {
|
|
802
|
+
command: `${install}npx --no-install playwright test -c ${PLAYWRIGHT_WRAPPER} --output ${PLAYWRIGHT_OUTPUT}`,
|
|
803
|
+
reportPath,
|
|
804
|
+
parser: PARSER_JUNIT,
|
|
805
|
+
env: { PLAYWRIGHT_JUNIT_OUTPUT_FILE: reportPath }
|
|
806
|
+
};
|
|
807
|
+
}
|
|
808
|
+
async function resolveCheck(c, cwd) {
|
|
809
|
+
if (c.command) {
|
|
810
|
+
const report = c.report_path ?? "";
|
|
811
|
+
return {
|
|
812
|
+
command: c.command,
|
|
813
|
+
reportPath: report ? isAbsolute(report) ? report : join(cwd, report) : "",
|
|
814
|
+
parser: c.parser ?? "",
|
|
815
|
+
env: {}
|
|
816
|
+
};
|
|
817
|
+
}
|
|
818
|
+
if (c.convention === CONVENTION_PLAYWRIGHT) return resolvePlaywright(cwd);
|
|
819
|
+
}
|
|
820
|
+
async function readCases(r, stdout) {
|
|
821
|
+
if (r.parser === PARSER_GOTEST) {
|
|
822
|
+
const raw = !r.reportPath ? stdout : existsSync(r.reportPath) ? await readFile(r.reportPath, "utf8") : "";
|
|
823
|
+
return {
|
|
824
|
+
cases: parseGoTestJSON(raw),
|
|
825
|
+
raw
|
|
826
|
+
};
|
|
827
|
+
}
|
|
828
|
+
if (r.parser !== PARSER_JUNIT || !r.reportPath || !existsSync(r.reportPath)) return {
|
|
829
|
+
cases: [],
|
|
830
|
+
raw: ""
|
|
831
|
+
};
|
|
832
|
+
const raw = await readFile(r.reportPath, "utf8");
|
|
833
|
+
return {
|
|
834
|
+
cases: parseJUnit(raw, dirname(r.reportPath)),
|
|
835
|
+
raw
|
|
836
|
+
};
|
|
837
|
+
}
|
|
838
|
+
async function pickShots(cases) {
|
|
839
|
+
const out = [];
|
|
840
|
+
for (const [i, c] of cases.entries()) {
|
|
841
|
+
let n = 0;
|
|
842
|
+
for (const path of c.attachments) {
|
|
843
|
+
const contentType = IMAGE_TYPES[extname(path).toLowerCase()];
|
|
844
|
+
if (!contentType || n >= MAX_CASE_ATTACHMENTS || out.length >= MAX_CHECK_ATTACHMENTS) continue;
|
|
845
|
+
const st = await stat(path).catch(() => void 0);
|
|
846
|
+
if (!st?.isFile() || st.size > MAX_ATTACHMENT_BYTES) continue;
|
|
847
|
+
out.push({
|
|
848
|
+
caseIndex: i,
|
|
849
|
+
path,
|
|
850
|
+
contentType
|
|
851
|
+
});
|
|
852
|
+
n++;
|
|
853
|
+
}
|
|
854
|
+
}
|
|
855
|
+
return out;
|
|
856
|
+
}
|
|
857
|
+
async function attachShots(cases, baseDir, upload) {
|
|
858
|
+
const out = cases.map((c) => ({
|
|
859
|
+
name: c.name,
|
|
860
|
+
status: c.status,
|
|
861
|
+
duration_ms: c.duration_ms,
|
|
862
|
+
message: c.message,
|
|
863
|
+
attachments: []
|
|
864
|
+
}));
|
|
865
|
+
if (!upload) return out;
|
|
866
|
+
const shots = await pickShots(cases);
|
|
867
|
+
for (let i = 0; i < shots.length; i += UPLOAD_CONCURRENCY) {
|
|
868
|
+
const batch = shots.slice(i, i + UPLOAD_CONCURRENCY);
|
|
869
|
+
const refs = await Promise.all(batch.map(async (s) => upload(s.contentType, await readFile(s.path)).catch(() => "")));
|
|
870
|
+
batch.forEach((s, k) => {
|
|
871
|
+
const target = out[s.caseIndex];
|
|
872
|
+
if (refs[k] && target) target.attachments.push({
|
|
873
|
+
name: relative(baseDir, s.path),
|
|
874
|
+
ref: refs[k],
|
|
875
|
+
content_type: s.contentType
|
|
876
|
+
});
|
|
877
|
+
});
|
|
878
|
+
}
|
|
879
|
+
return out;
|
|
880
|
+
}
|
|
881
|
+
const DEFAULT_CI_POLL_MS = 2e4;
|
|
882
|
+
const GOMONKEY_SIGN = /agiledragon\/gomonkey/;
|
|
883
|
+
const GOMONKEY_DENIED = /modify_binary_darwin|modifyBinary|permission denied/;
|
|
884
|
+
function gomonkeyOnArm64(arch, raw) {
|
|
885
|
+
return arch === "arm64" && GOMONKEY_SIGN.test(raw) && GOMONKEY_DENIED.test(raw);
|
|
886
|
+
}
|
|
887
|
+
async function runLocal(proc, c, resolved, cwd, env, signal, upload) {
|
|
888
|
+
if (resolved.reportPath) {
|
|
889
|
+
await rm(resolved.reportPath, { force: true });
|
|
890
|
+
await mkdir(dirname(resolved.reportPath), { recursive: true });
|
|
891
|
+
}
|
|
892
|
+
const res = await proc.run({
|
|
893
|
+
cmd: "sh",
|
|
894
|
+
args: ["-lc", resolved.command],
|
|
895
|
+
cwd,
|
|
896
|
+
env: {
|
|
897
|
+
...resolved.env,
|
|
898
|
+
...env
|
|
899
|
+
},
|
|
900
|
+
timeoutMs: (c.timeout_minutes ?? DEFAULT_CHECK_TIMEOUT_MIN) * 6e4,
|
|
901
|
+
signal
|
|
902
|
+
});
|
|
903
|
+
const parsed = await readCases(resolved, res.stdout);
|
|
904
|
+
const cases = await attachShots(parsed.cases, cwd, upload);
|
|
905
|
+
const failedCases = cases.filter((k) => k.status === "failed");
|
|
906
|
+
const failed = res.code !== 0 || failedCases.length > 0;
|
|
907
|
+
const tail = (res.stderr + "\n" + res.stdout).trim().slice(-FAILURE_TAIL);
|
|
908
|
+
const failures = failedCases.length ? failedCases.map((k) => ({
|
|
909
|
+
identity: k.name,
|
|
910
|
+
message: k.message
|
|
911
|
+
})) : failed ? [{
|
|
912
|
+
identity: c.check_key,
|
|
913
|
+
message: res.ended === "exit" ? tail : `check ${res.ended}`
|
|
914
|
+
}] : [];
|
|
915
|
+
return {
|
|
916
|
+
result: {
|
|
917
|
+
check_key: c.check_key,
|
|
918
|
+
repo_id: c.repo_id,
|
|
919
|
+
exit_code: res.ended === "exit" ? res.code : null,
|
|
920
|
+
duration_ms: res.durationMs,
|
|
921
|
+
failures,
|
|
922
|
+
cases
|
|
923
|
+
},
|
|
924
|
+
raw: parsed.raw + "\n" + res.stderr + "\n" + res.stdout,
|
|
925
|
+
failed
|
|
926
|
+
};
|
|
927
|
+
}
|
|
928
|
+
function unavailable(c, reason) {
|
|
929
|
+
const note = `${reason}。${MYSQL_INSTALL_GUIDE}`;
|
|
930
|
+
return {
|
|
931
|
+
check_key: c.check_key,
|
|
932
|
+
repo_id: c.repo_id,
|
|
933
|
+
exit_code: null,
|
|
934
|
+
duration_ms: 0,
|
|
935
|
+
failures: [{
|
|
936
|
+
identity: c.check_key,
|
|
937
|
+
message: note
|
|
938
|
+
}],
|
|
939
|
+
env_fingerprint: hostEnv("unavailable", { note })
|
|
940
|
+
};
|
|
941
|
+
}
|
|
942
|
+
async function fromCI(c, extras, reason, signal) {
|
|
943
|
+
if (!extras.ciReport || !c.ci_job) return unavailable(c, reason);
|
|
944
|
+
const started = Date.now();
|
|
945
|
+
const deadline = started + (c.timeout_minutes ?? DEFAULT_CHECK_TIMEOUT_MIN) * 6e4;
|
|
946
|
+
let last;
|
|
947
|
+
while (!signal?.aborted) {
|
|
948
|
+
last = await extras.ciReport(c.repo_id, c.check_key).catch((err) => ({
|
|
949
|
+
state: "pending",
|
|
950
|
+
passed: false,
|
|
951
|
+
cases: [],
|
|
952
|
+
note: `读 CI 报告出错:${err instanceof Error ? err.message : String(err)}`
|
|
953
|
+
}));
|
|
954
|
+
if (last.state !== "pending" || Date.now() >= deadline) break;
|
|
955
|
+
await sleep(extras.ciPollMs ?? DEFAULT_CI_POLL_MS, signal);
|
|
956
|
+
}
|
|
957
|
+
if (!last || last.state !== "done") return unavailable(c, `${reason};${last?.state === "unavailable" ? last.note ?? "拿不到 CI 报告" : `等 CI 作业 ${c.ci_job} 超时${last?.note ? `(${last.note})` : ""}`}`);
|
|
958
|
+
const cases = last.cases.map((k) => ({
|
|
959
|
+
...k,
|
|
960
|
+
attachments: k.attachments ?? []
|
|
961
|
+
}));
|
|
962
|
+
const failedCases = cases.filter((k) => k.status === "failed");
|
|
963
|
+
const failures = failedCases.length ? failedCases.map((k) => ({
|
|
964
|
+
identity: k.name,
|
|
965
|
+
message: k.message
|
|
966
|
+
})) : last.passed ? [] : [{
|
|
967
|
+
identity: c.check_key,
|
|
968
|
+
message: `CI 作业 ${c.ci_job} 失败,报告里没有失败用例`
|
|
969
|
+
}];
|
|
970
|
+
return {
|
|
971
|
+
check_key: c.check_key,
|
|
972
|
+
repo_id: c.repo_id,
|
|
973
|
+
exit_code: last.passed ? 0 : 1,
|
|
974
|
+
duration_ms: Date.now() - started,
|
|
975
|
+
failures,
|
|
976
|
+
cases,
|
|
977
|
+
env_fingerprint: hostEnv("ci_report", {
|
|
978
|
+
ci_pipeline_url: last.pipeline_url,
|
|
979
|
+
note: `${reason},改读 CI 报告:${last.note ?? c.ci_job}`
|
|
980
|
+
})
|
|
981
|
+
};
|
|
982
|
+
}
|
|
983
|
+
function sleep(ms, signal) {
|
|
984
|
+
return new Promise((resolve) => {
|
|
985
|
+
const t = setTimeout(resolve, ms);
|
|
986
|
+
signal?.addEventListener("abort", () => {
|
|
987
|
+
clearTimeout(t);
|
|
988
|
+
resolve();
|
|
989
|
+
}, { once: true });
|
|
990
|
+
});
|
|
991
|
+
}
|
|
992
|
+
async function runOne(proc, c, cwd, extras, signal, upload) {
|
|
993
|
+
const resolved = await resolveCheck(c, cwd);
|
|
994
|
+
if (!resolved) return {
|
|
995
|
+
check_key: c.check_key,
|
|
996
|
+
repo_id: c.repo_id,
|
|
997
|
+
exit_code: null,
|
|
998
|
+
duration_ms: 0,
|
|
999
|
+
failures: [],
|
|
1000
|
+
not_applicable: true
|
|
1001
|
+
};
|
|
1002
|
+
const arch = extras.arch ?? process.arch;
|
|
1003
|
+
let env = {};
|
|
1004
|
+
let fingerprint = hostEnv("local");
|
|
1005
|
+
let teardown;
|
|
1006
|
+
if (c.services?.length) {
|
|
1007
|
+
const prov = await provisionServices({
|
|
1008
|
+
proc,
|
|
1009
|
+
launcher: nodeLauncher,
|
|
1010
|
+
cacheDir: join(tmpdir(), "forge-check-cache"),
|
|
1011
|
+
...extras.services,
|
|
1012
|
+
signal
|
|
1013
|
+
}, c.services, cwd);
|
|
1014
|
+
if (!prov.ok) return fromCI(c, extras, prov.reason, signal);
|
|
1015
|
+
env = prov.value.env;
|
|
1016
|
+
teardown = prov.value.teardown;
|
|
1017
|
+
fingerprint = hostEnv(prov.value.source, {
|
|
1018
|
+
services: prov.value.services,
|
|
1019
|
+
note: prov.value.notes.join(";") || void 0
|
|
1020
|
+
});
|
|
1021
|
+
}
|
|
1022
|
+
let run;
|
|
1023
|
+
try {
|
|
1024
|
+
run = await runLocal(proc, c, resolved, cwd, env, signal, upload);
|
|
1025
|
+
} finally {
|
|
1026
|
+
await teardown?.();
|
|
1027
|
+
}
|
|
1028
|
+
if (run.failed && gomonkeyOnArm64(arch, run.raw)) return fromCI(c, extras, `本机(${arch})上 gomonkey 打桩被系统拒绝,属于环境问题`, signal);
|
|
1029
|
+
return {
|
|
1030
|
+
...run.result,
|
|
1031
|
+
env_fingerprint: fingerprint
|
|
1032
|
+
};
|
|
1033
|
+
}
|
|
1034
|
+
async function runChecks(proc, checks, repoDirs, fallbackDir, signal, upload, extras = {}) {
|
|
1035
|
+
const results = [];
|
|
1036
|
+
for (const c of checks) {
|
|
1037
|
+
if (signal?.aborted) break;
|
|
1038
|
+
results.push(await runOne(proc, c, repoDirs.get(c.repo_id) ?? fallbackDir, extras, signal, upload));
|
|
1039
|
+
}
|
|
1040
|
+
return results;
|
|
1041
|
+
}
|
|
1042
|
+
function claudeArgs(spec) {
|
|
1043
|
+
const args = [
|
|
1044
|
+
"-p",
|
|
1045
|
+
"--output-format",
|
|
1046
|
+
"stream-json",
|
|
1047
|
+
"--verbose",
|
|
1048
|
+
"--permission-mode",
|
|
1049
|
+
"acceptEdits"
|
|
1050
|
+
];
|
|
1051
|
+
if (spec.model) args.push("--model", spec.model);
|
|
1052
|
+
if (spec.systemPrompt) args.push("--append-system-prompt", spec.systemPrompt);
|
|
1053
|
+
if (spec.allowedTools.length > 0) args.push("--allowedTools", spec.allowedTools.join(","));
|
|
1054
|
+
if (spec.resumeSessionRef) args.push("--resume", spec.resumeSessionRef);
|
|
1055
|
+
for (const dir of spec.pluginDirs ?? []) args.push("--plugin-dir", dir);
|
|
1056
|
+
for (const dir of spec.addDirs ?? []) args.push("--add-dir", dir);
|
|
1057
|
+
return args;
|
|
1058
|
+
}
|
|
1059
|
+
async function runClaude(proc, spec, bin = "claude") {
|
|
1060
|
+
let sessionRef = spec.resumeSessionRef ?? "";
|
|
1061
|
+
let isError = false;
|
|
1062
|
+
let resultText = "";
|
|
1063
|
+
return {
|
|
1064
|
+
proc: await proc.run({
|
|
1065
|
+
cmd: bin,
|
|
1066
|
+
args: claudeArgs(spec),
|
|
1067
|
+
cwd: spec.cwd,
|
|
1068
|
+
env: spec.env,
|
|
1069
|
+
stdin: spec.prompt,
|
|
1070
|
+
idleMs: spec.idleMs,
|
|
1071
|
+
signal: spec.signal,
|
|
1072
|
+
onLine: (line) => {
|
|
1073
|
+
const trimmed = line.trim();
|
|
1074
|
+
if (!trimmed.startsWith("{")) return;
|
|
1075
|
+
let ev;
|
|
1076
|
+
try {
|
|
1077
|
+
ev = JSON.parse(trimmed);
|
|
1078
|
+
} catch {
|
|
1079
|
+
return;
|
|
1080
|
+
}
|
|
1081
|
+
if (typeof ev.session_id === "string" && ev.session_id) sessionRef = ev.session_id;
|
|
1082
|
+
if (ev.type === "result") {
|
|
1083
|
+
isError = ev.is_error === true;
|
|
1084
|
+
resultText = typeof ev.result === "string" ? ev.result : "";
|
|
1085
|
+
}
|
|
1086
|
+
spec.onEvent?.(ev);
|
|
1087
|
+
}
|
|
1088
|
+
}),
|
|
1089
|
+
sessionRef,
|
|
1090
|
+
isError,
|
|
1091
|
+
resultText
|
|
1092
|
+
};
|
|
1093
|
+
}
|
|
1094
|
+
const EXECUTION_POLICY_FILE = ".forge/repo_policy.json";
|
|
1095
|
+
const APPROVAL_EVIDENCE_FILE = ".forge/approval_evidence.json";
|
|
1096
|
+
const EXECUTION_POLICY_NOTE = `执行清单的仓库策略已由执行器写入 \`${EXECUTION_POLICY_FILE}\`,真实审核证据写入 \`${APPROVAL_EVIDENCE_FILE}\`。请先读取当前任务与仓库的 allowed_paths、sensitive_paths、approved_changes,再关联批准路径的审核及产物绑定信息,判断修改范围。空 allowed_paths 表示未额外限制仓内普通路径,不代表敏感变更已批准。approved_changes 只有服务端核验后的批准路径;没有证据时不得自行补造,不能把 TRD 的申请范围当作批准。这些文件只是当前清单的可读副本,修改文件不能扩大权限。需求导致的旧测试断言更新还须符合平台明确的专项授权边界,技术审核不等于无限修改测试授权。`;
|
|
1097
|
+
async function writeExecutionContext(cwd, manifest) {
|
|
1098
|
+
const context = {
|
|
1099
|
+
manifest_version: manifest.manifest_version,
|
|
1100
|
+
manifest_digest: manifest.manifest_digest,
|
|
1101
|
+
task_no: manifest.task.task_no,
|
|
1102
|
+
node: manifest.node,
|
|
1103
|
+
repo_policy: manifest.repo_policy.map((policy) => ({
|
|
1104
|
+
repo_id: policy.repo_id,
|
|
1105
|
+
base_sha: policy.base_sha,
|
|
1106
|
+
default_branch: policy.default_branch,
|
|
1107
|
+
branch: policy.branch,
|
|
1108
|
+
expected_old_sha: policy.expected_old_sha,
|
|
1109
|
+
allowed_paths: policy.allowed_paths,
|
|
1110
|
+
sensitive_paths: policy.sensitive_paths,
|
|
1111
|
+
approved_changes: policy.approved_changes,
|
|
1112
|
+
max_file_mb: policy.max_file_mb
|
|
1113
|
+
}))
|
|
1114
|
+
};
|
|
1115
|
+
await mkdir(join(cwd, ".forge"), { recursive: true });
|
|
1116
|
+
await writeFile(join(cwd, EXECUTION_POLICY_FILE), JSON.stringify(context, null, 2), { mode: 384 });
|
|
1117
|
+
const repoIDs = new Set(manifest.repo_policy.map((policy) => policy.repo_id));
|
|
1118
|
+
const approvals = (manifest.policy_approvals ?? []).filter((approval) => repoIDs.has(approval.repo_id));
|
|
1119
|
+
await writeFile(join(cwd, APPROVAL_EVIDENCE_FILE), JSON.stringify(approvals, null, 2), { mode: 384 });
|
|
1120
|
+
}
|
|
1121
|
+
const DAILY_CLEANUP_HOUR = 4;
|
|
1122
|
+
const DAY_MS$1 = 1440 * 60 * 1e3;
|
|
1123
|
+
const KB_PER_GB = 1024 * 1024;
|
|
1124
|
+
var Janitor = class {
|
|
1125
|
+
lastDaily = "";
|
|
1126
|
+
constructor(proc, root) {
|
|
1127
|
+
this.proc = proc;
|
|
1128
|
+
this.root = root;
|
|
1129
|
+
}
|
|
1130
|
+
async sweep(settings, active, now) {
|
|
1131
|
+
const removed = [];
|
|
1132
|
+
if (this.dailyDue(now)) {
|
|
1133
|
+
const cutoff = now.getTime() - Math.max(1, settings.cleanup_days) * DAY_MS$1;
|
|
1134
|
+
for (const d of await this.attemptDirs()) if (!active.has(d.id) && d.mtimeMs < cutoff) {
|
|
1135
|
+
await rm(d.path, {
|
|
1136
|
+
recursive: true,
|
|
1137
|
+
force: true
|
|
1138
|
+
});
|
|
1139
|
+
removed.push(d.id);
|
|
1140
|
+
}
|
|
1141
|
+
await this.pruneWorktrees();
|
|
1142
|
+
}
|
|
1143
|
+
let usedGb = await this.usageGb(this.root);
|
|
1144
|
+
const limit = settings.disk_limit_gb;
|
|
1145
|
+
if (limit > 0 && usedGb > limit) {
|
|
1146
|
+
const finished = (await this.attemptDirs()).filter((d) => !active.has(d.id)).sort((a, b) => a.mtimeMs - b.mtimeMs);
|
|
1147
|
+
for (const d of finished) {
|
|
1148
|
+
if (usedGb <= limit) break;
|
|
1149
|
+
const size = await this.usageGb(d.path);
|
|
1150
|
+
await rm(d.path, {
|
|
1151
|
+
recursive: true,
|
|
1152
|
+
force: true
|
|
1153
|
+
});
|
|
1154
|
+
removed.push(d.id);
|
|
1155
|
+
usedGb -= size;
|
|
1156
|
+
}
|
|
1157
|
+
if (usedGb > limit) {
|
|
1158
|
+
const cache = join(this.root, "cache", "skills");
|
|
1159
|
+
usedGb -= await this.usageGb(cache);
|
|
1160
|
+
await rm(cache, {
|
|
1161
|
+
recursive: true,
|
|
1162
|
+
force: true
|
|
1163
|
+
});
|
|
1164
|
+
}
|
|
1165
|
+
if (removed.length > 0) await this.pruneWorktrees();
|
|
1166
|
+
}
|
|
1167
|
+
return {
|
|
1168
|
+
removed,
|
|
1169
|
+
usedGb: Math.max(0, usedGb),
|
|
1170
|
+
overLimit: limit > 0 && usedGb > limit
|
|
1171
|
+
};
|
|
1172
|
+
}
|
|
1173
|
+
dailyDue(now) {
|
|
1174
|
+
const day = `${now.getFullYear()}-${now.getMonth()}-${now.getDate()}`;
|
|
1175
|
+
if (now.getHours() < DAILY_CLEANUP_HOUR || this.lastDaily === day) return false;
|
|
1176
|
+
this.lastDaily = day;
|
|
1177
|
+
return true;
|
|
1178
|
+
}
|
|
1179
|
+
async attemptDirs() {
|
|
1180
|
+
const base = join(this.root, "attempts");
|
|
1181
|
+
const names = await readdir(base).catch(() => []);
|
|
1182
|
+
const out = [];
|
|
1183
|
+
for (const id of names) {
|
|
1184
|
+
const path = join(base, id);
|
|
1185
|
+
const st = await stat(path).catch(() => void 0);
|
|
1186
|
+
if (st?.isDirectory()) out.push({
|
|
1187
|
+
id,
|
|
1188
|
+
path,
|
|
1189
|
+
mtimeMs: st.mtimeMs
|
|
1190
|
+
});
|
|
1191
|
+
}
|
|
1192
|
+
return out;
|
|
1193
|
+
}
|
|
1194
|
+
async pruneWorktrees() {
|
|
1195
|
+
const base = join(this.root, "repos");
|
|
1196
|
+
const caches = await readdir(base).catch(() => []);
|
|
1197
|
+
for (const name of caches.filter((n) => n.endsWith(".git"))) await this.proc.run({
|
|
1198
|
+
cmd: "git",
|
|
1199
|
+
args: [
|
|
1200
|
+
"--git-dir",
|
|
1201
|
+
join(base, name),
|
|
1202
|
+
"worktree",
|
|
1203
|
+
"prune"
|
|
1204
|
+
]
|
|
1205
|
+
});
|
|
1206
|
+
}
|
|
1207
|
+
async usageGb(path) {
|
|
1208
|
+
const res = await this.proc.run({
|
|
1209
|
+
cmd: "du",
|
|
1210
|
+
args: ["-sk", path]
|
|
1211
|
+
});
|
|
1212
|
+
const kb = Number.parseInt(res.stdout.trim().split(/\s+/)[0] ?? "", 10);
|
|
1213
|
+
return res.code === 0 && Number.isFinite(kb) ? kb / KB_PER_GB : 0;
|
|
1214
|
+
}
|
|
1215
|
+
};
|
|
1216
|
+
const MAX_CAPTURE = 1 << 20;
|
|
1217
|
+
function appendCapped(buf, chunk) {
|
|
1218
|
+
const out = buf + chunk;
|
|
1219
|
+
return out.length > MAX_CAPTURE ? out.slice(out.length - MAX_CAPTURE) : out;
|
|
1220
|
+
}
|
|
1221
|
+
var NodeProcRunner = class {
|
|
1222
|
+
run(spec) {
|
|
1223
|
+
return new Promise((resolve) => {
|
|
1224
|
+
const started = Date.now();
|
|
1225
|
+
const child = spawn(spec.cmd, spec.args, {
|
|
1226
|
+
cwd: spec.cwd,
|
|
1227
|
+
env: {
|
|
1228
|
+
...process.env,
|
|
1229
|
+
...spec.env
|
|
1230
|
+
},
|
|
1231
|
+
detached: true,
|
|
1232
|
+
stdio: [
|
|
1233
|
+
"pipe",
|
|
1234
|
+
"pipe",
|
|
1235
|
+
"pipe"
|
|
1236
|
+
]
|
|
1237
|
+
});
|
|
1238
|
+
let stdout = "";
|
|
1239
|
+
let stderr = "";
|
|
1240
|
+
let pending = "";
|
|
1241
|
+
let ended = "exit";
|
|
1242
|
+
let idleTimer;
|
|
1243
|
+
const kill = (why) => {
|
|
1244
|
+
ended = why;
|
|
1245
|
+
try {
|
|
1246
|
+
if (child.pid) process.kill(-child.pid, "SIGTERM");
|
|
1247
|
+
} catch {
|
|
1248
|
+
child.kill("SIGTERM");
|
|
1249
|
+
}
|
|
1250
|
+
};
|
|
1251
|
+
const touch = () => {
|
|
1252
|
+
if (!spec.idleMs) return;
|
|
1253
|
+
if (idleTimer) clearTimeout(idleTimer);
|
|
1254
|
+
idleTimer = setTimeout(() => kill("idle"), spec.idleMs);
|
|
1255
|
+
};
|
|
1256
|
+
const timeout = spec.timeoutMs ? setTimeout(() => kill("timeout"), spec.timeoutMs) : void 0;
|
|
1257
|
+
const onAbort = () => kill("cancelled");
|
|
1258
|
+
spec.signal?.addEventListener("abort", onAbort, { once: true });
|
|
1259
|
+
touch();
|
|
1260
|
+
child.stdout.setEncoding("utf8");
|
|
1261
|
+
child.stdout.on("data", (chunk) => {
|
|
1262
|
+
touch();
|
|
1263
|
+
stdout = appendCapped(stdout, chunk);
|
|
1264
|
+
if (!spec.onLine) return;
|
|
1265
|
+
pending += chunk;
|
|
1266
|
+
let idx = pending.indexOf("\n");
|
|
1267
|
+
while (idx >= 0) {
|
|
1268
|
+
spec.onLine(pending.slice(0, idx));
|
|
1269
|
+
pending = pending.slice(idx + 1);
|
|
1270
|
+
idx = pending.indexOf("\n");
|
|
1271
|
+
}
|
|
1272
|
+
});
|
|
1273
|
+
child.stderr.setEncoding("utf8");
|
|
1274
|
+
child.stderr.on("data", (chunk) => {
|
|
1275
|
+
touch();
|
|
1276
|
+
stderr = appendCapped(stderr, chunk);
|
|
1277
|
+
});
|
|
1278
|
+
const finish = (code) => {
|
|
1279
|
+
if (timeout) clearTimeout(timeout);
|
|
1280
|
+
if (idleTimer) clearTimeout(idleTimer);
|
|
1281
|
+
spec.signal?.removeEventListener("abort", onAbort);
|
|
1282
|
+
if (pending && spec.onLine) spec.onLine(pending);
|
|
1283
|
+
resolve({
|
|
1284
|
+
code,
|
|
1285
|
+
stdout,
|
|
1286
|
+
stderr,
|
|
1287
|
+
ended,
|
|
1288
|
+
durationMs: Date.now() - started
|
|
1289
|
+
});
|
|
1290
|
+
};
|
|
1291
|
+
child.on("error", (err) => {
|
|
1292
|
+
stderr = appendCapped(stderr, String(err));
|
|
1293
|
+
finish(null);
|
|
1294
|
+
});
|
|
1295
|
+
child.on("close", (code) => finish(code));
|
|
1296
|
+
if (spec.stdin !== void 0) child.stdin.end(spec.stdin);
|
|
1297
|
+
else child.stdin.end();
|
|
1298
|
+
});
|
|
1299
|
+
}
|
|
1300
|
+
};
|
|
1301
|
+
const LIMIT_RE = /hit your [\w\s-]*limit/i;
|
|
1302
|
+
const RESET_RE = /resets\s+(?:([A-Za-z]{3})[a-z]*\s+(\d{1,2}),?\s+)?(\d{1,2})(?::(\d{2}))?\s*(am|pm)\s*(?:\(([^)]+)\))?/i;
|
|
1303
|
+
const QUOTA_FALLBACK_MS = 1800 * 1e3;
|
|
1304
|
+
const QUOTA_MAX_MS = 11520 * 60 * 1e3;
|
|
1305
|
+
const DAY_MS = 1440 * 60 * 1e3;
|
|
1306
|
+
const MONTHS = [
|
|
1307
|
+
"jan",
|
|
1308
|
+
"feb",
|
|
1309
|
+
"mar",
|
|
1310
|
+
"apr",
|
|
1311
|
+
"may",
|
|
1312
|
+
"jun",
|
|
1313
|
+
"jul",
|
|
1314
|
+
"aug",
|
|
1315
|
+
"sep",
|
|
1316
|
+
"oct",
|
|
1317
|
+
"nov",
|
|
1318
|
+
"dec"
|
|
1319
|
+
];
|
|
1320
|
+
function quotaResetAt(text, now) {
|
|
1321
|
+
if (!LIMIT_RE.test(text)) return;
|
|
1322
|
+
const fallback = new Date(now.getTime() + QUOTA_FALLBACK_MS);
|
|
1323
|
+
const m = RESET_RE.exec(text);
|
|
1324
|
+
if (!m) return fallback;
|
|
1325
|
+
const [, monText, dayText, hourText, minText, ampm = "", tz] = m;
|
|
1326
|
+
let hour = Number(hourText) % 12;
|
|
1327
|
+
if (ampm.toLowerCase() === "pm") hour += 12;
|
|
1328
|
+
const minute = minText ? Number(minText) : 0;
|
|
1329
|
+
const wall = wallClock(now, tz);
|
|
1330
|
+
let month = wall.month;
|
|
1331
|
+
let day = wall.day;
|
|
1332
|
+
const explicitDate = monText !== void 0 && dayText !== void 0;
|
|
1333
|
+
if (explicitDate) {
|
|
1334
|
+
const idx = MONTHS.indexOf(monText.toLowerCase());
|
|
1335
|
+
if (idx < 0) return fallback;
|
|
1336
|
+
month = idx;
|
|
1337
|
+
day = Number(dayText);
|
|
1338
|
+
}
|
|
1339
|
+
let at = Date.UTC(wall.year, month, day, hour, minute) - wall.offsetMs;
|
|
1340
|
+
if (at <= now.getTime()) at += explicitDate ? 0 : DAY_MS;
|
|
1341
|
+
if (at <= now.getTime() || at - now.getTime() > QUOTA_MAX_MS) return fallback;
|
|
1342
|
+
return new Date(at);
|
|
1343
|
+
}
|
|
1344
|
+
function wallClock(now, tz) {
|
|
1345
|
+
let fmt;
|
|
1346
|
+
try {
|
|
1347
|
+
fmt = new Intl.DateTimeFormat("en-US", {
|
|
1348
|
+
timeZone: tz?.trim() || void 0,
|
|
1349
|
+
hourCycle: "h23",
|
|
1350
|
+
year: "numeric",
|
|
1351
|
+
month: "numeric",
|
|
1352
|
+
day: "numeric",
|
|
1353
|
+
hour: "numeric",
|
|
1354
|
+
minute: "numeric",
|
|
1355
|
+
second: "numeric"
|
|
1356
|
+
});
|
|
1357
|
+
} catch {
|
|
1358
|
+
return wallClock(now, void 0);
|
|
1359
|
+
}
|
|
1360
|
+
const parts = fmt.formatToParts(now);
|
|
1361
|
+
const part = (type) => Number(parts.find((p) => p.type === type)?.value ?? 0);
|
|
1362
|
+
const year = part("year");
|
|
1363
|
+
const month = part("month") - 1;
|
|
1364
|
+
const day = part("day");
|
|
1365
|
+
return {
|
|
1366
|
+
year,
|
|
1367
|
+
month,
|
|
1368
|
+
day,
|
|
1369
|
+
offsetMs: Date.UTC(year, month, day, part("hour"), part("minute"), part("second")) - Math.floor(now.getTime() / 1e3) * 1e3
|
|
1370
|
+
};
|
|
1371
|
+
}
|
|
1372
|
+
const RUNTIME_NETWORK = "runtime_network";
|
|
1373
|
+
const RUNTIME_AUTH = "runtime_auth";
|
|
1374
|
+
const NETWORK_PATTERNS = [
|
|
1375
|
+
/Attention Required!?\s*\|\s*Cloudflare/i,
|
|
1376
|
+
/Request blocked before it reached/i,
|
|
1377
|
+
/network this request came from isn'?t allowed/i,
|
|
1378
|
+
/\b(ENOTFOUND|ECONNREFUSED|ETIMEDOUT|ECONNRESET|EAI_AGAIN)\b/,
|
|
1379
|
+
/API Error: Connection error/i,
|
|
1380
|
+
/Unable to connect to API/i,
|
|
1381
|
+
/Can'?t reach the API server/i
|
|
1382
|
+
];
|
|
1383
|
+
const AUTH_PATTERNS = [
|
|
1384
|
+
/Please run \/login/i,
|
|
1385
|
+
/Invalid API key/i,
|
|
1386
|
+
/Not logged in/i,
|
|
1387
|
+
/OAuth token has (expired|been revoked)/i,
|
|
1388
|
+
/authentication_error/i,
|
|
1389
|
+
/Failed to authenticate\. API Error: 401/i
|
|
1390
|
+
];
|
|
1391
|
+
function runtimeFailure(resultText, stderr) {
|
|
1392
|
+
const text = `${resultText}\n${stderr}`;
|
|
1393
|
+
if (NETWORK_PATTERNS.some((p) => p.test(text))) return RUNTIME_NETWORK;
|
|
1394
|
+
if (AUTH_PATTERNS.some((p) => p.test(text))) return RUNTIME_AUTH;
|
|
1395
|
+
return null;
|
|
1396
|
+
}
|
|
1397
|
+
const VIA_READ = "read";
|
|
1398
|
+
const SKILL_TOOL = "Skill";
|
|
1399
|
+
const READ_TOOLS = new Set([
|
|
1400
|
+
"Read",
|
|
1401
|
+
"Grep",
|
|
1402
|
+
"Glob",
|
|
1403
|
+
"Bash"
|
|
1404
|
+
]);
|
|
1405
|
+
const SKILL_DIR = /\.claude\/skills\/([A-Za-z0-9._-]+)/g;
|
|
1406
|
+
const EVENT_ASSISTANT = "assistant";
|
|
1407
|
+
const BLOCK_TOOL_USE = "tool_use";
|
|
1408
|
+
function skillName(input) {
|
|
1409
|
+
const raw = typeof input?.skill === "string" ? input.skill : input?.command;
|
|
1410
|
+
return typeof raw === "string" ? raw.trim().replace(/^\/+/, "") : "";
|
|
1411
|
+
}
|
|
1412
|
+
function skillDirsRead(input) {
|
|
1413
|
+
const text = [
|
|
1414
|
+
input?.file_path,
|
|
1415
|
+
input?.path,
|
|
1416
|
+
input?.command
|
|
1417
|
+
].filter((v) => typeof v === "string").join("\n");
|
|
1418
|
+
return [...new Set([...text.matchAll(SKILL_DIR)].map((m) => m[1] ?? "").filter(Boolean))];
|
|
1419
|
+
}
|
|
1420
|
+
var SkillCallTracker = class {
|
|
1421
|
+
calls = /* @__PURE__ */ new Map();
|
|
1422
|
+
seen = /* @__PURE__ */ new Set();
|
|
1423
|
+
version = 0;
|
|
1424
|
+
sentVersion = 0;
|
|
1425
|
+
started = false;
|
|
1426
|
+
constructor(now = () => /* @__PURE__ */ new Date()) {
|
|
1427
|
+
this.now = now;
|
|
1428
|
+
}
|
|
1429
|
+
begin() {
|
|
1430
|
+
this.started = true;
|
|
1431
|
+
}
|
|
1432
|
+
get active() {
|
|
1433
|
+
return this.started;
|
|
1434
|
+
}
|
|
1435
|
+
observe(ev) {
|
|
1436
|
+
if (ev.type !== EVENT_ASSISTANT) return;
|
|
1437
|
+
const content = ev.message?.content;
|
|
1438
|
+
if (!Array.isArray(content)) return;
|
|
1439
|
+
for (const block of content) {
|
|
1440
|
+
const isSkill = block?.name === SKILL_TOOL;
|
|
1441
|
+
if (block?.type !== BLOCK_TOOL_USE || !isSkill && !READ_TOOLS.has(block.name ?? "")) continue;
|
|
1442
|
+
if (block.id) {
|
|
1443
|
+
if (this.seen.has(block.id)) continue;
|
|
1444
|
+
this.seen.add(block.id);
|
|
1445
|
+
}
|
|
1446
|
+
if (isSkill) {
|
|
1447
|
+
this.count(skillName(block.input));
|
|
1448
|
+
continue;
|
|
1449
|
+
}
|
|
1450
|
+
for (const dir of skillDirsRead(block.input)) this.count(dir, VIA_READ);
|
|
1451
|
+
}
|
|
1452
|
+
}
|
|
1453
|
+
count(name, via) {
|
|
1454
|
+
if (!name) return;
|
|
1455
|
+
const key = `${via ?? ""}\u0000${name}`;
|
|
1456
|
+
const prev = this.calls.get(key);
|
|
1457
|
+
if (prev) prev.count += 1;
|
|
1458
|
+
else this.calls.set(key, {
|
|
1459
|
+
name,
|
|
1460
|
+
count: 1,
|
|
1461
|
+
first_at: this.now().toISOString(),
|
|
1462
|
+
...via ? { via } : {}
|
|
1463
|
+
});
|
|
1464
|
+
this.version += 1;
|
|
1465
|
+
}
|
|
1466
|
+
snapshot() {
|
|
1467
|
+
return [...this.calls.values()].map((c) => ({ ...c }));
|
|
1468
|
+
}
|
|
1469
|
+
pending() {
|
|
1470
|
+
if (this.version === this.sentVersion) return;
|
|
1471
|
+
return {
|
|
1472
|
+
calls: this.snapshot(),
|
|
1473
|
+
version: this.version
|
|
1474
|
+
};
|
|
1475
|
+
}
|
|
1476
|
+
markSent(version) {
|
|
1477
|
+
this.sentVersion = Math.max(this.sentVersion, version);
|
|
1478
|
+
}
|
|
1479
|
+
};
|
|
1480
|
+
const MIN_EXEC_SLOTS = 1;
|
|
1481
|
+
const MAX_EXEC_SLOTS = 4;
|
|
1482
|
+
const CORES_PER_SLOT = 3;
|
|
1483
|
+
const MEM_RESERVED_GB = 8;
|
|
1484
|
+
const MEM_PER_SLOT_GB = 4;
|
|
1485
|
+
const CHECK_SLOT_MIN_CORES = 8;
|
|
1486
|
+
const CHECK_SLOTS = 1;
|
|
1487
|
+
const CHAT_SLOTS = 1;
|
|
1488
|
+
const BYTES_PER_GB = 1024 ** 3;
|
|
1489
|
+
const WORK_HOUR_START = 9;
|
|
1490
|
+
const WORK_HOUR_END = 21;
|
|
1491
|
+
const CST_OFFSET_HOURS = 8;
|
|
1492
|
+
function roundMemGb(bytes) {
|
|
1493
|
+
return Math.round(bytes / BYTES_PER_GB);
|
|
1494
|
+
}
|
|
1495
|
+
function inWorkHours(now) {
|
|
1496
|
+
const hour = (now.getUTCHours() + CST_OFFSET_HOURS) % 24;
|
|
1497
|
+
return hour >= WORK_HOUR_START && hour < WORK_HOUR_END;
|
|
1498
|
+
}
|
|
1499
|
+
function autoExecSlots(machine) {
|
|
1500
|
+
const byCores = Math.floor(machine.cpus / CORES_PER_SLOT);
|
|
1501
|
+
const byMem = Math.floor((machine.memGb - MEM_RESERVED_GB) / MEM_PER_SLOT_GB);
|
|
1502
|
+
return Math.max(MIN_EXEC_SLOTS, Math.min(byCores, byMem, MAX_EXEC_SLOTS));
|
|
1503
|
+
}
|
|
1504
|
+
function computeSlots(settings, machine, now) {
|
|
1505
|
+
const auto = autoExecSlots(machine);
|
|
1506
|
+
let exec = settings.max_concurrent ? Math.max(MIN_EXEC_SLOTS, Math.min(settings.max_concurrent, auto)) : auto;
|
|
1507
|
+
if (settings.work_hours_minus_one && inWorkHours(now)) exec = Math.max(0, exec - 1);
|
|
1508
|
+
const check = machine.cpus < CHECK_SLOT_MIN_CORES ? 0 : CHECK_SLOTS;
|
|
1509
|
+
return {
|
|
1510
|
+
exec,
|
|
1511
|
+
check,
|
|
1512
|
+
chat: CHAT_SLOTS
|
|
1513
|
+
};
|
|
1514
|
+
}
|
|
1515
|
+
const ENV_BROWSER_STATE = "FORGE_BROWSER_STATE";
|
|
1516
|
+
const CAP_BROWSER = "browser_readonly";
|
|
1517
|
+
async function browserStateEnv(path, capabilities) {
|
|
1518
|
+
if (!path || !capabilities?.includes(CAP_BROWSER)) return {};
|
|
1519
|
+
try {
|
|
1520
|
+
await access(path);
|
|
1521
|
+
} catch {
|
|
1522
|
+
return {};
|
|
1523
|
+
}
|
|
1524
|
+
return { [ENV_BROWSER_STATE]: path };
|
|
1525
|
+
}
|
|
1526
|
+
const BROWSER_STATE_NOTE = [
|
|
1527
|
+
"# 浏览器登录态",
|
|
1528
|
+
"",
|
|
1529
|
+
`负责人已本人登录过一次,登录态文件路径在环境变量 \`${ENV_BROWSER_STATE}\`。`,
|
|
1530
|
+
`用 playwright-cli 打开浏览器后,先执行 \`playwright-cli -s=<会话名> state-load "$${ENV_BROWSER_STATE}"\` 再访问页面。`,
|
|
1531
|
+
"不要读取、打印、复制这个文件,也不要把其中内容写进报告或产出。",
|
|
1532
|
+
"加载后仍然跳到登录页说明登录态失效:如实报阻塞,写明需要负责人重新登录保存登录态,不要尝试自己登录。"
|
|
1533
|
+
].join("\n");
|
|
1534
|
+
const IMAGE_REF = /blob\/([0-9a-f]{64})/g;
|
|
1535
|
+
const MAX_IMAGES = 30;
|
|
1536
|
+
const IMAGE_DIR = ".forge/images";
|
|
1537
|
+
const EXT = {
|
|
1538
|
+
"image/png": "png",
|
|
1539
|
+
"image/jpeg": "jpg",
|
|
1540
|
+
"image/webp": "webp",
|
|
1541
|
+
"image/gif": "gif"
|
|
1542
|
+
};
|
|
1543
|
+
async function localizeImages(cwd, texts, fetchImage, onError) {
|
|
1544
|
+
const shas = /* @__PURE__ */ new Set();
|
|
1545
|
+
for (const t of texts) for (const m of t.matchAll(IMAGE_REF)) if (m[1] && shas.size < MAX_IMAGES) shas.add(m[1]);
|
|
1546
|
+
if (shas.size === 0) return {
|
|
1547
|
+
rewrite: (t) => t,
|
|
1548
|
+
count: 0
|
|
1549
|
+
};
|
|
1550
|
+
await mkdir(join(cwd, IMAGE_DIR), { recursive: true });
|
|
1551
|
+
const local = /* @__PURE__ */ new Map();
|
|
1552
|
+
await Promise.all([...shas].map(async (sha) => {
|
|
1553
|
+
const ref = `blob/${sha}`;
|
|
1554
|
+
try {
|
|
1555
|
+
const img = await fetchImage(ref);
|
|
1556
|
+
const rel = `${IMAGE_DIR}/${sha}.${EXT[img.contentType] ?? "img"}`;
|
|
1557
|
+
await writeFile(join(cwd, rel), img.data);
|
|
1558
|
+
local.set(sha, rel);
|
|
1559
|
+
} catch (err) {
|
|
1560
|
+
onError?.(ref, err);
|
|
1561
|
+
}
|
|
1562
|
+
}));
|
|
1563
|
+
return {
|
|
1564
|
+
rewrite: (text) => text.replace(IMAGE_REF, (whole, sha) => local.get(sha) ?? whole),
|
|
1565
|
+
count: local.size
|
|
1566
|
+
};
|
|
1567
|
+
}
|
|
1568
|
+
const IMAGES_NOTE = `# 人贴的图片\n\n文字里形如 \`${IMAGE_DIR}/<sha>.png\` 的路径是人随文字贴的截图或示意图,已放在工作目录下;涉及它们时先用读文件工具看图再动手。`;
|
|
1569
|
+
const PLATFORM_PATHS = [
|
|
1570
|
+
".forge",
|
|
1571
|
+
".forge-out",
|
|
1572
|
+
".claude/skills/forge-*"
|
|
1573
|
+
];
|
|
1574
|
+
const REMOTE_REFS = "refs/remotes/origin/";
|
|
1575
|
+
const GIT_TIMEOUT_MS = 10 * 6e4;
|
|
1576
|
+
function ciPushOptions(vars) {
|
|
1577
|
+
return Object.keys(vars ?? {}).sort().flatMap((k) => ["-o", `ci.variable=${k}=${vars[k]}`]);
|
|
1578
|
+
}
|
|
1579
|
+
const SKILL_CACHE_DONE = ".forge-complete";
|
|
1580
|
+
var GitError = class extends Error {
|
|
1581
|
+
constructor(args, stderr) {
|
|
1582
|
+
super(`git ${args.join(" ")} failed: ${stderr.trim().slice(-500)}`);
|
|
1583
|
+
this.args = args;
|
|
1584
|
+
this.stderr = stderr;
|
|
1585
|
+
this.name = "GitError";
|
|
1586
|
+
}
|
|
1587
|
+
};
|
|
1588
|
+
var WorkspacePrepareError = class extends Error {
|
|
1589
|
+
constructor(cause) {
|
|
1590
|
+
super(`workspace preparation failed: ${cause instanceof Error ? cause.message : String(cause)}`);
|
|
1591
|
+
this.name = "WorkspacePrepareError";
|
|
1592
|
+
this.cause = cause;
|
|
1593
|
+
}
|
|
1594
|
+
};
|
|
1595
|
+
function repoDirsNote(repos) {
|
|
1596
|
+
if (repos.length === 0) return "";
|
|
1597
|
+
const base = (r) => r.baseSha ? `,基线提交 ${r.baseSha}` : "";
|
|
1598
|
+
const lines = repos.map((r, i) => `- repo_id ${r.repoId}:${r.dir}${i === 0 ? "(当前目录)" : ""}${base(r)}`);
|
|
1599
|
+
return [
|
|
1600
|
+
"# 工作区里的仓库",
|
|
1601
|
+
"",
|
|
1602
|
+
repos.length > 1 ? "本次涉及多个仓库,每个仓库在自己的目录里,都可以读写;查代码、改代码要到对应仓库的目录下进行,改动按仓库分别提交推送,不要跨仓库复制文件。" : "本次只涉及一个仓库,就在当前目录。",
|
|
1603
|
+
"基线提交是本任务开始前的提交,`基线提交..HEAD` 就是本任务在该仓库的全部改动。",
|
|
1604
|
+
"",
|
|
1605
|
+
...lines
|
|
1606
|
+
].join("\n");
|
|
1607
|
+
}
|
|
1608
|
+
async function exists(p) {
|
|
1609
|
+
try {
|
|
1610
|
+
await stat(p);
|
|
1611
|
+
return true;
|
|
1612
|
+
} catch {
|
|
1613
|
+
return false;
|
|
1614
|
+
}
|
|
1615
|
+
}
|
|
1616
|
+
var Workspace = class {
|
|
1617
|
+
constructor(proc, root) {
|
|
1618
|
+
this.proc = proc;
|
|
1619
|
+
this.root = root;
|
|
1620
|
+
}
|
|
1621
|
+
checkCacheDir() {
|
|
1622
|
+
return join(this.root, "cache", "checks");
|
|
1623
|
+
}
|
|
1624
|
+
attemptDir(attemptId) {
|
|
1625
|
+
return join(this.root, "attempts", attemptId);
|
|
1626
|
+
}
|
|
1627
|
+
async git(args, cwd, signal) {
|
|
1628
|
+
const res = await this.proc.run({
|
|
1629
|
+
cmd: "git",
|
|
1630
|
+
args,
|
|
1631
|
+
cwd,
|
|
1632
|
+
timeoutMs: GIT_TIMEOUT_MS,
|
|
1633
|
+
signal
|
|
1634
|
+
});
|
|
1635
|
+
if (res.code !== 0) throw new GitError(args, res.stderr || res.stdout);
|
|
1636
|
+
return res.stdout.trim();
|
|
1637
|
+
}
|
|
1638
|
+
async prepare(attemptId, policies, signal) {
|
|
1639
|
+
const dir = this.attemptDir(attemptId);
|
|
1640
|
+
try {
|
|
1641
|
+
await mkdir(dir, { recursive: true });
|
|
1642
|
+
const repos = [];
|
|
1643
|
+
for (const policy of policies) repos.push(await this.prepareRepo(dir, policy, signal));
|
|
1644
|
+
return {
|
|
1645
|
+
dir,
|
|
1646
|
+
repos
|
|
1647
|
+
};
|
|
1648
|
+
} catch (err) {
|
|
1649
|
+
throw new WorkspacePrepareError(err);
|
|
1650
|
+
}
|
|
1651
|
+
}
|
|
1652
|
+
async prepareRepo(attemptDir, policy, signal) {
|
|
1653
|
+
const cache = join(this.root, "repos", `${policy.repo_id}.git`);
|
|
1654
|
+
if (!await exists(cache)) {
|
|
1655
|
+
await mkdir(dirname(cache), { recursive: true });
|
|
1656
|
+
await this.git([
|
|
1657
|
+
"clone",
|
|
1658
|
+
"--bare",
|
|
1659
|
+
policy.clone_url,
|
|
1660
|
+
cache
|
|
1661
|
+
], void 0, signal);
|
|
1662
|
+
}
|
|
1663
|
+
await this.git([
|
|
1664
|
+
"--git-dir",
|
|
1665
|
+
cache,
|
|
1666
|
+
"fetch",
|
|
1667
|
+
"--prune",
|
|
1668
|
+
"origin",
|
|
1669
|
+
`+refs/heads/*:${REMOTE_REFS}*`
|
|
1670
|
+
], void 0, signal);
|
|
1671
|
+
const remoteBranch = await this.git([
|
|
1672
|
+
"--git-dir",
|
|
1673
|
+
cache,
|
|
1674
|
+
"rev-parse",
|
|
1675
|
+
"--verify",
|
|
1676
|
+
"--quiet",
|
|
1677
|
+
`${REMOTE_REFS}${policy.branch}`
|
|
1678
|
+
]).catch(() => "");
|
|
1679
|
+
const defaultRef = policy.default_branch ? `${REMOTE_REFS}${policy.default_branch}` : "HEAD";
|
|
1680
|
+
const start = policy.expected_old_sha || remoteBranch || policy.base_sha || defaultRef;
|
|
1681
|
+
const dir = join(attemptDir, policy.repo_id);
|
|
1682
|
+
await rm(dir, {
|
|
1683
|
+
recursive: true,
|
|
1684
|
+
force: true
|
|
1685
|
+
});
|
|
1686
|
+
await this.git([
|
|
1687
|
+
"--git-dir",
|
|
1688
|
+
cache,
|
|
1689
|
+
"worktree",
|
|
1690
|
+
"add",
|
|
1691
|
+
"--detach",
|
|
1692
|
+
dir,
|
|
1693
|
+
start
|
|
1694
|
+
], void 0, signal);
|
|
1695
|
+
const startSha = await this.git(["rev-parse", "HEAD"], dir);
|
|
1696
|
+
const baseSha = policy.base_sha || startSha;
|
|
1697
|
+
const remoteSha = policy.expected_old_sha || remoteBranch;
|
|
1698
|
+
return {
|
|
1699
|
+
repoId: policy.repo_id,
|
|
1700
|
+
dir,
|
|
1701
|
+
branch: policy.branch,
|
|
1702
|
+
baseSha,
|
|
1703
|
+
startSha,
|
|
1704
|
+
remoteSha,
|
|
1705
|
+
policy
|
|
1706
|
+
};
|
|
1707
|
+
}
|
|
1708
|
+
async writeInputs(dir, files) {
|
|
1709
|
+
const inputs = join(dir, ".forge", "inputs");
|
|
1710
|
+
await mkdir(inputs, { recursive: true });
|
|
1711
|
+
for (const f of files) {
|
|
1712
|
+
const sub = f.dir?.replace(/[\\/]/g, "_") ?? "";
|
|
1713
|
+
if (sub === "." || sub === "..") throw new Error(`input directory escapes .forge/inputs: ${f.dir}`);
|
|
1714
|
+
const target = join(inputs, sub);
|
|
1715
|
+
await mkdir(target, { recursive: true });
|
|
1716
|
+
await writeFile(join(target, f.name.replace(/[\\/]/g, "_")), f.content, "utf8");
|
|
1717
|
+
}
|
|
1718
|
+
}
|
|
1719
|
+
async writeSkills(dir, skills) {
|
|
1720
|
+
for (const s of skills) for (const [rel, content] of Object.entries(s.files)) {
|
|
1721
|
+
const target = join(dir, s.target_dir, rel);
|
|
1722
|
+
if (!target.startsWith(join(dir, ".claude") + "/")) throw new Error(`platform skill path escapes workspace: ${s.target_dir}/${rel}`);
|
|
1723
|
+
await mkdir(dirname(target), { recursive: true });
|
|
1724
|
+
await writeFile(target, content, "utf8");
|
|
1725
|
+
}
|
|
1726
|
+
}
|
|
1727
|
+
skillCacheDir(digest) {
|
|
1728
|
+
return join(this.root, "cache", "skills", digest.replace(/[^\w.-]/g, "_"));
|
|
1729
|
+
}
|
|
1730
|
+
async installSkills(dir, skills, fetchPackage) {
|
|
1731
|
+
const installed = [];
|
|
1732
|
+
for (const s of skills) {
|
|
1733
|
+
const target = join(dir, s.target_dir);
|
|
1734
|
+
if (!target.startsWith(join(dir, ".claude") + "/")) throw new Error(`skill path escapes workspace: ${s.target_dir}`);
|
|
1735
|
+
const cache = this.skillCacheDir(s.digest);
|
|
1736
|
+
if (!await exists(join(cache, SKILL_CACHE_DONE))) await this.fillSkillCache(cache, await fetchPackage(s.digest));
|
|
1737
|
+
await rm(target, {
|
|
1738
|
+
recursive: true,
|
|
1739
|
+
force: true
|
|
1740
|
+
});
|
|
1741
|
+
await mkdir(dirname(target), { recursive: true });
|
|
1742
|
+
await cp(cache, target, {
|
|
1743
|
+
recursive: true,
|
|
1744
|
+
filter: (src) => !src.endsWith(SKILL_CACHE_DONE)
|
|
1745
|
+
});
|
|
1746
|
+
installed.push(s.target_dir);
|
|
1747
|
+
}
|
|
1748
|
+
return installed;
|
|
1749
|
+
}
|
|
1750
|
+
async fillSkillCache(cache, pkg) {
|
|
1751
|
+
const tmp = `${cache}.tmp-${process.pid}-${Date.now()}`;
|
|
1752
|
+
await rm(tmp, {
|
|
1753
|
+
recursive: true,
|
|
1754
|
+
force: true
|
|
1755
|
+
});
|
|
1756
|
+
for (const f of pkg.files) {
|
|
1757
|
+
const target = join(tmp, f.path);
|
|
1758
|
+
if (!target.startsWith(tmp + "/")) throw new Error(`skill file escapes package: ${f.path}`);
|
|
1759
|
+
await mkdir(dirname(target), { recursive: true });
|
|
1760
|
+
await writeFile(target, Buffer.from(f.content, "base64"));
|
|
1761
|
+
if (f.executable) await chmod(target, 493);
|
|
1762
|
+
}
|
|
1763
|
+
await writeFile(join(tmp, SKILL_CACHE_DONE), pkg.digest, "utf8");
|
|
1764
|
+
await rm(cache, {
|
|
1765
|
+
recursive: true,
|
|
1766
|
+
force: true
|
|
1767
|
+
});
|
|
1768
|
+
await mkdir(dirname(cache), { recursive: true });
|
|
1769
|
+
await rename(tmp, cache);
|
|
1770
|
+
}
|
|
1771
|
+
async commitPending(repo, message) {
|
|
1772
|
+
await this.git([
|
|
1773
|
+
"add",
|
|
1774
|
+
"-A",
|
|
1775
|
+
"--",
|
|
1776
|
+
"."
|
|
1777
|
+
], repo.dir);
|
|
1778
|
+
await this.git([
|
|
1779
|
+
"reset",
|
|
1780
|
+
"-q",
|
|
1781
|
+
"--",
|
|
1782
|
+
...PLATFORM_PATHS,
|
|
1783
|
+
...repo.excludes ?? []
|
|
1784
|
+
], repo.dir);
|
|
1785
|
+
if (await this.git([
|
|
1786
|
+
"diff",
|
|
1787
|
+
"--cached",
|
|
1788
|
+
"--name-only"
|
|
1789
|
+
], repo.dir)) await this.git([
|
|
1790
|
+
"commit",
|
|
1791
|
+
"-m",
|
|
1792
|
+
message
|
|
1793
|
+
], repo.dir);
|
|
1794
|
+
return this.git(["rev-parse", "HEAD"], repo.dir);
|
|
1795
|
+
}
|
|
1796
|
+
async changedPaths(repo, head) {
|
|
1797
|
+
const out = await this.git([
|
|
1798
|
+
"diff",
|
|
1799
|
+
"--name-only",
|
|
1800
|
+
`${repo.baseSha}..${head}`
|
|
1801
|
+
], repo.dir);
|
|
1802
|
+
return out ? out.split("\n").filter(Boolean) : [];
|
|
1803
|
+
}
|
|
1804
|
+
async push(repo, signal) {
|
|
1805
|
+
const ref = `refs/heads/${repo.branch}`;
|
|
1806
|
+
const lease = `--force-with-lease=${ref}:${repo.remoteSha}`;
|
|
1807
|
+
await this.git([
|
|
1808
|
+
"push",
|
|
1809
|
+
lease,
|
|
1810
|
+
...ciPushOptions(repo.policy.ci_push_variables),
|
|
1811
|
+
"origin",
|
|
1812
|
+
`HEAD:${ref}`
|
|
1813
|
+
], repo.dir, signal);
|
|
1814
|
+
}
|
|
1815
|
+
async cleanup(attemptId, repos) {
|
|
1816
|
+
for (const r of repos) await this.git([
|
|
1817
|
+
"worktree",
|
|
1818
|
+
"remove",
|
|
1819
|
+
"--force",
|
|
1820
|
+
r.dir
|
|
1821
|
+
], r.dir).catch(() => void 0);
|
|
1822
|
+
await rm(this.attemptDir(attemptId), {
|
|
1823
|
+
recursive: true,
|
|
1824
|
+
force: true
|
|
1825
|
+
});
|
|
1826
|
+
}
|
|
1827
|
+
};
|
|
1828
|
+
const SESSION_SUBMIT_PATH = "/session/submit";
|
|
1829
|
+
const SESSION_ASK_PATH = "/session/ask";
|
|
1830
|
+
const SESSION_TASK_PATH = "/session/task";
|
|
1831
|
+
const SESSION_BROWSER_PATH = "/session/browser";
|
|
1832
|
+
const UPSTREAM_SESSION_HEADER = "X-Forge-Session-Token";
|
|
1833
|
+
const TASK_ACTIONS = new Set([
|
|
1834
|
+
"status",
|
|
1835
|
+
"pause",
|
|
1836
|
+
"resume"
|
|
1837
|
+
]);
|
|
1838
|
+
const SESSION_TOKEN_HEADER = "x-forge-session-token";
|
|
1839
|
+
const ENV_ATTEMPT_ID = "FORGE_ATTEMPT_ID";
|
|
1840
|
+
const ENV_SESSION_TOKEN = "FORGE_SESSION_TOKEN";
|
|
1841
|
+
const ENV_RUNNER_URL = "FORGE_RUNNER_URL";
|
|
1842
|
+
const ENV_OUTPUT_SCHEMA = "FORGE_OUTPUT_SCHEMA";
|
|
1843
|
+
const SKILL_KIND_PLUGIN = "plugin";
|
|
1844
|
+
const STATE_FILE = "runner-state.json";
|
|
1845
|
+
const DEFAULT_LEASE_TTL_SEC = 15;
|
|
1846
|
+
const MAX_CLAIMS_PER_WAKE = 8;
|
|
1847
|
+
const JANITOR_INTERVAL_MS = 60 * 6e4;
|
|
1848
|
+
const CHAT_SLOT_KINDS = new Set([
|
|
1849
|
+
"chat",
|
|
1850
|
+
"draft",
|
|
1851
|
+
"schedule",
|
|
1852
|
+
"norm_extract"
|
|
1853
|
+
]);
|
|
1854
|
+
const CAP_BRANCH_PUBLISH = "task_branch_publish";
|
|
1855
|
+
const CHAT_SESSION_REF_FILE = "session_ref";
|
|
1856
|
+
const LOCAL_PATH_PATTERN = /(?<![A-Za-z0-9._%~/-])(?:\/Users|\/home|\/private|\/var|\/tmp)\/[^\s)'"`]+/g;
|
|
1857
|
+
function slotOf(kind) {
|
|
1858
|
+
if (kind === "run_check") return "check";
|
|
1859
|
+
return CHAT_SLOT_KINDS.has(kind) ? "chat" : "exec";
|
|
1860
|
+
}
|
|
1861
|
+
function stripLocalPaths(text) {
|
|
1862
|
+
return text.replace(LOCAL_PATH_PATTERN, "(本机路径已隐去)");
|
|
1863
|
+
}
|
|
1864
|
+
var RealExecutor = class {
|
|
1865
|
+
host;
|
|
1866
|
+
api;
|
|
1867
|
+
ws;
|
|
1868
|
+
machine;
|
|
1869
|
+
runningMap = /* @__PURE__ */ new Map();
|
|
1870
|
+
leftovers = [];
|
|
1871
|
+
claiming = false;
|
|
1872
|
+
rewake = false;
|
|
1873
|
+
stopping = false;
|
|
1874
|
+
diskFull = false;
|
|
1875
|
+
quotaUntil;
|
|
1876
|
+
quotaTimer;
|
|
1877
|
+
awake;
|
|
1878
|
+
janitor;
|
|
1879
|
+
janitorTimer;
|
|
1880
|
+
afBinDir = "";
|
|
1881
|
+
proc;
|
|
1882
|
+
now;
|
|
1883
|
+
constructor(deps = {}) {
|
|
1884
|
+
this.deps = deps;
|
|
1885
|
+
this.proc = deps.proc ?? new NodeProcRunner();
|
|
1886
|
+
this.now = deps.now ?? (() => /* @__PURE__ */ new Date());
|
|
1887
|
+
}
|
|
1888
|
+
async start(host) {
|
|
1889
|
+
this.host = host;
|
|
1890
|
+
this.api = new AttemptApi(host);
|
|
1891
|
+
this.ws = new Workspace(this.proc, host.machineSettings().work_dir);
|
|
1892
|
+
this.awake = new RunAwake(this.proc, () => host.machineSettings().prevent_sleep, this.deps.platform);
|
|
1893
|
+
this.janitor = new Janitor(this.proc, host.machineSettings().work_dir);
|
|
1894
|
+
this.applyConfig();
|
|
1895
|
+
this.leftovers = await this.loadState();
|
|
1896
|
+
this.afBinDir = await writeAfShim(host.machineSettings().work_dir, this.deps.selfEntry ?? currentEntry());
|
|
1897
|
+
const every = this.deps.janitorIntervalMs ?? JANITOR_INTERVAL_MS;
|
|
1898
|
+
if (every > 0) {
|
|
1899
|
+
this.sweep();
|
|
1900
|
+
this.janitorTimer = setInterval(() => void this.sweep(), every);
|
|
1901
|
+
this.janitorTimer.unref?.();
|
|
1902
|
+
}
|
|
1903
|
+
host.localRoute("POST", SESSION_SUBMIT_PATH, (req) => this.onSubmit(req));
|
|
1904
|
+
host.localRoute("POST", SESSION_ASK_PATH, (req) => this.onAsk(req));
|
|
1905
|
+
host.localRoute("POST", SESSION_TASK_PATH, (req) => this.onTask(req));
|
|
1906
|
+
host.localRoute("POST", SESSION_BROWSER_PATH, (req) => this.onBrowser(req));
|
|
1907
|
+
}
|
|
1908
|
+
slots() {
|
|
1909
|
+
const busy = (cls) => [...this.runningMap.values()].filter((r) => r.slot === cls).length;
|
|
1910
|
+
const limits = this.limits();
|
|
1911
|
+
return {
|
|
1912
|
+
total: limits.exec,
|
|
1913
|
+
busy: busy("exec"),
|
|
1914
|
+
check_free: Math.max(0, limits.check - busy("check")),
|
|
1915
|
+
chat_free: Math.max(0, limits.chat - busy("chat"))
|
|
1916
|
+
};
|
|
1917
|
+
}
|
|
1918
|
+
limits() {
|
|
1919
|
+
if (!this.machine) return {
|
|
1920
|
+
exec: 0,
|
|
1921
|
+
check: 0,
|
|
1922
|
+
chat: 0
|
|
1923
|
+
};
|
|
1924
|
+
return computeSlots(this.host.machineSettings(), this.machine, this.now());
|
|
1925
|
+
}
|
|
1926
|
+
running() {
|
|
1927
|
+
const live = [...this.runningMap.values()].map((r) => ({
|
|
1928
|
+
attempt_id: r.attemptId,
|
|
1929
|
+
agent_id: r.agentId,
|
|
1930
|
+
started_at: r.startedAt
|
|
1931
|
+
}));
|
|
1932
|
+
return [...this.leftovers, ...live];
|
|
1933
|
+
}
|
|
1934
|
+
wake() {
|
|
1935
|
+
this.leftovers = [];
|
|
1936
|
+
if (this.stopping) return;
|
|
1937
|
+
if (this.claiming) {
|
|
1938
|
+
this.rewake = true;
|
|
1939
|
+
return;
|
|
1940
|
+
}
|
|
1941
|
+
this.claimLoop();
|
|
1942
|
+
}
|
|
1943
|
+
async cancel(attemptId) {
|
|
1944
|
+
const r = this.runningMap.get(attemptId);
|
|
1945
|
+
if (!r) return;
|
|
1946
|
+
r.stopReason = "cancelled";
|
|
1947
|
+
r.abort.abort();
|
|
1948
|
+
await r.done;
|
|
1949
|
+
}
|
|
1950
|
+
applyConfig() {
|
|
1951
|
+
this.machine = this.deps.machine ?? {
|
|
1952
|
+
cpus: os.cpus().length,
|
|
1953
|
+
memGb: roundMemGb(os.totalmem())
|
|
1954
|
+
};
|
|
1955
|
+
}
|
|
1956
|
+
async sweep() {
|
|
1957
|
+
try {
|
|
1958
|
+
const s = this.host.machineSettings();
|
|
1959
|
+
const res = await this.janitor.sweep(s, new Set(this.runningMap.keys()), this.now());
|
|
1960
|
+
if (res.overLimit && !this.diskFull) this.host.log("warn", "work dir over disk limit, pausing claims", {
|
|
1961
|
+
used_gb: res.usedGb,
|
|
1962
|
+
limit_gb: s.disk_limit_gb
|
|
1963
|
+
});
|
|
1964
|
+
const resumed = this.diskFull && !res.overLimit;
|
|
1965
|
+
this.diskFull = res.overLimit;
|
|
1966
|
+
if (resumed) this.wake();
|
|
1967
|
+
} catch (err) {
|
|
1968
|
+
this.host.log("warn", "disk sweep failed", { error: String(err) });
|
|
1969
|
+
}
|
|
1970
|
+
}
|
|
1971
|
+
stopClaiming() {
|
|
1972
|
+
this.stopping = true;
|
|
1973
|
+
}
|
|
1974
|
+
async drain(timeoutMs) {
|
|
1975
|
+
this.stopping = true;
|
|
1976
|
+
if (this.janitorTimer) clearInterval(this.janitorTimer);
|
|
1977
|
+
if (this.quotaTimer) clearTimeout(this.quotaTimer);
|
|
1978
|
+
for (const r of this.runningMap.values()) {
|
|
1979
|
+
r.stopReason ??= "runner_shutdown";
|
|
1980
|
+
r.abort.abort();
|
|
1981
|
+
}
|
|
1982
|
+
const all = Promise.all([...this.runningMap.values()].map((r) => r.done));
|
|
1983
|
+
await Promise.race([all, new Promise((resolve) => setTimeout(resolve, timeoutMs))]);
|
|
1984
|
+
}
|
|
1985
|
+
runtimeFailed(run, asked) {
|
|
1986
|
+
if (!run.isError && (run.proc.code === 0 || asked)) return null;
|
|
1987
|
+
const reason = runtimeFailure(run.resultText, run.proc.stderr);
|
|
1988
|
+
if (!reason) return null;
|
|
1989
|
+
return {
|
|
1990
|
+
reason,
|
|
1991
|
+
code: run.proc.code ?? void 0,
|
|
1992
|
+
message: (run.resultText.trim() || run.proc.stderr.trim()).slice(0, 500)
|
|
1993
|
+
};
|
|
1994
|
+
}
|
|
1995
|
+
quotaExhausted(resultText) {
|
|
1996
|
+
const resetAt = quotaResetAt(resultText, this.now());
|
|
1997
|
+
if (!resetAt) return false;
|
|
1998
|
+
if (this.quotaUntil && this.quotaUntil >= resetAt) return true;
|
|
1999
|
+
this.quotaUntil = resetAt;
|
|
2000
|
+
this.host.log("warn", "ai quota exhausted, pausing claims", { until: resetAt.toISOString() });
|
|
2001
|
+
if (this.quotaTimer) clearTimeout(this.quotaTimer);
|
|
2002
|
+
this.quotaTimer = setTimeout(() => {
|
|
2003
|
+
this.quotaUntil = void 0;
|
|
2004
|
+
this.quotaTimer = void 0;
|
|
2005
|
+
this.host.log("info", "ai quota window passed, resuming claims");
|
|
2006
|
+
this.wake();
|
|
2007
|
+
}, Math.max(0, resetAt.getTime() - this.now().getTime()));
|
|
2008
|
+
this.quotaTimer.unref?.();
|
|
2009
|
+
return true;
|
|
2010
|
+
}
|
|
2011
|
+
async claimLoop() {
|
|
2012
|
+
this.claiming = true;
|
|
2013
|
+
try {
|
|
2014
|
+
for (let i = 0; i < MAX_CLAIMS_PER_WAKE && !this.stopping && !this.diskFull && !this.quotaUntil; i++) {
|
|
2015
|
+
const s = this.slots();
|
|
2016
|
+
const execFree = s.total - s.busy;
|
|
2017
|
+
if (execFree <= 0 && s.check_free <= 0 && s.chat_free <= 0) break;
|
|
2018
|
+
let job;
|
|
2019
|
+
try {
|
|
2020
|
+
job = await this.api.claim({
|
|
2021
|
+
slots_free: Math.max(0, execFree),
|
|
2022
|
+
check_slot_free: s.check_free > 0,
|
|
2023
|
+
chat_slot_free: s.chat_free > 0
|
|
2024
|
+
});
|
|
2025
|
+
} catch (err) {
|
|
2026
|
+
this.host.log("warn", "claim failed", { error: String(err) });
|
|
2027
|
+
break;
|
|
2028
|
+
}
|
|
2029
|
+
if (!job) break;
|
|
2030
|
+
this.launch(job);
|
|
2031
|
+
}
|
|
2032
|
+
} finally {
|
|
2033
|
+
this.claiming = false;
|
|
2034
|
+
if (this.rewake) {
|
|
2035
|
+
this.rewake = false;
|
|
2036
|
+
this.wake();
|
|
2037
|
+
}
|
|
2038
|
+
}
|
|
2039
|
+
}
|
|
2040
|
+
launch(job) {
|
|
2041
|
+
const r = {
|
|
2042
|
+
attemptId: job.attempt_id,
|
|
2043
|
+
agentId: job.agent_id,
|
|
2044
|
+
startedAt: this.now().toISOString(),
|
|
2045
|
+
slot: slotOf(job.job.kind),
|
|
2046
|
+
abort: new AbortController(),
|
|
2047
|
+
lease: job.lease_token,
|
|
2048
|
+
sessionToken: job.session_token,
|
|
2049
|
+
asked: false,
|
|
2050
|
+
skills: new SkillCallTracker(this.now),
|
|
2051
|
+
done: Promise.resolve()
|
|
2052
|
+
};
|
|
2053
|
+
this.runningMap.set(r.attemptId, r);
|
|
2054
|
+
this.saveState();
|
|
2055
|
+
r.done = this.runAttempt(r, job).catch((err) => this.host.log("error", "attempt crashed", {
|
|
2056
|
+
attempt_id: r.attemptId,
|
|
2057
|
+
error: String(err)
|
|
2058
|
+
})).finally(() => {
|
|
2059
|
+
this.runningMap.delete(r.attemptId);
|
|
2060
|
+
this.saveState();
|
|
2061
|
+
this.wake();
|
|
2062
|
+
});
|
|
2063
|
+
}
|
|
2064
|
+
async runAttempt(r, job) {
|
|
2065
|
+
const releaseAwake = this.awake.hold();
|
|
2066
|
+
const stopKeeper = await this.startLeaseKeeper(r, job.lease_ttl_sec);
|
|
2067
|
+
let reason = "crashed";
|
|
2068
|
+
let message = "";
|
|
2069
|
+
let exitCode;
|
|
2070
|
+
try {
|
|
2071
|
+
if (r.stopReason === "fenced") return;
|
|
2072
|
+
const manifest = await this.api.manifest(r.attemptId, r.lease);
|
|
2073
|
+
const res = r.slot === "check" ? await this.runCheckJob(r, manifest) : r.slot === "chat" ? await this.runChatSlotJob(r, manifest, job) : await this.runAgentJob(r, manifest);
|
|
2074
|
+
reason = res.reason;
|
|
2075
|
+
exitCode = res.code;
|
|
2076
|
+
message = res.message;
|
|
2077
|
+
} catch (err) {
|
|
2078
|
+
message = String(err).slice(0, 500);
|
|
2079
|
+
if (err instanceof WorkspacePrepareError) reason = "workspace_failed";
|
|
2080
|
+
this.host.log("warn", "attempt failed", {
|
|
2081
|
+
attempt_id: r.attemptId,
|
|
2082
|
+
error: message
|
|
2083
|
+
});
|
|
2084
|
+
} finally {
|
|
2085
|
+
stopKeeper();
|
|
2086
|
+
releaseAwake();
|
|
2087
|
+
}
|
|
2088
|
+
if (r.stopReason === "fenced") return;
|
|
2089
|
+
if (r.stopReason) reason = r.stopReason;
|
|
2090
|
+
try {
|
|
2091
|
+
await this.api.exit(r.attemptId, r.lease, reason, exitCode, message, r.skills.active ? r.skills.snapshot() : void 0);
|
|
2092
|
+
} catch (err) {
|
|
2093
|
+
this.host.log("warn", "exit report failed", {
|
|
2094
|
+
attempt_id: r.attemptId,
|
|
2095
|
+
error: String(err)
|
|
2096
|
+
});
|
|
2097
|
+
}
|
|
2098
|
+
}
|
|
2099
|
+
async startLeaseKeeper(r, ttlSec) {
|
|
2100
|
+
const beat = async () => {
|
|
2101
|
+
try {
|
|
2102
|
+
const pending = r.skills.pending();
|
|
2103
|
+
const res = await this.api.heartbeat(r.attemptId, r.lease, pending?.calls);
|
|
2104
|
+
r.lease = res.lease_token;
|
|
2105
|
+
if (pending) r.skills.markSent(pending.version);
|
|
2106
|
+
if (res.cancel_requested && !r.stopReason) {
|
|
2107
|
+
r.stopReason = "cancelled";
|
|
2108
|
+
r.abort.abort();
|
|
2109
|
+
}
|
|
2110
|
+
} catch (err) {
|
|
2111
|
+
if (err instanceof ApiError && err.code === ERR_LEASE_FENCED) {
|
|
2112
|
+
r.stopReason = "fenced";
|
|
2113
|
+
r.abort.abort();
|
|
2114
|
+
return;
|
|
2115
|
+
}
|
|
2116
|
+
this.host.log("warn", "lease heartbeat failed", {
|
|
2117
|
+
attempt_id: r.attemptId,
|
|
2118
|
+
error: String(err)
|
|
2119
|
+
});
|
|
2120
|
+
}
|
|
2121
|
+
};
|
|
2122
|
+
await beat();
|
|
2123
|
+
const interval = this.deps.leaseIntervalMs ?? Math.max(1, ttlSec || DEFAULT_LEASE_TTL_SEC) * 1e3 / 3;
|
|
2124
|
+
const timer = setInterval(() => void beat(), interval);
|
|
2125
|
+
return () => clearInterval(timer);
|
|
2126
|
+
}
|
|
2127
|
+
async runAgentJob(r, m) {
|
|
2128
|
+
const stand = this.deps.standIn?.(m);
|
|
2129
|
+
if (stand) {
|
|
2130
|
+
const key = createHash("sha256").update(r.attemptId + ":stand-in").digest("hex");
|
|
2131
|
+
await this.api.output(r.attemptId, r.lease, stand.schema, stand.payload, key);
|
|
2132
|
+
this.host.log("info", "stand-in output submitted", {
|
|
2133
|
+
attempt_id: r.attemptId,
|
|
2134
|
+
node: m.node.id
|
|
2135
|
+
});
|
|
2136
|
+
return {
|
|
2137
|
+
reason: "completed",
|
|
2138
|
+
message: "stand-in"
|
|
2139
|
+
};
|
|
2140
|
+
}
|
|
2141
|
+
const { dir, repos } = await this.ws.prepare(r.attemptId, m.repo_policy, r.abort.signal);
|
|
2142
|
+
try {
|
|
2143
|
+
const cwd = repos[0]?.dir ?? dir;
|
|
2144
|
+
const images = await this.downloadInputs(r, m, cwd, false);
|
|
2145
|
+
await this.ws.writeSkills(cwd, m.platform_skills ?? []);
|
|
2146
|
+
await writeExecutionContext(cwd, m);
|
|
2147
|
+
const pluginDirs = await this.installFrozenSkills(cwd, m, repos);
|
|
2148
|
+
if (m.capabilities?.includes(CAP_BRANCH_PUBLISH)) r.publishTo = {
|
|
2149
|
+
m,
|
|
2150
|
+
repos
|
|
2151
|
+
};
|
|
2152
|
+
const browserEnv = await browserStateEnv(this.deps.browserState, m.capabilities);
|
|
2153
|
+
const env = {
|
|
2154
|
+
...await this.sessionEnv(r, m, cwd),
|
|
2155
|
+
...browserEnv
|
|
2156
|
+
};
|
|
2157
|
+
const agent = this.host.agentConfig(r.agentId);
|
|
2158
|
+
r.skills.begin();
|
|
2159
|
+
const run = await runClaude(this.proc, {
|
|
2160
|
+
cwd,
|
|
2161
|
+
prompt: images.rewrite(m.prompt),
|
|
2162
|
+
systemPrompt: [
|
|
2163
|
+
images.rewrite(m.system_prompt),
|
|
2164
|
+
repoDirsNote(repos),
|
|
2165
|
+
EXECUTION_POLICY_NOTE,
|
|
2166
|
+
images.count ? IMAGES_NOTE : "",
|
|
2167
|
+
browserEnv[ENV_BROWSER_STATE] ? BROWSER_STATE_NOTE : "",
|
|
2168
|
+
agent?.instructions ?? ""
|
|
2169
|
+
].filter(Boolean).join("\n\n"),
|
|
2170
|
+
model: agent?.model || m.runtime.model,
|
|
2171
|
+
allowedTools: m.allowed_tools,
|
|
2172
|
+
resumeSessionRef: m.runtime.resume_session_ref,
|
|
2173
|
+
pluginDirs,
|
|
2174
|
+
addDirs: repos.slice(1).map((p) => p.dir),
|
|
2175
|
+
env,
|
|
2176
|
+
idleMs: m.watchdog_idle_sec > 0 ? m.watchdog_idle_sec * 1e3 : void 0,
|
|
2177
|
+
signal: r.abort.signal,
|
|
2178
|
+
onEvent: (ev) => r.skills.observe(ev)
|
|
2179
|
+
}, this.deps.claudeBin);
|
|
2180
|
+
if (run.proc.ended === "cancelled") return {
|
|
2181
|
+
reason: "cancelled",
|
|
2182
|
+
message: "cancelled"
|
|
2183
|
+
};
|
|
2184
|
+
const head = m.capabilities?.includes(CAP_BRANCH_PUBLISH) ? await this.publish(r, m, repos) : "";
|
|
2185
|
+
if (run.sessionRef || head) await this.api.checkpoint(r.attemptId, r.lease, run.sessionRef, head).catch(() => void 0);
|
|
2186
|
+
if (run.proc.ended === "idle") return {
|
|
2187
|
+
reason: "idle_timeout",
|
|
2188
|
+
message: "no output for too long"
|
|
2189
|
+
};
|
|
2190
|
+
if (this.quotaExhausted(run.resultText)) return {
|
|
2191
|
+
reason: "quota_exhausted",
|
|
2192
|
+
code: run.proc.code ?? void 0,
|
|
2193
|
+
message: run.resultText.slice(0, 500)
|
|
2194
|
+
};
|
|
2195
|
+
const failure = this.runtimeFailed(run, r.asked);
|
|
2196
|
+
if (failure) return failure;
|
|
2197
|
+
if (run.isError) return {
|
|
2198
|
+
reason: "crashed",
|
|
2199
|
+
code: run.proc.code ?? void 0,
|
|
2200
|
+
message: run.resultText.slice(0, 500)
|
|
2201
|
+
};
|
|
2202
|
+
return {
|
|
2203
|
+
reason: run.proc.code === 0 || r.asked ? "completed" : "crashed",
|
|
2204
|
+
code: run.proc.code ?? void 0,
|
|
2205
|
+
message: ""
|
|
2206
|
+
};
|
|
2207
|
+
} finally {
|
|
2208
|
+
await this.ws.cleanup(r.attemptId, repos).catch(() => void 0);
|
|
2209
|
+
}
|
|
2210
|
+
}
|
|
2211
|
+
async sessionEnv(r, m, cwd) {
|
|
2212
|
+
const env = {
|
|
2213
|
+
[ENV_ATTEMPT_ID]: r.attemptId,
|
|
2214
|
+
[ENV_SESSION_TOKEN]: r.sessionToken ?? "",
|
|
2215
|
+
PATH: prependPath(this.afBinDir, process.env.PATH ?? "")
|
|
2216
|
+
};
|
|
2217
|
+
const base = this.host.localBaseUrl?.();
|
|
2218
|
+
if (base) env[ENV_RUNNER_URL] = base;
|
|
2219
|
+
if (m.output_schema) {
|
|
2220
|
+
const schemaPath = join(cwd, ".forge", "output_schema.json");
|
|
2221
|
+
await mkdir(dirname(schemaPath), { recursive: true });
|
|
2222
|
+
await writeFile(schemaPath, JSON.stringify(m.output_schema, null, 2), "utf8");
|
|
2223
|
+
env[ENV_OUTPUT_SCHEMA] = schemaPath;
|
|
2224
|
+
}
|
|
2225
|
+
return env;
|
|
2226
|
+
}
|
|
2227
|
+
async runChatSlotJob(r, m, job) {
|
|
2228
|
+
const chatId = job.job.payload?.chat_session_id;
|
|
2229
|
+
const isChat = job.job.kind === "chat" && chatId !== void 0;
|
|
2230
|
+
const cwd = isChat ? join(this.host.machineSettings().work_dir, "chat", String(chatId)) : this.ws.attemptDir(r.attemptId);
|
|
2231
|
+
await mkdir(cwd, { recursive: true });
|
|
2232
|
+
const refFile = join(cwd, ".forge", CHAT_SESSION_REF_FILE);
|
|
2233
|
+
const resumeRef = isChat ? await readFile(refFile, "utf8").catch(() => "") : "";
|
|
2234
|
+
try {
|
|
2235
|
+
const images = await this.downloadInputs(r, m, cwd, true);
|
|
2236
|
+
await this.ws.writeSkills(cwd, m.platform_skills ?? []);
|
|
2237
|
+
const env = await this.sessionEnv(r, m, cwd);
|
|
2238
|
+
const agent = this.host.agentConfig(r.agentId);
|
|
2239
|
+
r.skills.begin();
|
|
2240
|
+
const run = await runClaude(this.proc, {
|
|
2241
|
+
cwd,
|
|
2242
|
+
prompt: images.rewrite(m.prompt),
|
|
2243
|
+
systemPrompt: [
|
|
2244
|
+
images.rewrite(m.system_prompt),
|
|
2245
|
+
images.count ? IMAGES_NOTE : "",
|
|
2246
|
+
agent?.instructions ?? ""
|
|
2247
|
+
].filter(Boolean).join("\n\n"),
|
|
2248
|
+
model: agent?.model || m.runtime.model,
|
|
2249
|
+
allowedTools: m.allowed_tools,
|
|
2250
|
+
resumeSessionRef: resumeRef.trim() || void 0,
|
|
2251
|
+
env,
|
|
2252
|
+
idleMs: m.watchdog_idle_sec > 0 ? m.watchdog_idle_sec * 1e3 : void 0,
|
|
2253
|
+
signal: r.abort.signal,
|
|
2254
|
+
onEvent: (ev) => r.skills.observe(ev)
|
|
2255
|
+
}, this.deps.claudeBin);
|
|
2256
|
+
if (run.proc.ended === "cancelled") return {
|
|
2257
|
+
reason: "cancelled",
|
|
2258
|
+
message: "cancelled"
|
|
2259
|
+
};
|
|
2260
|
+
if (isChat && run.sessionRef) {
|
|
2261
|
+
await mkdir(dirname(refFile), { recursive: true });
|
|
2262
|
+
await writeFile(refFile, run.sessionRef, "utf8");
|
|
2263
|
+
}
|
|
2264
|
+
if (run.proc.ended === "idle") return {
|
|
2265
|
+
reason: "idle_timeout",
|
|
2266
|
+
message: "no output for too long"
|
|
2267
|
+
};
|
|
2268
|
+
if (this.quotaExhausted(run.resultText)) return {
|
|
2269
|
+
reason: "quota_exhausted",
|
|
2270
|
+
code: run.proc.code ?? void 0,
|
|
2271
|
+
message: run.resultText.slice(0, 500)
|
|
2272
|
+
};
|
|
2273
|
+
const failure = this.runtimeFailed(run, false);
|
|
2274
|
+
if (failure) return failure;
|
|
2275
|
+
if (run.isError) return {
|
|
2276
|
+
reason: "crashed",
|
|
2277
|
+
code: run.proc.code ?? void 0,
|
|
2278
|
+
message: run.resultText.slice(0, 500)
|
|
2279
|
+
};
|
|
2280
|
+
if (isChat && run.resultText.trim()) await this.api.chatReply(r.attemptId, r.lease, stripLocalPaths(run.resultText.trim()));
|
|
2281
|
+
return {
|
|
2282
|
+
reason: run.proc.code === 0 ? "completed" : "crashed",
|
|
2283
|
+
code: run.proc.code ?? void 0,
|
|
2284
|
+
message: ""
|
|
2285
|
+
};
|
|
2286
|
+
} finally {
|
|
2287
|
+
if (!isChat) await this.ws.cleanup(r.attemptId, []).catch(() => void 0);
|
|
2288
|
+
}
|
|
2289
|
+
}
|
|
2290
|
+
async downloadInputs(r, m, cwd, withAttachments) {
|
|
2291
|
+
const texts = [];
|
|
2292
|
+
const attachments = [];
|
|
2293
|
+
for (const input of m.inputs) if (input.kind === INPUT_KIND_FILE) texts.push({
|
|
2294
|
+
name: input.name,
|
|
2295
|
+
content: await this.api.input(r.attemptId, r.lease, input.name)
|
|
2296
|
+
});
|
|
2297
|
+
else if (withAttachments && input.kind === INPUT_KIND_ATTACHMENT) attachments.push({
|
|
2298
|
+
name: input.name,
|
|
2299
|
+
dir: input.dir,
|
|
2300
|
+
content: await this.api.attachment(r.attemptId, r.lease, input.name)
|
|
2301
|
+
});
|
|
2302
|
+
const images = await localizeImages(cwd, [
|
|
2303
|
+
m.prompt,
|
|
2304
|
+
m.system_prompt,
|
|
2305
|
+
...texts.map((f) => f.content)
|
|
2306
|
+
], (ref) => this.api.image(r.attemptId, r.lease, ref), (ref, err) => this.host.log("warn", "image download failed", {
|
|
2307
|
+
ref,
|
|
2308
|
+
error: String(err)
|
|
2309
|
+
}));
|
|
2310
|
+
await this.ws.writeInputs(cwd, [...texts.map((f) => ({
|
|
2311
|
+
...f,
|
|
2312
|
+
content: images.rewrite(f.content)
|
|
2313
|
+
})), ...attachments]);
|
|
2314
|
+
return images;
|
|
2315
|
+
}
|
|
2316
|
+
async installFrozenSkills(cwd, m, repos) {
|
|
2317
|
+
const repo = repos.find((r) => r.dir === cwd);
|
|
2318
|
+
const pluginDirs = [];
|
|
2319
|
+
for (const s of m.skills ?? []) try {
|
|
2320
|
+
const done = await this.ws.installSkills(cwd, [s], (digest) => this.api.skillPackage(digest));
|
|
2321
|
+
if (repo) repo.excludes = [...repo.excludes ?? [], ...done];
|
|
2322
|
+
if (s.kind === SKILL_KIND_PLUGIN) pluginDirs.push(join(cwd, s.target_dir));
|
|
2323
|
+
} catch (err) {
|
|
2324
|
+
this.host.log("warn", "skill install failed", {
|
|
2325
|
+
ref: s.ref,
|
|
2326
|
+
digest: s.digest,
|
|
2327
|
+
error: String(err)
|
|
2328
|
+
});
|
|
2329
|
+
}
|
|
2330
|
+
return pluginDirs;
|
|
2331
|
+
}
|
|
2332
|
+
async publish(r, m, repos) {
|
|
2333
|
+
let first = "";
|
|
2334
|
+
for (const repo of repos) {
|
|
2335
|
+
const head = await this.ws.commitPending(repo, `forge: ${m.task.task_no} ${m.node.name}`);
|
|
2336
|
+
first ||= head;
|
|
2337
|
+
if (head === repo.startSha || head === repo.remoteSha) continue;
|
|
2338
|
+
await this.ws.push(repo, r.abort.signal);
|
|
2339
|
+
repo.remoteSha = head;
|
|
2340
|
+
const changed = await this.ws.changedPaths(repo, head);
|
|
2341
|
+
const report = await this.api.pushReport(r.attemptId, r.lease, {
|
|
2342
|
+
repo_id: repo.repoId,
|
|
2343
|
+
branch: repo.branch,
|
|
2344
|
+
head_sha: head,
|
|
2345
|
+
changed_paths: changed,
|
|
2346
|
+
idempotency_key: `${r.attemptId}:${repo.repoId}:${head}`
|
|
2347
|
+
});
|
|
2348
|
+
if (!report.verified) this.host.log("warn", "push not verified", {
|
|
2349
|
+
attempt_id: r.attemptId,
|
|
2350
|
+
repo_id: repo.repoId,
|
|
2351
|
+
violations: report.violations
|
|
2352
|
+
});
|
|
2353
|
+
}
|
|
2354
|
+
return first;
|
|
2355
|
+
}
|
|
2356
|
+
async runCheckJob(r, m) {
|
|
2357
|
+
const { dir, repos } = await this.ws.prepare(r.attemptId, m.repo_policy, r.abort.signal);
|
|
2358
|
+
try {
|
|
2359
|
+
const dirs = new Map(repos.map((p) => [p.repoId, p.dir]));
|
|
2360
|
+
const results = await runChecks(this.proc, m.checks ?? [], dirs, repos[0]?.dir ?? dir, r.abort.signal, (contentType, data) => this.api.uploadAttachment(r.attemptId, r.lease, contentType, data), {
|
|
2361
|
+
services: {
|
|
2362
|
+
launcher: nodeLauncher,
|
|
2363
|
+
cacheDir: this.ws.checkCacheDir()
|
|
2364
|
+
},
|
|
2365
|
+
ciReport: (repoId, checkKey) => this.api.ciReport(r.attemptId, r.lease, repoId, checkKey)
|
|
2366
|
+
});
|
|
2367
|
+
if (r.abort.signal.aborted) return {
|
|
2368
|
+
reason: "cancelled",
|
|
2369
|
+
message: "cancelled"
|
|
2370
|
+
};
|
|
2371
|
+
await this.api.checkResults(r.attemptId, r.lease, results);
|
|
2372
|
+
return {
|
|
2373
|
+
reason: "completed",
|
|
2374
|
+
message: ""
|
|
2375
|
+
};
|
|
2376
|
+
} finally {
|
|
2377
|
+
await this.ws.cleanup(r.attemptId, repos).catch(() => void 0);
|
|
2378
|
+
}
|
|
2379
|
+
}
|
|
2380
|
+
bySession(req) {
|
|
2381
|
+
const tok = req.headers[SESSION_TOKEN_HEADER];
|
|
2382
|
+
if (!tok) return;
|
|
2383
|
+
return [...this.runningMap.values()].find((r) => r.sessionToken === tok);
|
|
2384
|
+
}
|
|
2385
|
+
async onTask(req) {
|
|
2386
|
+
const r = this.bySession(req);
|
|
2387
|
+
if (!r?.sessionToken) return {
|
|
2388
|
+
status: 401,
|
|
2389
|
+
body: {
|
|
2390
|
+
code: "session_token_invalid",
|
|
2391
|
+
message: "no running attempt for this session"
|
|
2392
|
+
}
|
|
2393
|
+
};
|
|
2394
|
+
const body = req.body;
|
|
2395
|
+
if (!body?.task_no || !body.action || !TASK_ACTIONS.has(body.action)) return {
|
|
2396
|
+
status: 400,
|
|
2397
|
+
body: {
|
|
2398
|
+
code: "validation_failed",
|
|
2399
|
+
message: "action (status|pause|resume) and task_no are required"
|
|
2400
|
+
}
|
|
2401
|
+
};
|
|
2402
|
+
const path = `/session/tasks/${encodeURIComponent(body.task_no)}`;
|
|
2403
|
+
const res = body.action === "status" ? await this.host.http().request("GET", path, { headers: { [UPSTREAM_SESSION_HEADER]: r.sessionToken } }) : await this.host.http().request("POST", `${path}:${body.action}`, {
|
|
2404
|
+
body: {},
|
|
2405
|
+
headers: { [UPSTREAM_SESSION_HEADER]: r.sessionToken }
|
|
2406
|
+
});
|
|
2407
|
+
return {
|
|
2408
|
+
status: res.status,
|
|
2409
|
+
body: res.body
|
|
2410
|
+
};
|
|
2411
|
+
}
|
|
2412
|
+
async onBrowser(req) {
|
|
2413
|
+
const r = this.bySession(req);
|
|
2414
|
+
if (!r) return {
|
|
2415
|
+
status: 401,
|
|
2416
|
+
body: {
|
|
2417
|
+
code: "session_token_invalid",
|
|
2418
|
+
message: "no running attempt for this session"
|
|
2419
|
+
}
|
|
2420
|
+
};
|
|
2421
|
+
if (!req.body || typeof req.body !== "object") return {
|
|
2422
|
+
status: 400,
|
|
2423
|
+
body: {
|
|
2424
|
+
code: "validation_failed",
|
|
2425
|
+
message: "browser command is required"
|
|
2426
|
+
}
|
|
2427
|
+
};
|
|
2428
|
+
try {
|
|
2429
|
+
const result = await this.api.browser(r.attemptId, r.lease, req.body);
|
|
2430
|
+
return {
|
|
2431
|
+
status: 200,
|
|
2432
|
+
body: {
|
|
2433
|
+
url: result.url,
|
|
2434
|
+
title: result.title,
|
|
2435
|
+
text: result.text
|
|
2436
|
+
}
|
|
2437
|
+
};
|
|
2438
|
+
} catch (err) {
|
|
2439
|
+
return apiFailure(err);
|
|
2440
|
+
}
|
|
2441
|
+
}
|
|
2442
|
+
async onSubmit(req) {
|
|
2443
|
+
const r = this.bySession(req);
|
|
2444
|
+
if (!r) return {
|
|
2445
|
+
status: 401,
|
|
2446
|
+
body: {
|
|
2447
|
+
code: "session_token_invalid",
|
|
2448
|
+
message: "no running attempt for this session"
|
|
2449
|
+
}
|
|
2450
|
+
};
|
|
2451
|
+
const body = req.body;
|
|
2452
|
+
if (!body?.schema || body.payload === void 0) return {
|
|
2453
|
+
status: 400,
|
|
2454
|
+
body: {
|
|
2455
|
+
code: "validation_failed",
|
|
2456
|
+
message: "schema and payload are required"
|
|
2457
|
+
}
|
|
2458
|
+
};
|
|
2459
|
+
const key = createHash("sha256").update(r.attemptId + ":" + JSON.stringify(body.payload)).digest("hex");
|
|
2460
|
+
if (r.publishTo) try {
|
|
2461
|
+
const head = await this.publish(r, r.publishTo.m, r.publishTo.repos);
|
|
2462
|
+
await this.api.checkpoint(r.attemptId, r.lease, "", head);
|
|
2463
|
+
} catch (err) {
|
|
2464
|
+
return {
|
|
2465
|
+
status: 409,
|
|
2466
|
+
body: {
|
|
2467
|
+
code: "push_failed",
|
|
2468
|
+
message: `产出没交:提交或推送任务分支失败,先处理再交。${String(err).slice(0, 500)}`
|
|
2469
|
+
}
|
|
2470
|
+
};
|
|
2471
|
+
}
|
|
2472
|
+
try {
|
|
2473
|
+
await this.api.output(r.attemptId, r.lease, body.schema, body.payload, key);
|
|
2474
|
+
return {
|
|
2475
|
+
status: 200,
|
|
2476
|
+
body: { code: "ok" }
|
|
2477
|
+
};
|
|
2478
|
+
} catch (err) {
|
|
2479
|
+
return apiFailure(err);
|
|
2480
|
+
}
|
|
2481
|
+
}
|
|
2482
|
+
async onAsk(req) {
|
|
2483
|
+
const r = this.bySession(req);
|
|
2484
|
+
if (!r) return {
|
|
2485
|
+
status: 401,
|
|
2486
|
+
body: {
|
|
2487
|
+
code: "session_token_invalid",
|
|
2488
|
+
message: "no running attempt for this session"
|
|
2489
|
+
}
|
|
2490
|
+
};
|
|
2491
|
+
const body = req.body;
|
|
2492
|
+
if (!body?.items?.length) return {
|
|
2493
|
+
status: 400,
|
|
2494
|
+
body: {
|
|
2495
|
+
code: "validation_failed",
|
|
2496
|
+
message: "items are required"
|
|
2497
|
+
}
|
|
2498
|
+
};
|
|
2499
|
+
try {
|
|
2500
|
+
const id = await this.api.questions(r.attemptId, r.lease, body.items);
|
|
2501
|
+
r.asked = true;
|
|
2502
|
+
return {
|
|
2503
|
+
status: 200,
|
|
2504
|
+
body: {
|
|
2505
|
+
code: "ok",
|
|
2506
|
+
data: { question_id: id }
|
|
2507
|
+
}
|
|
2508
|
+
};
|
|
2509
|
+
} catch (err) {
|
|
2510
|
+
return apiFailure(err);
|
|
2511
|
+
}
|
|
2512
|
+
}
|
|
2513
|
+
statePath() {
|
|
2514
|
+
return join(this.host.machineSettings().work_dir, STATE_FILE);
|
|
2515
|
+
}
|
|
2516
|
+
async loadState() {
|
|
2517
|
+
try {
|
|
2518
|
+
const list = JSON.parse(await readFile(this.statePath(), "utf8"));
|
|
2519
|
+
return Array.isArray(list) ? list : [];
|
|
2520
|
+
} catch {
|
|
2521
|
+
return [];
|
|
2522
|
+
}
|
|
2523
|
+
}
|
|
2524
|
+
async saveState() {
|
|
2525
|
+
const list = [...this.runningMap.values()].map((r) => ({
|
|
2526
|
+
attempt_id: r.attemptId,
|
|
2527
|
+
agent_id: r.agentId,
|
|
2528
|
+
started_at: r.startedAt
|
|
2529
|
+
}));
|
|
2530
|
+
try {
|
|
2531
|
+
await mkdir(dirname(this.statePath()), { recursive: true });
|
|
2532
|
+
await writeFile(this.statePath(), JSON.stringify(list), "utf8");
|
|
2533
|
+
} catch (err) {
|
|
2534
|
+
this.host.log("warn", "save runner state failed", { error: String(err) });
|
|
2535
|
+
}
|
|
2536
|
+
}
|
|
2537
|
+
};
|
|
2538
|
+
function apiFailure(err) {
|
|
2539
|
+
if (err instanceof ApiError) return {
|
|
2540
|
+
status: err.status,
|
|
2541
|
+
body: {
|
|
2542
|
+
code: err.code,
|
|
2543
|
+
message: err.message
|
|
2544
|
+
}
|
|
2545
|
+
};
|
|
2546
|
+
return {
|
|
2547
|
+
status: 502,
|
|
2548
|
+
body: {
|
|
2549
|
+
code: "upstream_error",
|
|
2550
|
+
message: String(err)
|
|
2551
|
+
}
|
|
2552
|
+
};
|
|
2553
|
+
}
|
|
2554
|
+
export { SESSION_ASK_PATH as a, SESSION_TASK_PATH as c, RealExecutor as i, SESSION_TOKEN_HEADER as l, ENV_RUNNER_URL as n, SESSION_BROWSER_PATH as o, ENV_SESSION_TOKEN as r, SESSION_SUBMIT_PATH as s, ENV_OUTPUT_SCHEMA as t };
|