@online-tools/agent-runner 0.0.0-stage → 0.0.1-alpha-1
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/LICENSE +21 -0
- package/README.md +102 -2
- package/bin/gitcode-agent-runner.mjs +679 -0
- package/lib/claude-cli.mjs +85 -0
- package/lib/config.mjs +126 -0
- package/lib/connection.mjs +191 -0
- package/lib/doctor.mjs +240 -0
- package/lib/http.mjs +198 -0
- package/lib/jobs.mjs +494 -0
- package/lib/lock.mjs +66 -0
- package/lib/log.mjs +22 -0
- package/lib/packages.mjs +74 -0
- package/lib/prompt.mjs +76 -0
- package/lib/sandbox.mjs +110 -0
- package/lib/service.mjs +187 -0
- package/lib/setup.mjs +152 -0
- package/lib/skill-text.mjs +29 -0
- package/lib/skills.mjs +211 -0
- package/package.json +10 -4
package/lib/http.mjs
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
// The website protocol (/api/machine/v1) over fetch: Bearer token + client id
|
|
2
|
+
// on every request, JSON bodies, the SSE control channel. Only https, except
|
|
3
|
+
// http://127.0.0.1 / http://localhost for development.
|
|
4
|
+
|
|
5
|
+
import http from 'node:http';
|
|
6
|
+
|
|
7
|
+
export const PROTOCOL_PATH = '/api/machine/v1';
|
|
8
|
+
|
|
9
|
+
export class ApiError extends Error {
|
|
10
|
+
constructor(status, body, retryAfterMs = 0) {
|
|
11
|
+
super(body?.message || `HTTP ${status}`);
|
|
12
|
+
this.name = 'ApiError';
|
|
13
|
+
this.status = status;
|
|
14
|
+
this.code = typeof body?.error === 'string' ? body.error : '';
|
|
15
|
+
this.body = body || null;
|
|
16
|
+
this.retryAfterMs = retryAfterMs;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export class IdleError extends Error {
|
|
21
|
+
constructor(ms) {
|
|
22
|
+
super(`控制通道 ${Math.round(ms / 1000)} 秒没有数据`);
|
|
23
|
+
this.name = 'IdleError';
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** The website origin; throws for anything but https (or http on 127.0.0.1 / localhost). */
|
|
28
|
+
export function normalizeServerUrl(raw) {
|
|
29
|
+
let url;
|
|
30
|
+
try {
|
|
31
|
+
url = new URL(String(raw ?? '').trim());
|
|
32
|
+
} catch {
|
|
33
|
+
throw new Error('网站地址不正确');
|
|
34
|
+
}
|
|
35
|
+
const local = ['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname);
|
|
36
|
+
if (url.protocol !== 'https:' && !(url.protocol === 'http:' && local)) {
|
|
37
|
+
throw new Error('网站地址必须是 https(只有 127.0.0.1 / localhost 可以用 http)');
|
|
38
|
+
}
|
|
39
|
+
if (url.username || url.password) throw new Error('网站地址不能包含账号');
|
|
40
|
+
return url.origin;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function userAgent(version) {
|
|
44
|
+
return `gitcode-agent-runner/${version} (${process.platform}; ${process.arch}; node/${process.versions.node})`;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function retryAfterMs(response) {
|
|
48
|
+
const seconds = Number(response.headers.get('retry-after'));
|
|
49
|
+
return Number.isFinite(seconds) && seconds > 0 ? Math.min(seconds, 3600) * 1000 : 0;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function withTimeout(signal, ms) {
|
|
53
|
+
const timeout = AbortSignal.timeout(ms);
|
|
54
|
+
return signal ? AbortSignal.any([signal, timeout]) : timeout;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Splits SSE text into messages; returns the unfinished rest. */
|
|
58
|
+
function parseFrames(buffer, onEvent) {
|
|
59
|
+
let rest = buffer.replace(/\r\n?/g, '\n');
|
|
60
|
+
let index;
|
|
61
|
+
while ((index = rest.indexOf('\n\n')) >= 0) {
|
|
62
|
+
const frame = rest.slice(0, index);
|
|
63
|
+
rest = rest.slice(index + 2);
|
|
64
|
+
const data = frame
|
|
65
|
+
.split('\n')
|
|
66
|
+
.filter((line) => line.startsWith('data:'))
|
|
67
|
+
.map((line) => line.slice(5).replace(/^ /, ''))
|
|
68
|
+
.join('\n');
|
|
69
|
+
if (!data) continue; // comments (": ping") and empty frames
|
|
70
|
+
let event;
|
|
71
|
+
try {
|
|
72
|
+
event = JSON.parse(data);
|
|
73
|
+
} catch {
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
onEvent(event);
|
|
77
|
+
}
|
|
78
|
+
return rest;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function createClient({ server, token, clientId, version, timeoutMs = 30_000 }) {
|
|
82
|
+
const base = `${server}${PROTOCOL_PATH}`;
|
|
83
|
+
const headers = (extra = {}) => ({
|
|
84
|
+
Authorization: `Bearer ${token}`,
|
|
85
|
+
'X-Machine-Client': clientId,
|
|
86
|
+
'User-Agent': userAgent(version),
|
|
87
|
+
...extra,
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
async function request(method, url, body, { signal, timeout = timeoutMs } = {}) {
|
|
91
|
+
const response = await fetch(`${base}${url}`, {
|
|
92
|
+
method,
|
|
93
|
+
headers: headers(body === undefined ? {} : { 'Content-Type': 'application/json' }),
|
|
94
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
95
|
+
signal: withTimeout(signal, timeout),
|
|
96
|
+
});
|
|
97
|
+
const text = await response.text();
|
|
98
|
+
let json = null;
|
|
99
|
+
try {
|
|
100
|
+
json = text ? JSON.parse(text) : null;
|
|
101
|
+
} catch {
|
|
102
|
+
// Not JSON (e.g. a proxy error page).
|
|
103
|
+
}
|
|
104
|
+
if (!response.ok) throw new ApiError(response.status, json, retryAfterMs(response));
|
|
105
|
+
return json;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
async function download(url, { signal, timeout = 120_000 } = {}) {
|
|
109
|
+
const response = await fetch(`${base}${url}`, { headers: headers(), signal: withTimeout(signal, timeout) });
|
|
110
|
+
if (!response.ok) {
|
|
111
|
+
const text = await response.text().catch(() => '');
|
|
112
|
+
let json = null;
|
|
113
|
+
try {
|
|
114
|
+
json = JSON.parse(text);
|
|
115
|
+
} catch {
|
|
116
|
+
// Ignore.
|
|
117
|
+
}
|
|
118
|
+
throw new ApiError(response.status, json, retryAfterMs(response));
|
|
119
|
+
}
|
|
120
|
+
return Buffer.from(await response.arrayBuffer());
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* The control channel: calls onOpen() once connected and onEvent(event)
|
|
125
|
+
* for every message. Resolves when the server ends it, rejects with an
|
|
126
|
+
* ApiError (refused), an IdleError (no byte for idleMs) or a network error.
|
|
127
|
+
* Aborting `signal` resolves quietly.
|
|
128
|
+
*/
|
|
129
|
+
async function stream(url, { onEvent, onOpen, idleMs = 45_000, signal } = {}) {
|
|
130
|
+
const controller = new AbortController();
|
|
131
|
+
const stop = () => controller.abort();
|
|
132
|
+
signal?.addEventListener('abort', stop, { once: true });
|
|
133
|
+
let idle = false;
|
|
134
|
+
let timer = null;
|
|
135
|
+
const arm = () => {
|
|
136
|
+
clearTimeout(timer);
|
|
137
|
+
timer = setTimeout(() => {
|
|
138
|
+
idle = true;
|
|
139
|
+
controller.abort();
|
|
140
|
+
}, idleMs);
|
|
141
|
+
};
|
|
142
|
+
try {
|
|
143
|
+
arm();
|
|
144
|
+
const response = await fetch(`${base}${url}`, {
|
|
145
|
+
headers: headers({ Accept: 'text/event-stream', 'Accept-Encoding': 'identity', 'Cache-Control': 'no-cache' }),
|
|
146
|
+
signal: controller.signal,
|
|
147
|
+
});
|
|
148
|
+
if (!response.ok) {
|
|
149
|
+
const text = await response.text().catch(() => '');
|
|
150
|
+
let json = null;
|
|
151
|
+
try {
|
|
152
|
+
json = JSON.parse(text);
|
|
153
|
+
} catch {
|
|
154
|
+
// Ignore.
|
|
155
|
+
}
|
|
156
|
+
throw new ApiError(response.status, json, retryAfterMs(response));
|
|
157
|
+
}
|
|
158
|
+
onOpen?.();
|
|
159
|
+
const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
|
|
160
|
+
let buffer = '';
|
|
161
|
+
for (;;) {
|
|
162
|
+
const { value, done } = await reader.read();
|
|
163
|
+
if (done) break;
|
|
164
|
+
arm();
|
|
165
|
+
buffer = parseFrames(buffer + value, onEvent);
|
|
166
|
+
}
|
|
167
|
+
} catch (error) {
|
|
168
|
+
if (idle) throw new IdleError(idleMs);
|
|
169
|
+
if (signal?.aborted) return;
|
|
170
|
+
throw error;
|
|
171
|
+
} finally {
|
|
172
|
+
clearTimeout(timer);
|
|
173
|
+
signal?.removeEventListener('abort', stop);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
return { request, download, stream };
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** True when HTTPS_PROXY / HTTP_PROXY (either case) is set. */
|
|
181
|
+
export function hasProxy(env = process.env) {
|
|
182
|
+
return ['HTTPS_PROXY', 'HTTP_PROXY', 'https_proxy', 'http_proxy'].some((name) => Boolean(env[name]));
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* Makes this process's fetch use the proxy variables: 'enabled' (Node 24.14+
|
|
187
|
+
* / 25.4+ can do it at runtime), 'restart' (older Node only reads
|
|
188
|
+
* NODE_USE_ENV_PROXY at startup: run again with it set) or 'none'.
|
|
189
|
+
*/
|
|
190
|
+
export function proxyMode(env = process.env) {
|
|
191
|
+
if (!hasProxy(env)) return 'none';
|
|
192
|
+
if (typeof http.setGlobalProxyFromEnv === 'function') {
|
|
193
|
+
http.setGlobalProxyFromEnv();
|
|
194
|
+
return 'enabled';
|
|
195
|
+
}
|
|
196
|
+
if (env.NODE_USE_ENV_PROXY || env.GC_RUNNER_REEXEC) return 'none';
|
|
197
|
+
return 'restart';
|
|
198
|
+
}
|
package/lib/jobs.mjs
ADDED
|
@@ -0,0 +1,494 @@
|
|
|
1
|
+
// Running website jobs on this machine.
|
|
2
|
+
//
|
|
3
|
+
// A job carries data only (task text, model, credentials, timeout, Skill
|
|
4
|
+
// version); the command line, environment, tool allowlist and sandbox
|
|
5
|
+
// settings are built here. Per job:
|
|
6
|
+
// validate → accept → sync Skills → run directory → claude (own process
|
|
7
|
+
// group, sandboxed) → stream output (ordered batches, retried) → exit →
|
|
8
|
+
// delete the run directory.
|
|
9
|
+
// Logs name the run, feature, duration and exit code — never the API key,
|
|
10
|
+
// GITCODE_CRED, the machine token or proxy credentials.
|
|
11
|
+
|
|
12
|
+
import { spawn } from 'node:child_process';
|
|
13
|
+
import fs from 'node:fs';
|
|
14
|
+
import path from 'node:path';
|
|
15
|
+
import { StringDecoder } from 'node:string_decoder';
|
|
16
|
+
|
|
17
|
+
import { claudeArgs, claudeEnv } from './claude-cli.mjs';
|
|
18
|
+
import { ApiError } from './http.mjs';
|
|
19
|
+
import { caPaths, createRunLayout, homeReadAllow, passThroughEnv, writeSandboxSettings } from './sandbox.mjs';
|
|
20
|
+
|
|
21
|
+
export const FEATURE_LABELS = {
|
|
22
|
+
'pr-desc-issue-gen': 'PR 描述 / Issue',
|
|
23
|
+
'ascend-code-review': '代码检视(全量)',
|
|
24
|
+
'code-review-flash': '代码检视(快速)',
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
const RUN_ID = /^(skill|review)_\d+_[0-9a-f]{8}$/;
|
|
28
|
+
const TASK_MAX_BYTES = 64 * 1024;
|
|
29
|
+
const KILL_GRACE_MS = 5000;
|
|
30
|
+
const CLOSE_WAIT_MS = 2000;
|
|
31
|
+
|
|
32
|
+
const BATCH_DELAY_MS = 200;
|
|
33
|
+
const BATCH_BYTES = 64 * 1024;
|
|
34
|
+
const REQUEST_MAX_BYTES = 1024 * 1024;
|
|
35
|
+
const RETRY_MIN_MS = 1000;
|
|
36
|
+
const RETRY_MAX_MS = 10_000;
|
|
37
|
+
const UNDELIVERED_LIMIT_MS = 60_000;
|
|
38
|
+
const BACKLOG_LIMIT_BYTES = 32 * 1024 * 1024;
|
|
39
|
+
|
|
40
|
+
/** '' when the job is acceptable, else the name of the first bad field (design 5.4). */
|
|
41
|
+
export function invalidJobField(job) {
|
|
42
|
+
if (!job || typeof job !== 'object') return 'job';
|
|
43
|
+
if (job.protocol !== 1) return 'protocol';
|
|
44
|
+
if (typeof job.runId !== 'string' || !RUN_ID.test(job.runId)) return 'runId';
|
|
45
|
+
if (!Object.hasOwn(FEATURE_LABELS, job.feature)) return 'feature';
|
|
46
|
+
if (typeof job.task !== 'string' || !job.task || Buffer.byteLength(job.task) > TASK_MAX_BYTES) return 'task';
|
|
47
|
+
if (typeof job.model !== 'string' || job.model.length < 1 || job.model.length > 120 || /[\s/]/.test(job.model)) return 'model';
|
|
48
|
+
try {
|
|
49
|
+
const url = new URL(job.baseUrl);
|
|
50
|
+
if (url.protocol !== 'https:' || url.username || url.password || url.search || url.hash) return 'baseUrl';
|
|
51
|
+
} catch {
|
|
52
|
+
return 'baseUrl';
|
|
53
|
+
}
|
|
54
|
+
if (typeof job.apiKey !== 'string' || job.apiKey.length < 1 || job.apiKey.length > 512 || /[\r\n]/.test(job.apiKey)) return 'apiKey';
|
|
55
|
+
const env = job.env;
|
|
56
|
+
if (!env || typeof env !== 'object' || Array.isArray(env)) return 'env';
|
|
57
|
+
const keys = Object.keys(env);
|
|
58
|
+
if (keys.length !== 1 || keys[0] !== 'GITCODE_CRED' || typeof env.GITCODE_CRED !== 'string' || env.GITCODE_CRED.length > 512) return 'env';
|
|
59
|
+
if (!Number.isInteger(job.timeoutMs) || job.timeoutMs < 60_000 || job.timeoutMs > 14_400_000) return 'timeoutMs';
|
|
60
|
+
if (job.interactive !== false) return 'interactive';
|
|
61
|
+
if (typeof job.skillsHash !== 'string' || !/^[0-9a-f]{64}$/.test(job.skillsHash)) return 'skillsHash';
|
|
62
|
+
return '';
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
66
|
+
|
|
67
|
+
function backoff(attempt) {
|
|
68
|
+
return Math.min(RETRY_MAX_MS, RETRY_MIN_MS * 2 ** attempt);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Cuts `text` to at most `bytes` UTF-8 bytes without splitting a character. */
|
|
72
|
+
function sliceBytes(text, bytes) {
|
|
73
|
+
if (Buffer.byteLength(text) <= bytes) return [text, ''];
|
|
74
|
+
let end = Math.min(text.length, bytes);
|
|
75
|
+
while (end > 0 && Buffer.byteLength(text.slice(0, end)) > bytes) end = Math.floor(end * 0.9);
|
|
76
|
+
// Never split a surrogate pair.
|
|
77
|
+
if (end > 0 && /[\uD800-\uDBFF]/.test(text[end - 1])) end -= 1;
|
|
78
|
+
return [text.slice(0, end), text.slice(end)];
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Sends a job's output in order: one request at a time, numbered from 1, a
|
|
83
|
+
* batch every 200 ms or 64 KB (at most 1 MB). Failures retry the same batch
|
|
84
|
+
* (1–10 s apart). Gives up — and calls onFailure(reason) — when nothing got
|
|
85
|
+
* through for 60 s or 32 MB are waiting; onGone() when the website no longer
|
|
86
|
+
* knows the job (404).
|
|
87
|
+
*/
|
|
88
|
+
export class OutputUploader {
|
|
89
|
+
constructor({ client, runId, onGone, onFailure, onFatal }) {
|
|
90
|
+
this.client = client;
|
|
91
|
+
this.url = `/jobs/${encodeURIComponent(runId)}/output`;
|
|
92
|
+
this.onGone = onGone;
|
|
93
|
+
this.onFailure = onFailure;
|
|
94
|
+
this.onFatal = onFatal;
|
|
95
|
+
this.pending = []; // [{ stream, data }]
|
|
96
|
+
this.pendingBytes = 0;
|
|
97
|
+
this.pendingSince = 0;
|
|
98
|
+
this.lastSeq = 0; // last seq acknowledged
|
|
99
|
+
this.dead = false;
|
|
100
|
+
this.pump = null;
|
|
101
|
+
this.timer = null;
|
|
102
|
+
this.idle = [];
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
push(stream, data) {
|
|
106
|
+
if (this.dead || !data) return;
|
|
107
|
+
const last = this.pending.at(-1);
|
|
108
|
+
if (last && last.stream === stream) last.data += data;
|
|
109
|
+
else this.pending.push({ stream, data });
|
|
110
|
+
this.pendingBytes += Buffer.byteLength(data);
|
|
111
|
+
if (!this.pendingSince) this.pendingSince = Date.now();
|
|
112
|
+
if (this.pendingBytes > BACKLOG_LIMIT_BYTES) {
|
|
113
|
+
this.fail('输出积压过多');
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
this.schedule();
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
schedule() {
|
|
120
|
+
if (this.pump || this.dead) return;
|
|
121
|
+
const wait = this.pendingBytes >= BATCH_BYTES ? 0 : Math.max(0, BATCH_DELAY_MS - (Date.now() - this.pendingSince));
|
|
122
|
+
clearTimeout(this.timer);
|
|
123
|
+
this.timer = setTimeout(() => this.start(), wait);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
start() {
|
|
127
|
+
if (this.pump || this.dead || !this.pending.length) {
|
|
128
|
+
this.settleIdle();
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
this.pump = this.send().finally(() => {
|
|
132
|
+
this.pump = null;
|
|
133
|
+
if (this.pending.length && !this.dead) this.schedule();
|
|
134
|
+
else this.settleIdle();
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
takeBatch() {
|
|
139
|
+
const chunks = [];
|
|
140
|
+
let budget = REQUEST_MAX_BYTES;
|
|
141
|
+
while (this.pending.length && budget > 0) {
|
|
142
|
+
const head = this.pending[0];
|
|
143
|
+
const [part, rest] = sliceBytes(head.data, budget);
|
|
144
|
+
if (!part) break;
|
|
145
|
+
chunks.push({ stream: head.stream, data: part });
|
|
146
|
+
budget -= Buffer.byteLength(part);
|
|
147
|
+
if (rest) head.data = rest;
|
|
148
|
+
else this.pending.shift();
|
|
149
|
+
}
|
|
150
|
+
const bytes = chunks.reduce((sum, chunk) => sum + Buffer.byteLength(chunk.data), 0);
|
|
151
|
+
this.pendingBytes -= bytes;
|
|
152
|
+
this.pendingSince = this.pending.length ? Date.now() : 0;
|
|
153
|
+
return chunks;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
async send() {
|
|
157
|
+
const seq = this.lastSeq + 1;
|
|
158
|
+
const chunks = this.takeBatch();
|
|
159
|
+
const firstTry = Date.now();
|
|
160
|
+
for (let attempt = 0; !this.dead; attempt += 1) {
|
|
161
|
+
try {
|
|
162
|
+
const reply = await this.client.request('POST', this.url, { seq, chunks });
|
|
163
|
+
this.lastSeq = Math.max(seq, Number(reply?.ackSeq) || seq);
|
|
164
|
+
return;
|
|
165
|
+
} catch (error) {
|
|
166
|
+
if (error instanceof ApiError) {
|
|
167
|
+
if (error.status === 404) {
|
|
168
|
+
this.dead = true;
|
|
169
|
+
this.onGone();
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
172
|
+
if (error.status === 401 || (error.status === 403 && error.code === 'machine_blocked')) {
|
|
173
|
+
this.dead = true;
|
|
174
|
+
this.onFatal(error);
|
|
175
|
+
return;
|
|
176
|
+
}
|
|
177
|
+
if (error.status === 409 && error.code === 'seq_gap') {
|
|
178
|
+
// The website already has this batch (a reply got lost): carry on.
|
|
179
|
+
if (Number(error.body?.expected) === seq + 1) {
|
|
180
|
+
this.lastSeq = seq;
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
this.fail('输出序号与网站不一致');
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
if (error.status === 409 && error.code === 'machine_unknown') {
|
|
187
|
+
this.dead = true;
|
|
188
|
+
this.onGone();
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
if (Date.now() - firstTry > UNDELIVERED_LIMIT_MS) {
|
|
193
|
+
this.fail('输出 60 秒无法送达');
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
await sleep(error?.retryAfterMs || backoff(attempt));
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
fail(reason) {
|
|
202
|
+
if (this.dead) return;
|
|
203
|
+
this.dead = true;
|
|
204
|
+
this.pending = [];
|
|
205
|
+
this.pendingBytes = 0;
|
|
206
|
+
clearTimeout(this.timer);
|
|
207
|
+
this.onFailure(reason);
|
|
208
|
+
this.settleIdle();
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
settleIdle() {
|
|
212
|
+
if (this.pump || (this.pending.length && !this.dead)) return;
|
|
213
|
+
for (const resolve of this.idle.splice(0)) resolve();
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** Resolves once everything pushed so far was acknowledged (or the uploader gave up). */
|
|
217
|
+
drain() {
|
|
218
|
+
clearTimeout(this.timer);
|
|
219
|
+
if (!this.pump && this.pending.length && !this.dead) this.start();
|
|
220
|
+
return new Promise((resolve) => {
|
|
221
|
+
this.idle.push(resolve);
|
|
222
|
+
this.settleIdle();
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
function killGroup(pid, signal) {
|
|
228
|
+
if (!pid) return;
|
|
229
|
+
try {
|
|
230
|
+
process.kill(-pid, signal);
|
|
231
|
+
} catch {
|
|
232
|
+
// Gone already.
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* Holds the jobs running on this machine. `client`: http.mjs client;
|
|
238
|
+
* `skills`: SkillCache; `onFatal(error)`: the token or machine is no longer
|
|
239
|
+
* accepted (stop everything).
|
|
240
|
+
*/
|
|
241
|
+
export class JobManager {
|
|
242
|
+
constructor({ client, skills, workRoot, claudePath, realHome, env = process.env, platform = process.platform, log, onFatal = () => {} }) {
|
|
243
|
+
this.client = client;
|
|
244
|
+
this.skills = skills;
|
|
245
|
+
this.runsDir = path.join(workRoot, 'runs');
|
|
246
|
+
this.claudePath = claudePath;
|
|
247
|
+
this.realHome = realHome;
|
|
248
|
+
this.env = env;
|
|
249
|
+
this.platform = platform;
|
|
250
|
+
this.log = log;
|
|
251
|
+
this.onFatal = onFatal;
|
|
252
|
+
this.jobs = new Map(); // runId → entry
|
|
253
|
+
this.closed = false;
|
|
254
|
+
fs.mkdirSync(this.runsDir, { recursive: true, mode: 0o700 });
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
runningIds() {
|
|
258
|
+
return [...this.jobs.keys()];
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/** A `job` event from the control channel. Repeats of a running job are ignored. */
|
|
262
|
+
handle(job) {
|
|
263
|
+
if (this.closed) return;
|
|
264
|
+
const runId = typeof job?.runId === 'string' && job.runId.length <= 100 ? job.runId : '';
|
|
265
|
+
if (!runId || this.jobs.has(runId)) return;
|
|
266
|
+
const entry = { runId, job, child: null, cancelled: false, timedOut: false, failure: '', gone: false, done: null };
|
|
267
|
+
this.jobs.set(runId, entry);
|
|
268
|
+
entry.done = this.run(entry)
|
|
269
|
+
.catch((error) => this.log.error(`任务 ${runId} 异常:${error?.message || error}`))
|
|
270
|
+
.finally(() => this.jobs.delete(runId));
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/** Stops a job (website cancel, heartbeat reconciliation). */
|
|
274
|
+
cancel(runId) {
|
|
275
|
+
const entry = this.jobs.get(runId);
|
|
276
|
+
if (!entry || entry.cancelled) return;
|
|
277
|
+
entry.cancelled = true;
|
|
278
|
+
this.log.info(`任务 ${runId} 被取消`);
|
|
279
|
+
this.terminate(entry);
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
terminate(entry) {
|
|
283
|
+
const pid = entry.child?.pid;
|
|
284
|
+
if (!pid || entry.killing) return;
|
|
285
|
+
entry.killing = true;
|
|
286
|
+
killGroup(pid, 'SIGTERM');
|
|
287
|
+
setTimeout(() => killGroup(pid, 'SIGKILL'), KILL_GRACE_MS).unref();
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/** Stops every job and waits (≤ timeoutMs) for their exits to be reported. */
|
|
291
|
+
async stopAll(timeoutMs = 5000) {
|
|
292
|
+
this.closed = true;
|
|
293
|
+
const entries = [...this.jobs.values()];
|
|
294
|
+
for (const entry of entries) {
|
|
295
|
+
entry.cancelled = true;
|
|
296
|
+
this.terminate(entry);
|
|
297
|
+
}
|
|
298
|
+
await Promise.race([
|
|
299
|
+
Promise.allSettled(entries.map((entry) => entry.done)),
|
|
300
|
+
sleep(timeoutMs),
|
|
301
|
+
]);
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
async accept(entry) {
|
|
305
|
+
const url = `/jobs/${encodeURIComponent(entry.runId)}/accept`;
|
|
306
|
+
for (let attempt = 0; attempt < 4; attempt += 1) {
|
|
307
|
+
try {
|
|
308
|
+
await this.client.request('POST', url, {});
|
|
309
|
+
return true;
|
|
310
|
+
} catch (error) {
|
|
311
|
+
if (error instanceof ApiError && error.status === 404) return false;
|
|
312
|
+
if (error instanceof ApiError && (error.status === 401 || error.status === 403)) {
|
|
313
|
+
this.onFatal(error);
|
|
314
|
+
return false;
|
|
315
|
+
}
|
|
316
|
+
await sleep(1000 * (attempt + 1));
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
return false; // the website gives up after 10 s anyway
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
async reportExit(entry, { seq = 0, code = null, signal = null, timedOut = false, error = '' }) {
|
|
323
|
+
const url = `/jobs/${encodeURIComponent(entry.runId)}/exit`;
|
|
324
|
+
const body = { seq, code, signal, timedOut, error: String(error || '').slice(0, 500) };
|
|
325
|
+
for (let attempt = 0; attempt < 6; attempt += 1) {
|
|
326
|
+
try {
|
|
327
|
+
await this.client.request('POST', url, body);
|
|
328
|
+
return;
|
|
329
|
+
} catch (failure) {
|
|
330
|
+
if (failure instanceof ApiError) {
|
|
331
|
+
if (failure.status === 404) return;
|
|
332
|
+
if (failure.status === 401 || failure.status === 403) return;
|
|
333
|
+
if (failure.status === 409 && failure.code === 'seq_gap') {
|
|
334
|
+
this.log.warn(`任务 ${entry.runId} 的输出与网站不一致,无法补齐`);
|
|
335
|
+
return;
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
await sleep(failure?.retryAfterMs || backoff(attempt));
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
async run(entry) {
|
|
344
|
+
const { runId, job } = entry;
|
|
345
|
+
const started = Date.now();
|
|
346
|
+
const invalid = invalidJobField(job);
|
|
347
|
+
// Acknowledge first so the website does not wait for the accept timeout.
|
|
348
|
+
if (!(await this.accept(entry))) {
|
|
349
|
+
this.log.warn(`任务 ${runId} 已在网站上失效,未执行`);
|
|
350
|
+
return;
|
|
351
|
+
}
|
|
352
|
+
if (invalid) {
|
|
353
|
+
this.log.warn(`任务 ${runId} 参数不合法(${invalid}),未执行`);
|
|
354
|
+
await this.reportExit(entry, { error: `任务参数不合法:${invalid}` });
|
|
355
|
+
return;
|
|
356
|
+
}
|
|
357
|
+
const label = FEATURE_LABELS[job.feature];
|
|
358
|
+
this.log.info(`开始任务 ${runId}(${label})`);
|
|
359
|
+
|
|
360
|
+
let files;
|
|
361
|
+
try {
|
|
362
|
+
files = await this.skills.ensure(job.skillsHash);
|
|
363
|
+
} catch (error) {
|
|
364
|
+
if (error instanceof ApiError && (error.status === 401 || error.status === 403)) this.onFatal(error);
|
|
365
|
+
await this.reportExit(entry, { error: `同步 Skill 失败:${error?.message || error}` });
|
|
366
|
+
return;
|
|
367
|
+
}
|
|
368
|
+
if (entry.cancelled) {
|
|
369
|
+
await this.reportExit(entry, { signal: 'SIGTERM' });
|
|
370
|
+
return;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
const runDir = path.join(this.runsDir, runId);
|
|
374
|
+
let layout;
|
|
375
|
+
try {
|
|
376
|
+
fs.rmSync(runDir, { recursive: true, force: true });
|
|
377
|
+
layout = createRunLayout(runDir);
|
|
378
|
+
this.skills.copyInto(job.skillsHash, files, layout.skillsDir, layout.workAgentDir);
|
|
379
|
+
writeSandboxSettings(layout.settingsFile, {
|
|
380
|
+
workDir: fs.realpathSync(layout.workDir),
|
|
381
|
+
realHome: this.realHome,
|
|
382
|
+
readAllow: homeReadAllow({ realHome: this.realHome, pathEnv: this.env.PATH || '', caPaths: caPaths(this.env) }),
|
|
383
|
+
});
|
|
384
|
+
} catch (error) {
|
|
385
|
+
fs.rmSync(runDir, { recursive: true, force: true });
|
|
386
|
+
await this.reportExit(entry, { error: `准备运行目录失败:${error?.message || error}` });
|
|
387
|
+
return;
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
try {
|
|
391
|
+
const result = await this.spawnClaude(entry, layout);
|
|
392
|
+
if (!entry.gone) {
|
|
393
|
+
await this.reportExit(entry, {
|
|
394
|
+
seq: entry.uploader.lastSeq,
|
|
395
|
+
code: result.code,
|
|
396
|
+
signal: result.signal,
|
|
397
|
+
timedOut: entry.timedOut,
|
|
398
|
+
error: result.error || entry.failure,
|
|
399
|
+
});
|
|
400
|
+
}
|
|
401
|
+
const seconds = Math.round((Date.now() - started) / 1000);
|
|
402
|
+
const outcome = entry.timedOut ? '超时' : entry.cancelled ? '已取消' : result.error ? result.error : `退出码 ${result.code ?? result.signal}`;
|
|
403
|
+
this.log.info(`任务 ${runId} 结束(${label}):${outcome},用时 ${seconds} 秒`);
|
|
404
|
+
} finally {
|
|
405
|
+
fs.rmSync(runDir, { recursive: true, force: true });
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
spawnClaude(entry, layout) {
|
|
410
|
+
const { job } = entry;
|
|
411
|
+
return new Promise((resolve) => {
|
|
412
|
+
if (!this.claudePath) {
|
|
413
|
+
entry.uploader = { lastSeq: 0 };
|
|
414
|
+
resolve({ code: null, signal: null, error: '无法启动 claude:未安装' });
|
|
415
|
+
return;
|
|
416
|
+
}
|
|
417
|
+
let child;
|
|
418
|
+
try {
|
|
419
|
+
child = spawn(this.claudePath, claudeArgs({ settingsFile: layout.settingsFile }), {
|
|
420
|
+
cwd: layout.workDir,
|
|
421
|
+
detached: true,
|
|
422
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
423
|
+
env: claudeEnv({
|
|
424
|
+
path: this.env.PATH,
|
|
425
|
+
runDir: layout.runDir,
|
|
426
|
+
homeDir: layout.homeDir,
|
|
427
|
+
configDir: layout.configDir,
|
|
428
|
+
tmpDir: layout.tmpDir,
|
|
429
|
+
baseUrl: job.baseUrl,
|
|
430
|
+
apiKey: job.apiKey,
|
|
431
|
+
model: job.model,
|
|
432
|
+
extra: { ...passThroughEnv(this.env, this.platform), GITCODE_CRED: job.env.GITCODE_CRED },
|
|
433
|
+
}),
|
|
434
|
+
});
|
|
435
|
+
} catch (error) {
|
|
436
|
+
entry.uploader = { lastSeq: 0 };
|
|
437
|
+
resolve({ code: null, signal: null, error: `无法启动 claude:${error.code || error.message}` });
|
|
438
|
+
return;
|
|
439
|
+
}
|
|
440
|
+
entry.child = child;
|
|
441
|
+
const uploader = new OutputUploader({
|
|
442
|
+
client: this.client,
|
|
443
|
+
runId: entry.runId,
|
|
444
|
+
onGone: () => {
|
|
445
|
+
entry.gone = true;
|
|
446
|
+
this.terminate(entry);
|
|
447
|
+
},
|
|
448
|
+
onFailure: (reason) => {
|
|
449
|
+
entry.failure = reason;
|
|
450
|
+
this.terminate(entry);
|
|
451
|
+
},
|
|
452
|
+
onFatal: (error) => {
|
|
453
|
+
this.terminate(entry);
|
|
454
|
+
this.onFatal(error);
|
|
455
|
+
},
|
|
456
|
+
});
|
|
457
|
+
entry.uploader = uploader;
|
|
458
|
+
for (const name of ['stdout', 'stderr']) {
|
|
459
|
+
const decoder = new StringDecoder('utf8');
|
|
460
|
+
child[name].on('data', (chunk) => uploader.push(name, decoder.write(chunk)));
|
|
461
|
+
child[name].on('end', () => uploader.push(name, decoder.end()));
|
|
462
|
+
}
|
|
463
|
+
const timeout = setTimeout(() => {
|
|
464
|
+
entry.timedOut = true;
|
|
465
|
+
this.terminate(entry);
|
|
466
|
+
}, job.timeoutMs);
|
|
467
|
+
timeout.unref();
|
|
468
|
+
if (entry.cancelled) this.terminate(entry);
|
|
469
|
+
let closeWait = null;
|
|
470
|
+
let finished = false;
|
|
471
|
+
const finish = async (result) => {
|
|
472
|
+
if (finished) return;
|
|
473
|
+
finished = true;
|
|
474
|
+
clearTimeout(timeout);
|
|
475
|
+
clearTimeout(closeWait);
|
|
476
|
+
killGroup(child.pid, 'SIGKILL'); // whatever the job left behind
|
|
477
|
+
await uploader.drain();
|
|
478
|
+
resolve(result);
|
|
479
|
+
};
|
|
480
|
+
child.once('exit', () => {
|
|
481
|
+
// Background descendants may keep the pipes open: end them shortly after.
|
|
482
|
+
closeWait = setTimeout(() => killGroup(child.pid, 'SIGKILL'), CLOSE_WAIT_MS);
|
|
483
|
+
closeWait.unref();
|
|
484
|
+
});
|
|
485
|
+
// Spawn failures (ENOENT, EACCES) have no pid; 'close' may or may not follow.
|
|
486
|
+
child.once('error', (error) => {
|
|
487
|
+
if (!child.pid) finish({ code: null, signal: null, error: `无法启动 claude:${error.code || error.message}` });
|
|
488
|
+
});
|
|
489
|
+
child.once('close', (code, signal) => finish({ code, signal, error: '' }));
|
|
490
|
+
child.stdin.on('error', () => {});
|
|
491
|
+
child.stdin.end(job.task);
|
|
492
|
+
});
|
|
493
|
+
}
|
|
494
|
+
}
|