@online-tools/agent-runner 0.0.1-alpha-1 → 0.0.1-alpha-2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -6,7 +6,7 @@ GitCode 在线工具的 Agent 执行机器:把「在线 Agent」里的 **PR
6
6
 
7
7
  ## 安装与首次运行
8
8
 
9
- 需要 Linux 或 macOS,Node.js 22.21+(或 24.5+、25+)。
9
+ 需要 Linux 或 macOS 和 Node.js(npm)。程序本身要在 Node 22.21+(或 24.5+、25+)上运行;系统自带的 Node 更旧时(例如 Ubuntu 24.04 的 18、22.04 的 12、20.04 的 10),首次运行会提示下载 Node.js 官方的最新 LTS 版本(约 60 MB,nodejs.org,访问不了时用 npmmirror.com,均按 `SHASUMS256.txt` 校验 SHA-256),回车确认即可。下载的 Node 只给本程序用,不改动系统的 Node 和 PATH;以后运行(包括后台服务)自动使用它。不在终端里运行时(脚本、CI)不会自动下载,可以加 `--yes`。
10
10
 
11
11
  ```bash
12
12
  npm i -g @online-tools/agent-runner
@@ -45,6 +45,7 @@ gitcode-agent-runner service install # 可选:注册为后台服务,开
45
45
 
46
46
  - 配置:`${XDG_CONFIG_HOME:-~/.config}/gitcode-agent-runner/config.json`(0600)
47
47
  - Skill 缓存:`${XDG_CACHE_HOME:-~/.cache}/gitcode-agent-runner/skills/`
48
+ - 自动下载的 Node(只有系统 Node 过旧时才有):`${XDG_DATA_HOME:-~/.local/share}/gitcode-agent-runner/node/`
48
49
  - 工作目录:Linux `/var/tmp/gitcode-agent-runner-<uid>/`,macOS `$TMPDIR/gitcode-agent-runner/`。**不能在主目录之内**(沙箱不允许读取主目录)
49
50
 
50
51
  ## 任务怎么运行
@@ -94,6 +95,7 @@ gitcode-agent-runner service install # 可选:注册为后台服务,开
94
95
  gitcode-agent-runner service uninstall
95
96
  gitcode-agent-runner logout
96
97
  npm rm -g @online-tools/agent-runner
98
+ rm -rf ~/.local/share/gitcode-agent-runner # 自动下载的 Node(如果有)
97
99
  ```
98
100
 
99
101
  最后在网页「在线 Agent → 模型配置 → 执行机器」里移除这台机器。
@@ -0,0 +1,139 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+ // gitcode-agent-runner entry point. It makes sure the program (main.mjs) runs
4
+ // on a supported Node (22.21+ / 24.5+ / 25+). On an older one it uses the
5
+ // Node this program installed before, or — after asking — downloads the
6
+ // official LTS build (lib/node-runtime.cjs), then runs the same command again
7
+ // with it.
8
+ //
9
+ // Linux distributions ship old Node versions (Ubuntu 20.04: 10, 22.04: 12,
10
+ // 24.04: 18), and an ES module, `?.` or a `node:` name would fail there
11
+ // before any message could be shown. So this file and node-runtime.cjs are
12
+ // CommonJS that runs on Node 10 (tests/agent-runner-node.test.js checks the
13
+ // syntax).
14
+
15
+ const childProcess = require('child_process');
16
+ const os = require('os');
17
+ const readline = require('readline');
18
+
19
+ const runtime = require('../lib/node-runtime.cjs');
20
+
21
+ const ARGS = process.argv.slice(2);
22
+ // Tests stand in for an old Node with GC_RUNNER_TEST_NODE_VERSION (never passed on).
23
+ const CURRENT = process.env.GC_RUNNER_TEST_NODE_VERSION || process.versions.node;
24
+ const ATTENTION = 78; // EXIT_NEEDS_ATTENTION (lib/service.mjs): services do not restart on it
25
+ const VERSION_ARGS = ['version', '--version', '-v'];
26
+
27
+ function say(text) {
28
+ process.stdout.write(text + '\n');
29
+ }
30
+
31
+ // serviceExitCode() in lib/service.mjs (which old Node cannot load): launchd
32
+ // cannot exempt one exit code from KeepAlive, so 78 becomes 0 there.
33
+ function finish(code) {
34
+ const exitCode = code === ATTENTION && process.env.GC_RUNNER_SERVICE === 'launchd' ? 0 : code;
35
+ process.stdout.write('', () => process.exit(exitCode));
36
+ }
37
+
38
+ /** [Y/n]; an empty answer is yes, Ctrl+C / Ctrl+D no. */
39
+ function askYesNo(question) {
40
+ return new Promise((resolve) => {
41
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
42
+ let answered = false;
43
+ rl.on('close', () => {
44
+ if (answered) return;
45
+ process.stdout.write('\n');
46
+ resolve(false);
47
+ });
48
+ rl.question(question + ' [Y/n] ', (answer) => {
49
+ answered = true;
50
+ rl.close();
51
+ const value = String(answer || '').trim().toLowerCase();
52
+ resolve(!value || ['y', 'yes', '是', '好'].indexOf(value) !== -1);
53
+ });
54
+ });
55
+ }
56
+
57
+ function progressPrinter() {
58
+ if (!process.stdout.isTTY) return undefined;
59
+ let last = 0;
60
+ const mb = (bytes) => (bytes / 1048576).toFixed(1);
61
+ return (received, total) => {
62
+ const now = Date.now();
63
+ const done = total > 0 && received >= total;
64
+ if (now - last < 300 && !done) return;
65
+ last = now;
66
+ process.stdout.write('\r 已下载 ' + mb(received) + (total ? ' / ' + mb(total) : '') + ' MB');
67
+ if (done) process.stdout.write('\n');
68
+ };
69
+ }
70
+
71
+ /** A supported Node to run with: installed before, or downloaded now. Resolves { node } or { code }. */
72
+ async function supportedNode() {
73
+ const dataDir = runtime.nodeDataDir();
74
+ const installed = runtime.findManagedNode(dataDir);
75
+ if (installed) return { node: installed };
76
+ const yes = ARGS.indexOf('--yes') !== -1 || ARGS.indexOf('-y') !== -1;
77
+ const interactive = Boolean(process.stdin.isTTY && process.stdout.isTTY) && !process.env.GC_RUNNER_SERVICE;
78
+ say('当前 Node ' + CURRENT + ' 版本过低,本程序需要 Node ' + runtime.NODE_REQUIREMENT + '。');
79
+ if (!yes && !interactive) {
80
+ say('在终端里运行 gitcode-agent-runner 可以自动下载合适的 Node(脚本里可加 --yes),也可以自行升级 Node 后重试。');
81
+ return { code: ATTENTION };
82
+ }
83
+ say('可以下载 Node.js 官方的最新 LTS 版本(约 60 MB)到 ' + dataDir);
84
+ say('只供本程序使用,不改动系统里的 Node 和 PATH。');
85
+ if (!yes && !(await askYesNo('是否下载?'))) {
86
+ say('已取消。请自行安装 Node 22.21 以上版本(https://nodejs.org 或 nvm),然后重新运行。');
87
+ return { code: ATTENTION };
88
+ }
89
+ try {
90
+ const node = await runtime.installManagedNode({ dataDir, say: (text) => say(' ' + text), onProgress: progressPrinter() });
91
+ say('✓ 已安装 Node ' + node.version + '(' + node.nodePath + '),以后运行本程序会自动使用它');
92
+ return { node };
93
+ } catch (error) {
94
+ process.stderr.write(
95
+ '下载 Node 失败:' + error.message + '\n' +
96
+ '请检查网络(需要能访问 nodejs.org 或 npmmirror.com;公司代理请设置 HTTPS_PROXY),或自行安装 Node 22.21 以上版本。\n',
97
+ );
98
+ return { code: 1 };
99
+ }
100
+ }
101
+
102
+ /** Runs the same command with `node`; resolves with its exit code. */
103
+ function runWith(node) {
104
+ return new Promise((resolve) => {
105
+ const env = Object.assign({}, process.env, { GC_RUNNER_NODE_SWITCHED: node.nodePath });
106
+ delete env.GC_RUNNER_TEST_NODE_VERSION;
107
+ const child = childProcess.spawn(node.nodePath, [__filename].concat(ARGS), { stdio: 'inherit', env });
108
+ // The terminal signals both processes; the program stops its jobs itself.
109
+ for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) process.on(signal, () => child.kill(signal));
110
+ child.on('error', (error) => {
111
+ process.stderr.write('无法启动 ' + node.nodePath + ':' + error.message + '\n');
112
+ resolve(1);
113
+ });
114
+ child.on('exit', (code, signal) => resolve(code === null ? 128 + (os.constants.signals[signal] || 0) : code));
115
+ });
116
+ }
117
+
118
+ async function switchNode() {
119
+ if (process.env.GC_RUNNER_NODE_SWITCHED) {
120
+ process.stderr.write('已改用 ' + process.env.GC_RUNNER_NODE_SWITCHED + ',但它的版本 ' + CURRENT + ' 仍然不满足要求(需要 ' + runtime.NODE_REQUIREMENT + ')\n');
121
+ return ATTENTION;
122
+ }
123
+ const result = await supportedNode();
124
+ return result.node ? runWith(result.node) : result.code;
125
+ }
126
+
127
+ if (runtime.nodeSupported(CURRENT)) {
128
+ // require() of an ES module: every supported Node has it (main.mjs and its
129
+ // imports must not use top-level await).
130
+ require('./main.mjs');
131
+ } else if (ARGS.some((arg) => VERSION_ARGS.indexOf(arg) !== -1)) {
132
+ // The version needs no newer Node.
133
+ say(require('../package.json').version);
134
+ } else {
135
+ switchNode().then(finish, (error) => {
136
+ process.stderr.write('出错:' + (error && error.message ? error.message : error) + '\n');
137
+ finish(1);
138
+ });
139
+ }
@@ -1,7 +1,7 @@
1
- #!/usr/bin/env node
2
1
  // gitcode-agent-runner: runs GitCode 在线工具's 在线 Agent jobs (PR 描述 /
3
- // Issue, 代码检视) on this machine. This file owns every side effect —
4
- // arguments, the config file, the lock, signals, exit codes; ../lib does the work.
2
+ // Issue, 代码检视) on this machine. Loaded by gitcode-agent-runner.cjs once a
3
+ // supported Node runs it. This file owns every side effect — arguments, the
4
+ // config file, the lock, signals, exit codes; ../lib does the work.
5
5
  //
6
6
  // Exit codes: 0 stopped normally, 1 error, 78 needs a person (no token, token
7
7
  // deleted, machine blocked, same config running twice, unsupported system,
@@ -31,13 +31,15 @@ import { SANDBOX_DOCS, runDoctor, which } from '../lib/doctor.mjs';
31
31
  import { ApiError, createClient, normalizeServerUrl, proxyMode } from '../lib/http.mjs';
32
32
  import { FEATURE_LABELS, JobManager } from '../lib/jobs.mjs';
33
33
  import { LockedError, acquireLock, isRunnerAlive } from '../lib/lock.mjs';
34
+ import { NODE_REQUIREMENT, nodeSupported } from '../lib/node-runtime.cjs';
34
35
  import { createLogger } from '../lib/log.mjs';
35
36
  import { CancelledError, askYesNo, isInteractive, readHidden, readStdin } from '../lib/prompt.mjs';
36
37
  import { EXIT_NEEDS_ATTENTION, installService, serviceExitCode, serviceStatus, uninstallService } from '../lib/service.mjs';
37
38
  import { DEFAULT_REQUIRED_TOOLS, npmPrefixWritable, planSetup, runSetup } from '../lib/setup.mjs';
38
39
  import { SkillCache } from '../lib/skills.mjs';
39
40
 
40
- const ENTRY = fileURLToPath(import.meta.url);
41
+ // The command's entry point (it checks the Node version, then loads this file).
42
+ const ENTRY = fileURLToPath(new URL('./gitcode-agent-runner.cjs', import.meta.url));
41
43
  const VERSION = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
42
44
  const TOKEN_PATTERN = /^gcm_[A-Za-z0-9_-]{43}$/;
43
45
  const DOCTOR_INTERVAL_MS = 60 * 60_000;
@@ -81,16 +83,10 @@ class ExitError extends Error {
81
83
  const say = (text = '') => process.stdout.write(`${text}\n`);
82
84
  const log = createLogger();
83
85
 
84
- function nodeSupported(version = process.versions.node) {
85
- const [major, minor] = version.split('.').map(Number);
86
- if (major === 22) return minor >= 21;
87
- if (major === 24) return minor >= 5;
88
- return major >= 25;
89
- }
90
-
91
86
  function checkSystem() {
92
87
  if (!['linux', 'darwin'].includes(process.platform)) throw new ExitError(ATTENTION, '暂不支持此系统(只支持 Linux 和 macOS)');
93
- if (!nodeSupported()) throw new ExitError(ATTENTION, `需要 Node 22.21+、24.5+ 或 25+(当前 ${process.versions.node})`);
88
+ // gitcode-agent-runner.cjs already switched to a supported Node when it could.
89
+ if (!nodeSupported(process.versions.node)) throw new ExitError(ATTENTION, `需要 Node ${NODE_REQUIREMENT}(当前 ${process.versions.node})`);
94
90
  }
95
91
 
96
92
  /**
@@ -0,0 +1,594 @@
1
+ 'use strict';
2
+ // A supported Node for the program when the machine's own is too old (Linux
3
+ // distributions ship old ones: Ubuntu 20.04 has 10, 22.04 has 12, 24.04 has
4
+ // 18): download the latest official Node.js LTS build (nodejs.org, or the
5
+ // npmmirror copy when nodejs.org is unreachable), check its SHA-256 against
6
+ // SHASUMS256.txt, and keep only bin/node under
7
+ // ${XDG_DATA_HOME:-~/.local/share}/gitcode-agent-runner/node/. The system
8
+ // Node and PATH are never touched.
9
+ //
10
+ // This file runs on that old Node (from bin/gitcode-agent-runner.cjs), so it
11
+ // is CommonJS and must work on Node 10: bare built-in names (no `node:`), no
12
+ // `?.` / `??`, no fetch, fs.rmSync, Array#at or other newer APIs.
13
+ // tests/agent-runner-node.test.js checks the syntax. Requiring it has no
14
+ // side effects.
15
+
16
+ const childProcess = require('child_process');
17
+ const crypto = require('crypto');
18
+ const fs = require('fs');
19
+ const http = require('http');
20
+ const https = require('https');
21
+ const os = require('os');
22
+ const path = require('path');
23
+ const tls = require('tls');
24
+ const zlib = require('zlib');
25
+
26
+ const NODE_REQUIREMENT = '22.21+、24.5+ 或 25+';
27
+ const OFFICIAL_SOURCE = 'https://nodejs.org/dist';
28
+ const MIRROR_SOURCE = 'https://npmmirror.com/mirrors/node';
29
+ const REQUEST_TIMEOUT_MS = 30000;
30
+ const TEXT_LIMIT = 4 * 1024 * 1024;
31
+ const MAX_REDIRECTS = 5;
32
+
33
+ /** The program's requirement: 22.x ≥ 22.21, 24.x ≥ 24.5, or 25+. */
34
+ function nodeSupported(version) {
35
+ const match = /^v?(\d+)\.(\d+)\.(\d+)/.exec(String(version || ''));
36
+ if (!match) return false;
37
+ const major = Number(match[1]);
38
+ const minor = Number(match[2]);
39
+ if (major === 22) return minor >= 21;
40
+ if (major === 24) return minor >= 5;
41
+ return major >= 25;
42
+ }
43
+
44
+ function versionKey(version) {
45
+ return String(version).replace(/^v/, '').split('.').map(Number);
46
+ }
47
+
48
+ function compareVersionsDesc(a, b) {
49
+ const x = versionKey(a);
50
+ const y = versionKey(b);
51
+ for (let index = 0; index < 3; index += 1) {
52
+ if (x[index] !== y[index]) return y[index] - x[index];
53
+ }
54
+ return 0;
55
+ }
56
+
57
+ function nodeDataDir(env, home) {
58
+ const vars = env || process.env;
59
+ return path.join(vars.XDG_DATA_HOME || path.join(home || os.homedir(), '.local', 'share'), 'gitcode-agent-runner', 'node');
60
+ }
61
+
62
+ /** fs.rmSync(target, { recursive: true, force: true }), which Node < 14.14 lacks. */
63
+ function removeTree(target) {
64
+ if (typeof fs.rmSync === 'function') {
65
+ fs.rmSync(target, { recursive: true, force: true });
66
+ return;
67
+ }
68
+ let stat;
69
+ try {
70
+ stat = fs.lstatSync(target);
71
+ } catch (error) {
72
+ return;
73
+ }
74
+ if (stat.isDirectory()) {
75
+ for (const name of fs.readdirSync(target)) removeTree(path.join(target, name));
76
+ fs.rmdirSync(target);
77
+ } else fs.unlinkSync(target);
78
+ }
79
+
80
+ function isMusl(platform) {
81
+ if (platform !== 'linux') return false;
82
+ try {
83
+ if (process.report && typeof process.report.getReport === 'function') {
84
+ return !process.report.getReport().header.glibcVersionRuntime;
85
+ }
86
+ } catch (error) {
87
+ // Fall through to the loader check.
88
+ }
89
+ try {
90
+ return fs.readdirSync('/lib').some((name) => name.indexOf('ld-musl-') === 0);
91
+ } catch (error) {
92
+ return false;
93
+ }
94
+ }
95
+
96
+ /**
97
+ * Which official build fits: { indexKey (index.json "files"), suffix (file
98
+ * name) }, or null when there is none for this system.
99
+ */
100
+ function distTarget(platform, arch, musl) {
101
+ const system = platform || process.platform;
102
+ const cpu = arch || process.arch;
103
+ if (system === 'darwin') {
104
+ if (cpu === 'x64' || cpu === 'arm64') return { indexKey: 'osx-' + cpu + '-tar', suffix: 'darwin-' + cpu };
105
+ return null;
106
+ }
107
+ if (system !== 'linux') return null;
108
+ if (musl === undefined ? isMusl(system) : musl) {
109
+ return cpu === 'x64' ? { indexKey: 'linux-x64-musl', suffix: 'linux-x64-musl' } : null;
110
+ }
111
+ const names = { x64: 'linux-x64', arm64: 'linux-arm64', ppc64: 'linux-ppc64le', s390x: 'linux-s390x' };
112
+ return names[cpu] ? { indexKey: names[cpu], suffix: names[cpu] } : null;
113
+ }
114
+
115
+ /** The newest LTS release in index.json that has a build for `target` and meets the requirement. */
116
+ function pickRelease(index, target) {
117
+ if (!Array.isArray(index)) return null;
118
+ for (const release of index) {
119
+ if (!release || !release.lts || typeof release.version !== 'string') continue;
120
+ if (!/^v\d+\.\d+\.\d+$/.test(release.version)) continue;
121
+ if (!nodeSupported(release.version)) continue;
122
+ if (!Array.isArray(release.files) || release.files.indexOf(target.indexKey) === -1) continue;
123
+ return { version: release.version.slice(1), lts: String(release.lts) };
124
+ }
125
+ return null;
126
+ }
127
+
128
+ // ---- HTTPS (with HTTPS_PROXY via CONNECT) ---------------------------------------
129
+
130
+ function bareHost(hostname) {
131
+ return hostname.replace(/^\[(.*)\]$/, '$1');
132
+ }
133
+
134
+ function isLoopback(hostname) {
135
+ const host = bareHost(hostname);
136
+ return host === '127.0.0.1' || host === 'localhost' || host === '::1';
137
+ }
138
+
139
+ /** The proxy for an https URL (HTTPS_PROXY, then HTTP_PROXY), honouring NO_PROXY; null for none. */
140
+ function proxyFor(target, env) {
141
+ const vars = env || process.env;
142
+ if (isLoopback(target.hostname)) return null;
143
+ const raw = vars.HTTPS_PROXY || vars.https_proxy || vars.HTTP_PROXY || vars.http_proxy || '';
144
+ if (!raw) return null;
145
+ const skip = String(vars.NO_PROXY || vars.no_proxy || '')
146
+ .split(',')
147
+ .map((item) => item.trim().toLowerCase())
148
+ .filter(Boolean);
149
+ const host = target.hostname.toLowerCase();
150
+ for (const entry of skip) {
151
+ if (entry === '*') return null;
152
+ const bare = entry.replace(/^\*?\./, '').replace(/:\d+$/, '');
153
+ if (host === bare || host.endsWith('.' + bare)) return null;
154
+ }
155
+ let proxy;
156
+ try {
157
+ proxy = new URL(raw.indexOf('://') === -1 ? 'http://' + raw : raw);
158
+ } catch (error) {
159
+ return null;
160
+ }
161
+ return proxy.protocol === 'http:' ? proxy : null; // only plain-HTTP proxies (CONNECT)
162
+ }
163
+
164
+ /**
165
+ * GET `url` (https; http only to 127.0.0.1 / localhost) and resolve with the
166
+ * 200 response, following redirects. `timeoutMs` is an idle timeout. The
167
+ * response is guarded so that it always ends in 'end' or 'error' (old Node
168
+ * only emits 'close' when a response is cut off).
169
+ */
170
+ function httpGet(url, options, redirects) {
171
+ const opts = options || {};
172
+ const timeoutMs = opts.timeoutMs || REQUEST_TIMEOUT_MS;
173
+ const env = opts.env || process.env;
174
+ const tlsOptions = opts.tlsOptions || {};
175
+ const hops = redirects || 0;
176
+ return new Promise((resolve, reject) => {
177
+ let target;
178
+ try {
179
+ target = new URL(url);
180
+ } catch (error) {
181
+ reject(new Error('地址不正确:' + url));
182
+ return;
183
+ }
184
+ const secure = target.protocol === 'https:';
185
+ if (!secure && !(target.protocol === 'http:' && isLoopback(target.hostname))) {
186
+ reject(new Error('只允许 https 下载:' + url));
187
+ return;
188
+ }
189
+ const port = target.port || (secure ? '443' : '80');
190
+ const send = (socket) => {
191
+ const requestOptions = Object.assign({}, socket ? {} : tlsOptions, {
192
+ hostname: bareHost(target.hostname),
193
+ port,
194
+ path: target.pathname + target.search,
195
+ method: 'GET',
196
+ headers: { 'User-Agent': 'gitcode-agent-runner', Accept: '*/*' },
197
+ });
198
+ if (socket) requestOptions.createConnection = () => socket;
199
+ const request = (secure ? https : http).request(requestOptions, (response) => {
200
+ const statusCode = response.statusCode;
201
+ const location = response.headers.location;
202
+ if ([301, 302, 303, 307, 308].indexOf(statusCode) !== -1 && location) {
203
+ response.resume();
204
+ if (hops >= MAX_REDIRECTS) {
205
+ reject(new Error('重定向过多:' + url));
206
+ return;
207
+ }
208
+ resolve(httpGet(new URL(location, target).toString(), opts, hops + 1));
209
+ return;
210
+ }
211
+ if (statusCode !== 200) {
212
+ response.resume();
213
+ reject(new Error('HTTP ' + statusCode + ':' + url));
214
+ return;
215
+ }
216
+ response.setTimeout(timeoutMs, () => response.destroy(new Error('下载超时:' + url)));
217
+ response.on('close', () => {
218
+ if (!response.complete) response.emit('error', new Error('连接中断:' + url));
219
+ });
220
+ resolve(response);
221
+ });
222
+ request.setTimeout(timeoutMs, () => request.destroy(new Error('连接超时:' + target.host)));
223
+ request.on('error', reject);
224
+ request.end();
225
+ };
226
+ const proxy = secure ? proxyFor(target, env) : null;
227
+ if (!proxy) {
228
+ send(null);
229
+ return;
230
+ }
231
+ const headers = { Host: target.hostname + ':' + port };
232
+ if (proxy.username) {
233
+ const credentials = decodeURIComponent(proxy.username) + ':' + decodeURIComponent(proxy.password);
234
+ headers['Proxy-Authorization'] = 'Basic ' + Buffer.from(credentials).toString('base64');
235
+ }
236
+ const connect = http.request({
237
+ hostname: bareHost(proxy.hostname),
238
+ port: proxy.port || 80,
239
+ method: 'CONNECT',
240
+ path: target.hostname + ':' + port,
241
+ headers,
242
+ });
243
+ connect.setTimeout(timeoutMs, () => connect.destroy(new Error('代理连接超时')));
244
+ connect.on('connect', (response, socket) => {
245
+ if (response.statusCode !== 200) {
246
+ socket.destroy();
247
+ reject(new Error('代理拒绝连接(HTTP ' + response.statusCode + ')'));
248
+ return;
249
+ }
250
+ // The tunnel's own request keeps the idle timeout from here on.
251
+ socket.setTimeout(0);
252
+ socket.removeAllListeners('timeout');
253
+ const tunnel = tls.connect(Object.assign({ socket, servername: bareHost(target.hostname) }, tlsOptions));
254
+ tunnel.once('secureConnect', () => send(tunnel));
255
+ tunnel.once('error', reject);
256
+ });
257
+ connect.on('error', reject);
258
+ connect.end();
259
+ });
260
+ }
261
+
262
+ function httpText(url, options) {
263
+ return httpGet(url, options).then(
264
+ (response) =>
265
+ new Promise((resolve, reject) => {
266
+ const chunks = [];
267
+ let size = 0;
268
+ response.on('data', (chunk) => {
269
+ size += chunk.length;
270
+ if (size > TEXT_LIMIT) {
271
+ response.destroy();
272
+ reject(new Error('响应过大:' + url));
273
+ return;
274
+ }
275
+ chunks.push(chunk);
276
+ });
277
+ response.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
278
+ response.on('error', reject);
279
+ }),
280
+ );
281
+ }
282
+
283
+ /** Streams `url` into `file`; resolves with { sha256, size }. `options.onProgress(received, total)`. */
284
+ function downloadFile(url, file, options) {
285
+ const opts = options || {};
286
+ return httpGet(url, opts).then(
287
+ (response) =>
288
+ new Promise((resolve, reject) => {
289
+ const total = Number(response.headers['content-length']) || 0;
290
+ const hash = crypto.createHash('sha256');
291
+ let received = 0;
292
+ const out = fs.createWriteStream(file, { mode: 0o600 });
293
+ response.on('data', (chunk) => {
294
+ hash.update(chunk);
295
+ received += chunk.length;
296
+ if (opts.onProgress) opts.onProgress(received, total);
297
+ });
298
+ response.on('error', (error) => {
299
+ out.destroy();
300
+ reject(error);
301
+ });
302
+ out.on('error', reject);
303
+ out.on('finish', () => {
304
+ if (total && received !== total) reject(new Error('下载不完整'));
305
+ else resolve({ sha256: hash.digest('hex'), size: received });
306
+ });
307
+ response.pipe(out);
308
+ }),
309
+ );
310
+ }
311
+
312
+ /** The SHA-256 of `fileName` in a SHASUMS256.txt, or ''. */
313
+ function checksumFor(sums, fileName) {
314
+ for (const line of String(sums).split('\n')) {
315
+ const match = /^([0-9a-f]{64})\s+\*?(\S+)$/.exec(line.trim());
316
+ if (match && match[2] === fileName) return match[1];
317
+ }
318
+ return '';
319
+ }
320
+
321
+ // ---- tar.gz: take bin/node only -----------------------------------------------
322
+
323
+ function field(header, start, length) {
324
+ const raw = header.subarray(start, start + length);
325
+ const end = raw.indexOf(0);
326
+ return raw.subarray(0, end === -1 ? length : end).toString('utf8');
327
+ }
328
+
329
+ function entrySize(header) {
330
+ if (header[124] & 0x80) {
331
+ // GNU base-256 for large sizes.
332
+ let size = 0;
333
+ for (let index = 125; index < 136; index += 1) size = size * 256 + header[index];
334
+ return size;
335
+ }
336
+ const text = field(header, 124, 12).trim();
337
+ return text ? parseInt(text, 8) : 0;
338
+ }
339
+
340
+ /**
341
+ * Extracts the one regular file `wanted` (e.g. node-v26.13.1-linux-x64/bin/node)
342
+ * from a .tar.gz into `dest` (mode 0755). Nothing else is ever written, so
343
+ * archive paths cannot escape. Understands ustar names, GNU long names and
344
+ * pax `path` records. Resolves false when the entry is missing.
345
+ */
346
+ function extractTarEntry(archive, wanted, dest) {
347
+ return new Promise((resolve, reject) => {
348
+ const input = fs.createReadStream(archive);
349
+ const gunzip = zlib.createGunzip();
350
+ let header = Buffer.alloc(0);
351
+ let dataLeft = 0; // bytes of the current entry still to read
352
+ let padLeft = 0; // padding after it
353
+ let fd = null; // open while writing `wanted`
354
+ let collect = null; // { kind: 'L' | 'x', chunks } for long names / pax data
355
+ let nextName = '';
356
+ let found = false;
357
+ let ended = false;
358
+ let failed = false;
359
+ const fail = (error) => {
360
+ if (failed) return;
361
+ failed = true;
362
+ if (fd !== null) {
363
+ try {
364
+ fs.closeSync(fd);
365
+ } catch (closeError) {
366
+ // Ignore.
367
+ }
368
+ fd = null;
369
+ }
370
+ input.destroy();
371
+ gunzip.destroy();
372
+ reject(error);
373
+ };
374
+ const finishEntry = () => {
375
+ if (fd !== null) {
376
+ fs.closeSync(fd);
377
+ fd = null;
378
+ found = true;
379
+ }
380
+ if (collect) {
381
+ const text = Buffer.concat(collect.chunks).toString('utf8');
382
+ if (collect.kind === 'L') nextName = text.replace(/\0+$/, '');
383
+ else {
384
+ const match = /(?:^|\n)\d+ path=([^\n]*)\n/.exec(text);
385
+ if (match) nextName = match[1];
386
+ }
387
+ collect = null;
388
+ }
389
+ };
390
+ const startEntry = (block) => {
391
+ const name = field(block, 0, 100);
392
+ const prefix = block.subarray(257, 262).toString('latin1') === 'ustar' ? field(block, 345, 155) : '';
393
+ const type = String.fromCharCode(block[156] || 48);
394
+ const size = entrySize(block);
395
+ dataLeft = size;
396
+ padLeft = (512 - (size % 512)) % 512;
397
+ if (type === 'L' || type === 'x') {
398
+ collect = { kind: type, chunks: [] };
399
+ return;
400
+ }
401
+ const full = (nextName || (prefix ? prefix + '/' + name : name)).replace(/^\.\//, '');
402
+ nextName = '';
403
+ if (full === wanted && (type === '0' || type === '7')) {
404
+ fd = fs.openSync(dest, 'w', 0o755);
405
+ }
406
+ if (dataLeft === 0) finishEntry();
407
+ };
408
+ gunzip.on('data', (chunk) => {
409
+ if (failed) return;
410
+ try {
411
+ let offset = 0;
412
+ while (offset < chunk.length && !ended) {
413
+ if (dataLeft > 0) {
414
+ const count = Math.min(dataLeft, chunk.length - offset);
415
+ const slice = chunk.subarray(offset, offset + count);
416
+ if (fd !== null) fs.writeSync(fd, slice);
417
+ else if (collect) collect.chunks.push(Buffer.from(slice));
418
+ offset += count;
419
+ dataLeft -= count;
420
+ if (dataLeft === 0) finishEntry();
421
+ continue;
422
+ }
423
+ if (padLeft > 0) {
424
+ const count = Math.min(padLeft, chunk.length - offset);
425
+ offset += count;
426
+ padLeft -= count;
427
+ continue;
428
+ }
429
+ const take = chunk.subarray(offset, offset + 512 - header.length);
430
+ header = Buffer.concat([header, take]);
431
+ offset += take.length;
432
+ if (header.length < 512) continue;
433
+ const block = header;
434
+ header = Buffer.alloc(0);
435
+ if (block.every((byte) => byte === 0)) {
436
+ ended = true; // end-of-archive marker
437
+ break;
438
+ }
439
+ startEntry(block);
440
+ }
441
+ } catch (error) {
442
+ fail(error);
443
+ }
444
+ });
445
+ gunzip.on('end', () => {
446
+ if (failed) return;
447
+ if (fd !== null) {
448
+ fs.closeSync(fd);
449
+ fd = null;
450
+ }
451
+ resolve(found);
452
+ });
453
+ gunzip.on('error', fail);
454
+ input.on('error', fail);
455
+ input.pipe(gunzip);
456
+ });
457
+ }
458
+
459
+ // ---- Install / find ---------------------------------------------------------------
460
+
461
+ /** Whether `nodePath --version` prints v<version>; `output` explains a failure. */
462
+ function nodeRuns(nodePath, version) {
463
+ const result = childProcess.spawnSync(nodePath, ['--version'], { encoding: 'utf8', timeout: 15000, stdio: ['ignore', 'pipe', 'pipe'] });
464
+ const output = ((result.stdout || '') + (result.stderr || '') || (result.error ? result.error.message : '')).trim();
465
+ return { ok: result.status === 0 && String(result.stdout).trim() === 'v' + version, output };
466
+ }
467
+
468
+ /** The newest installed supported Node that runs: { nodePath, version } or null. */
469
+ function findManagedNode(dataDir) {
470
+ let names = [];
471
+ try {
472
+ names = fs.readdirSync(dataDir);
473
+ } catch (error) {
474
+ return null;
475
+ }
476
+ const versions = names
477
+ .filter((name) => /^v\d+\.\d+\.\d+$/.test(name) && nodeSupported(name))
478
+ .map((name) => name.slice(1))
479
+ .sort(compareVersionsDesc);
480
+ for (const version of versions) {
481
+ const nodePath = path.join(dataDir, 'v' + version, 'bin', 'node');
482
+ if (fs.existsSync(nodePath) && nodeRuns(nodePath, version).ok) return { nodePath, version };
483
+ }
484
+ return null;
485
+ }
486
+
487
+ function hostOf(source) {
488
+ try {
489
+ return new URL(source).host;
490
+ } catch (error) {
491
+ return source;
492
+ }
493
+ }
494
+
495
+ /** One source: resolves with the installed { nodePath, version }. */
496
+ async function installFrom(source, { dataDir, target, env, tlsOptions, say, onProgress }) {
497
+ const request = { env, tlsOptions };
498
+ const work = fs.mkdtempSync(path.join(dataDir, '.download-'));
499
+ try {
500
+ const release = pickRelease(JSON.parse(await httpText(source + '/index.json', request)), target);
501
+ if (!release) throw new Error('没有找到合适的 LTS 版本');
502
+ const fileName = 'node-v' + release.version + '-' + target.suffix + '.tar.gz';
503
+ let expected = checksumFor(await httpText(source + '/v' + release.version + '/SHASUMS256.txt', request), fileName);
504
+ if (!expected) throw new Error('SHASUMS256.txt 里没有 ' + fileName);
505
+ if (source === MIRROR_SOURCE) {
506
+ let official = '';
507
+ try {
508
+ official = checksumFor(await httpText(OFFICIAL_SOURCE + '/v' + release.version + '/SHASUMS256.txt', { env, timeoutMs: 10000 }), fileName);
509
+ } catch (error) {
510
+ say('无法访问 nodejs.org 核对校验值,使用 ' + hostOf(source) + ' 提供的校验值');
511
+ }
512
+ if (official && official !== expected) throw new Error('镜像的校验值与 nodejs.org 不一致,已停止');
513
+ if (official) expected = official;
514
+ }
515
+ const url = source + '/v' + release.version + '/' + fileName;
516
+ say('下载 ' + url);
517
+ const archive = path.join(work, fileName);
518
+ const got = await downloadFile(url, archive, { env, tlsOptions, onProgress });
519
+ if (got.sha256 !== expected) throw new Error(fileName + ' 的 SHA-256 与 SHASUMS256.txt 不一致,已丢弃');
520
+ say('✓ 校验通过(SHA-256)');
521
+ const staged = path.join(work, 'v' + release.version);
522
+ fs.mkdirSync(path.join(staged, 'bin'), { recursive: true });
523
+ const stagedNode = path.join(staged, 'bin', 'node');
524
+ const entry = 'node-v' + release.version + '-' + target.suffix + '/bin/node';
525
+ if (!(await extractTarEntry(archive, entry, stagedNode))) throw new Error('压缩包里没有 ' + entry);
526
+ fs.chmodSync(stagedNode, 0o755);
527
+ const check = nodeRuns(stagedNode, release.version);
528
+ if (!check.ok) throw new Error('下载的 Node 无法在这台机器上运行:' + (check.output.slice(0, 300) || '没有输出'));
529
+ const final = path.join(dataDir, 'v' + release.version);
530
+ removeTree(final);
531
+ fs.renameSync(staged, final);
532
+ // Older managed versions are no longer needed.
533
+ for (const name of fs.readdirSync(dataDir)) {
534
+ if (/^v\d+\.\d+\.\d+$/.test(name) && name !== 'v' + release.version) removeTree(path.join(dataDir, name));
535
+ }
536
+ return { nodePath: path.join(final, 'bin', 'node'), version: release.version };
537
+ } finally {
538
+ removeTree(work);
539
+ }
540
+ }
541
+
542
+ /**
543
+ * Downloads and installs the latest LTS Node into `dataDir`; resolves with
544
+ * { nodePath, version, source }. `sources`: tried in order (GC_RUNNER_NODE_MIRROR
545
+ * when set, else nodejs.org then npmmirror). With the mirror, its checksum is
546
+ * cross-checked against nodejs.org when that answers. `say(text)` reports
547
+ * steps, `onProgress(received, total)` the download.
548
+ */
549
+ async function installManagedNode(options) {
550
+ const platform = options.platform || process.platform;
551
+ const arch = options.arch || process.arch;
552
+ const env = options.env || process.env;
553
+ const say = options.say || (() => {});
554
+ const dataDir = options.dataDir;
555
+ const target = distTarget(platform, arch, options.musl);
556
+ if (!target) throw new Error('没有适用于 ' + platform + '/' + arch + ' 的 Node.js 官方版本,请自行安装 Node ' + NODE_REQUIREMENT);
557
+ const list = options.sources || (env.GC_RUNNER_NODE_MIRROR ? [env.GC_RUNNER_NODE_MIRROR.replace(/\/+$/, '')] : [OFFICIAL_SOURCE, MIRROR_SOURCE]);
558
+ fs.mkdirSync(dataDir, { recursive: true, mode: 0o700 });
559
+ // Left by an interrupted download (Ctrl+C skips the cleanup in installFrom).
560
+ for (const name of fs.readdirSync(dataDir)) {
561
+ if (name.indexOf('.download-') === 0) removeTree(path.join(dataDir, name));
562
+ }
563
+ const problems = [];
564
+ for (let index = 0; index < list.length; index += 1) {
565
+ const source = list[index];
566
+ try {
567
+ const installed = await installFrom(source, { dataDir, target, env, tlsOptions: options.tlsOptions, say, onProgress: options.onProgress });
568
+ return { nodePath: installed.nodePath, version: installed.version, source };
569
+ } catch (error) {
570
+ problems.push(hostOf(source) + ':' + error.message);
571
+ if (index < list.length - 1) say(hostOf(source) + ' 下载失败(' + error.message + '),改用下一个来源');
572
+ }
573
+ }
574
+ throw new Error(problems.join(';'));
575
+ }
576
+
577
+ module.exports = {
578
+ NODE_REQUIREMENT,
579
+ OFFICIAL_SOURCE,
580
+ MIRROR_SOURCE,
581
+ nodeSupported,
582
+ nodeDataDir,
583
+ distTarget,
584
+ pickRelease,
585
+ proxyFor,
586
+ httpGet,
587
+ httpText,
588
+ downloadFile,
589
+ checksumFor,
590
+ extractTarEntry,
591
+ nodeRuns,
592
+ findManagedNode,
593
+ installManagedNode,
594
+ };
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@online-tools/agent-runner",
3
- "version": "0.0.1-alpha-1",
3
+ "version": "0.0.1-alpha-2",
4
4
  "description": "GitCode 在线工具的 Agent 执行机器:在自己的机器上运行 PR 描述、代码检视任务",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
- "bin": { "gitcode-agent-runner": "bin/gitcode-agent-runner.mjs" },
7
+ "bin": { "gitcode-agent-runner": "bin/gitcode-agent-runner.cjs" },
8
8
  "files": ["bin/", "lib/", "README.md", "LICENSE"],
9
- "engines": { "node": ">=22.21.0" },
9
+ "engines": { "node": ">=10.12.0" },
10
10
  "os": ["linux", "darwin"],
11
11
  "publishConfig": { "access": "public" }
12
12
  }