@online-tools/agent-runner 0.0.1-alpha-1 → 0.0.1-alpha-3
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 +16 -6
- package/bin/gitcode-agent-runner.cjs +139 -0
- package/bin/{gitcode-agent-runner.mjs → main.mjs} +94 -28
- package/lib/config.mjs +3 -1
- package/lib/connection.mjs +36 -2
- package/lib/node-runtime.cjs +594 -0
- package/lib/prompt.mjs +18 -0
- package/lib/system-info.mjs +132 -0
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -6,16 +6,20 @@ GitCode 在线工具的 Agent 执行机器:把「在线 Agent」里的 **PR
|
|
|
6
6
|
|
|
7
7
|
## 安装与首次运行
|
|
8
8
|
|
|
9
|
-
需要 Linux 或 macOS
|
|
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
|
|
13
|
-
gitcode-agent-runner # 首次运行:粘贴接入令牌 → 连接 → 检查并安装依赖 → 保持在线
|
|
13
|
+
gitcode-agent-runner # 首次运行:粘贴接入令牌 → 起名字 → 连接 → 检查并安装依赖 → 保持在线
|
|
14
14
|
gitcode-agent-runner service install # 可选:注册为后台服务,开机自启
|
|
15
15
|
```
|
|
16
16
|
|
|
17
17
|
接入令牌在网页「在线 Agent → 模型配置 → 接入令牌」里新建。粘贴后先向网站校验,通过才保存;以后启动直接连接。
|
|
18
18
|
|
|
19
|
+
粘贴令牌后会问这台机器叫什么(回车用主机名;脚本里用 `--name <名称>`),网页上就用这个名字。之后改名请在网页上改。
|
|
20
|
+
|
|
21
|
+
**新机器要在网页上确认后才会收到任务**:打开「在线 Agent → 模型配置 → 执行机器」,核对主机名、IP 和令牌后点「确认」(也可以在这里改名字)。确认前程序照样保持在线,确认后会提示「可以接收任务了」。不是你的机器出现在那里时,请封禁它并删除对应的令牌。
|
|
22
|
+
|
|
19
23
|
首次运行会检查依赖并列出要执行的安装命令,确认后才执行:
|
|
20
24
|
|
|
21
25
|
- `git`、`curl`、`python3`、`jq`、`sed`、`base64`:Skill 需要(各功能需要的不完全一样)
|
|
@@ -31,22 +35,27 @@ gitcode-agent-runner service install # 可选:注册为后台服务,开
|
|
|
31
35
|
| 命令 | 作用 |
|
|
32
36
|
|---|---|
|
|
33
37
|
| `gitcode-agent-runner [start]` | 连接网站并等待任务 |
|
|
34
|
-
| `login [--new-id] [--token-stdin]` | 输入(更换)接入令牌,校验通过才保存。`--new-id`
|
|
38
|
+
| `login [--new-id] [--token-stdin] [--name <名称>]` | 输入(更换)接入令牌,校验通过才保存。`--new-id` 重新生成机器标识(网页上会作为新机器出现,需要重新确认);`--token-stdin` 从标准输入读令牌 |
|
|
35
39
|
| `logout` | 清除本机保存的令牌(机器标识保留) |
|
|
36
40
|
| `setup [--yes]` | 检查并安装缺少或版本过低的依赖(只在终端里运行;`--yes` 跳过确认) |
|
|
37
|
-
| `doctor [--json]` |
|
|
38
|
-
| `status` | 网站地址、令牌前 12
|
|
41
|
+
| `doctor [--json]` | 检查依赖、沙箱和各功能是否可用,显示系统信息 |
|
|
42
|
+
| `status` | 网站地址、令牌前 12 位、机器标识、登记名称、工作目录、系统信息、服务状态和连接测试 |
|
|
39
43
|
| `service install \| uninstall \| status` | 后台服务:Linux 为 systemd 用户服务,macOS 为 launchd |
|
|
40
44
|
| `version` / `help` | — |
|
|
41
45
|
|
|
42
|
-
全局选项:`--server <url>`(默认 `https://online-tools.closerouter.site`,会保存)、`--work-dir <dir>`(会保存)、`--allow-root`。
|
|
46
|
+
全局选项:`--server <url>`(默认 `https://online-tools.closerouter.site`,会保存)、`--work-dir <dir>`(会保存)、`--name <名称>`(机器登记时用的名称,1–40 个字符,会保存)、`--allow-root`。
|
|
43
47
|
|
|
44
48
|
文件位置:
|
|
45
49
|
|
|
46
50
|
- 配置:`${XDG_CONFIG_HOME:-~/.config}/gitcode-agent-runner/config.json`(0600)
|
|
47
51
|
- Skill 缓存:`${XDG_CACHE_HOME:-~/.cache}/gitcode-agent-runner/skills/`
|
|
52
|
+
- 自动下载的 Node(只有系统 Node 过旧时才有):`${XDG_DATA_HOME:-~/.local/share}/gitcode-agent-runner/node/`
|
|
48
53
|
- 工作目录:Linux `/var/tmp/gitcode-agent-runner-<uid>/`,macOS `$TMPDIR/gitcode-agent-runner/`。**不能在主目录之内**(沙箱不允许读取主目录)
|
|
49
54
|
|
|
55
|
+
## 上报给网站的信息
|
|
56
|
+
|
|
57
|
+
除了程序版本和各项依赖是否可用,程序还会在连接和每次心跳(约 20 秒)时上报这台机器的概况,显示在网页「执行机器」的「资源」和「详情」里(只有你和网站管理员看得到):系统和内核、CPU 型号和核数、内存总量和可用量(容器有内存限制时同时显示限制)、工作目录所在磁盘的总量和可用量、负载、系统运行时间、运行程序的账号、是否在容器内、是否在用程序自动下载的 Node。不上报文件内容、环境变量或进程列表。
|
|
58
|
+
|
|
50
59
|
## 任务怎么运行
|
|
51
60
|
|
|
52
61
|
网站只下发任务数据:任务文本、模型、你的模型 API Key、GitCode 授权、超时和 Skill 版本。claude 的命令行、环境变量、工具白名单和沙箱设置都由本程序生成,网站改不了。
|
|
@@ -94,6 +103,7 @@ gitcode-agent-runner service install # 可选:注册为后台服务,开
|
|
|
94
103
|
gitcode-agent-runner service uninstall
|
|
95
104
|
gitcode-agent-runner logout
|
|
96
105
|
npm rm -g @online-tools/agent-runner
|
|
106
|
+
rm -rf ~/.local/share/gitcode-agent-runner # 自动下载的 Node(如果有)
|
|
97
107
|
```
|
|
98
108
|
|
|
99
109
|
最后在网页「在线 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.
|
|
4
|
-
//
|
|
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,15 +31,19 @@ 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
|
-
import { CancelledError, askYesNo, isInteractive, readHidden, readStdin } from '../lib/prompt.mjs';
|
|
36
|
+
import { CancelledError, askText, 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';
|
|
40
|
+
import { collectSystemInfo, describeSystem } from '../lib/system-info.mjs';
|
|
39
41
|
|
|
40
|
-
|
|
42
|
+
// The command's entry point (it checks the Node version, then loads this file).
|
|
43
|
+
const ENTRY = fileURLToPath(new URL('./gitcode-agent-runner.cjs', import.meta.url));
|
|
41
44
|
const VERSION = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
|
|
42
45
|
const TOKEN_PATTERN = /^gcm_[A-Za-z0-9_-]{43}$/;
|
|
46
|
+
const NAME_MAX_CHARS = 40; // the website's limit (normalizeMachineName)
|
|
43
47
|
const DOCTOR_INTERVAL_MS = 60 * 60_000;
|
|
44
48
|
const ATTENTION = EXIT_NEEDS_ATTENTION;
|
|
45
49
|
|
|
@@ -56,7 +60,7 @@ const USAGE = `GitCode Agent 执行机器 ${VERSION}
|
|
|
56
60
|
|
|
57
61
|
命令:
|
|
58
62
|
start 连接网站并等待任务(默认)
|
|
59
|
-
login [--new-id] [--token-stdin]
|
|
63
|
+
login [--new-id] [--token-stdin] [--name <名称>]
|
|
60
64
|
输入接入令牌(校验通过才保存);--new-id 重新生成机器标识
|
|
61
65
|
logout 清除本机保存的令牌(机器标识保留)
|
|
62
66
|
setup [--yes] 检查并安装缺少的依赖(需在终端里运行)
|
|
@@ -69,6 +73,7 @@ const USAGE = `GitCode Agent 执行机器 ${VERSION}
|
|
|
69
73
|
选项:
|
|
70
74
|
--server <url> 网站地址(默认 ${DEFAULT_SERVER},会保存)
|
|
71
75
|
--work-dir <dir> 工作目录(不能在主目录之内,会保存)
|
|
76
|
+
--name <名称> 这台机器登记时用的名称(默认主机名,会保存;登记后在网页上修改)
|
|
72
77
|
--allow-root 允许以 root 运行(仅限容器等确有需要的场合)`;
|
|
73
78
|
|
|
74
79
|
class ExitError extends Error {
|
|
@@ -81,16 +86,10 @@ class ExitError extends Error {
|
|
|
81
86
|
const say = (text = '') => process.stdout.write(`${text}\n`);
|
|
82
87
|
const log = createLogger();
|
|
83
88
|
|
|
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
89
|
function checkSystem() {
|
|
92
90
|
if (!['linux', 'darwin'].includes(process.platform)) throw new ExitError(ATTENTION, '暂不支持此系统(只支持 Linux 和 macOS)');
|
|
93
|
-
|
|
91
|
+
// gitcode-agent-runner.cjs already switched to a supported Node when it could.
|
|
92
|
+
if (!nodeSupported(process.versions.node)) throw new ExitError(ATTENTION, `需要 Node ${NODE_REQUIREMENT}(当前 ${process.versions.node})`);
|
|
94
93
|
}
|
|
95
94
|
|
|
96
95
|
/**
|
|
@@ -117,7 +116,14 @@ function realHome() {
|
|
|
117
116
|
}
|
|
118
117
|
}
|
|
119
118
|
|
|
120
|
-
/**
|
|
119
|
+
/** A name the website accepts: trimmed, 1–40 characters, no control characters; else ''. */
|
|
120
|
+
function machineName(value) {
|
|
121
|
+
const name = String(value ?? '').trim();
|
|
122
|
+
const length = [...name].length;
|
|
123
|
+
return length >= 1 && length <= NAME_MAX_CHARS && !/\p{Cc}/u.test(name) ? name : '';
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** Config, server, client id and work root; --server / --work-dir / --name are saved. */
|
|
121
127
|
function loadContext(values, { workRoot: needWorkRoot = true } = {}) {
|
|
122
128
|
const paths = configPaths();
|
|
123
129
|
const config = loadConfig(paths);
|
|
@@ -136,6 +142,14 @@ function loadContext(values, { workRoot: needWorkRoot = true } = {}) {
|
|
|
136
142
|
config.server = server;
|
|
137
143
|
changed = true;
|
|
138
144
|
}
|
|
145
|
+
if (values.name !== undefined) {
|
|
146
|
+
const name = machineName(values.name);
|
|
147
|
+
if (!name) throw new ExitError(1, `名称需为 1–${NAME_MAX_CHARS} 个字符,不能包含控制字符`);
|
|
148
|
+
if (name !== config.machineName) {
|
|
149
|
+
config.machineName = name;
|
|
150
|
+
changed = true;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
139
153
|
if (values['work-dir']) {
|
|
140
154
|
const dir = path.resolve(values['work-dir']);
|
|
141
155
|
if (dir !== config.workRoot) {
|
|
@@ -156,8 +170,49 @@ function clientFor(ctx, token = ctx.config.token) {
|
|
|
156
170
|
return createClient({ server: ctx.server, token, clientId: ctx.config.clientId, version: VERSION });
|
|
157
171
|
}
|
|
158
172
|
|
|
159
|
-
|
|
160
|
-
|
|
173
|
+
/** POST /connect. `name` only names a machine the website does not know yet. */
|
|
174
|
+
function connect(ctx, client, capabilities) {
|
|
175
|
+
return client.request('POST', '/connect', {
|
|
176
|
+
hostname: os.hostname(),
|
|
177
|
+
name: ctx.config.machineName || '',
|
|
178
|
+
version: VERSION,
|
|
179
|
+
capabilities,
|
|
180
|
+
system: systemInfo(ctx),
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function systemInfo(ctx) {
|
|
185
|
+
return collectSystemInfo({ workRoot: ctx.workRoot || ctx.config.workRoot || defaultWorkRoot() });
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** After /connect: what the machine is called there, and whether its owner confirmed it. */
|
|
189
|
+
function sayRegistered(ctx, reply) {
|
|
190
|
+
say(`✓ 已连接 ${ctx.server},本机登记为「${reply.name}」(令牌:${reply.tokenName})`);
|
|
191
|
+
if (!reply.created && ctx.config.machineName && reply.name !== ctx.config.machineName) {
|
|
192
|
+
say(` 这台机器之前已登记为「${reply.name}」,名称请在网页上修改`);
|
|
193
|
+
}
|
|
194
|
+
if (reply.confirmed === false) {
|
|
195
|
+
say('⚠ 这台机器还没有确认,确认后才会收到任务:请在网页「在线 Agent → 模型配置 → 执行机器」里核对主机名和 IP 后点「确认」');
|
|
196
|
+
say(` ${ctx.server}/features#agent/config`);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** First login in a terminal: the name this machine registers with (Enter = hostname). */
|
|
201
|
+
async function askMachineName(ctx) {
|
|
202
|
+
const hostname = os.hostname();
|
|
203
|
+
for (;;) {
|
|
204
|
+
const answer = await askText(`给这台机器起个名字(回车使用主机名 ${hostname}):`);
|
|
205
|
+
if (!answer) {
|
|
206
|
+
ctx.config.machineName = machineName(hostname) || '';
|
|
207
|
+
return;
|
|
208
|
+
}
|
|
209
|
+
const name = machineName(answer);
|
|
210
|
+
if (name) {
|
|
211
|
+
ctx.config.machineName = name;
|
|
212
|
+
return;
|
|
213
|
+
}
|
|
214
|
+
say(`名称需为 1–${NAME_MAX_CHARS} 个字符,不能包含控制字符`);
|
|
215
|
+
}
|
|
161
216
|
}
|
|
162
217
|
|
|
163
218
|
function networkReason(error) {
|
|
@@ -197,12 +252,13 @@ async function obtainToken(ctx, { fromStdin = false, capabilities }) {
|
|
|
197
252
|
say('令牌格式不正确(应为 gcm_ 开头的 47 个字符),请重新粘贴');
|
|
198
253
|
continue;
|
|
199
254
|
}
|
|
255
|
+
if (!fromStdin && !ctx.config.machineName) await askMachineName(ctx);
|
|
200
256
|
const client = clientFor(ctx, token);
|
|
201
257
|
try {
|
|
202
|
-
const reply = await connect(client, capabilities);
|
|
258
|
+
const reply = await connect(ctx, client, capabilities);
|
|
203
259
|
ctx.config.token = token;
|
|
204
260
|
save(ctx);
|
|
205
|
-
|
|
261
|
+
sayRegistered(ctx, reply);
|
|
206
262
|
return { client, reply };
|
|
207
263
|
} catch (error) {
|
|
208
264
|
if (error instanceof ApiError && error.status === 401) {
|
|
@@ -222,7 +278,7 @@ async function connectSaved(ctx, client, capabilities) {
|
|
|
222
278
|
let delay = 1000;
|
|
223
279
|
for (;;) {
|
|
224
280
|
try {
|
|
225
|
-
return await connect(client, capabilities);
|
|
281
|
+
return await connect(ctx, client, capabilities);
|
|
226
282
|
} catch (error) {
|
|
227
283
|
const fatal = fatalFor(error);
|
|
228
284
|
if (fatal) {
|
|
@@ -341,7 +397,7 @@ async function start(values) {
|
|
|
341
397
|
} else {
|
|
342
398
|
client = clientFor(ctx);
|
|
343
399
|
reply = await connectSaved(ctx, client, result.capabilities);
|
|
344
|
-
|
|
400
|
+
sayRegistered(ctx, reply);
|
|
345
401
|
}
|
|
346
402
|
printDoctor(result);
|
|
347
403
|
if (!ctx.config.setupDone && interactive) {
|
|
@@ -413,8 +469,10 @@ async function serve(ctx, client, initial, reply) {
|
|
|
413
469
|
jobs,
|
|
414
470
|
log,
|
|
415
471
|
version: VERSION,
|
|
416
|
-
connect: () => connect(client, capabilities),
|
|
472
|
+
connect: () => connect(ctx, client, capabilities),
|
|
417
473
|
capabilities: { current: () => capabilities },
|
|
474
|
+
system: { current: () => systemInfo(ctx) },
|
|
475
|
+
confirmed: reply.confirmed !== false,
|
|
418
476
|
heartbeatMs: reply.heartbeatMs,
|
|
419
477
|
signal: controller.signal,
|
|
420
478
|
});
|
|
@@ -437,8 +495,10 @@ async function login(values) {
|
|
|
437
495
|
const ctx = loadContext(values);
|
|
438
496
|
if (values['new-id']) {
|
|
439
497
|
ctx.config.clientId = newClientId();
|
|
498
|
+
// A new machine on the website: ask for its name again (unless --name gave one).
|
|
499
|
+
if (values.name === undefined) ctx.config.machineName = '';
|
|
440
500
|
save(ctx);
|
|
441
|
-
say('
|
|
501
|
+
say('已生成新的机器标识:这台机器在网页上会作为新机器出现,需要在网页上确认');
|
|
442
502
|
}
|
|
443
503
|
if (!values['token-stdin'] && !isInteractive()) throw new ExitError(ATTENTION, 'login 需要在终端里运行(脚本里请用 --token-stdin)');
|
|
444
504
|
say('检查依赖和沙箱……');
|
|
@@ -469,7 +529,7 @@ async function setup(values) {
|
|
|
469
529
|
if (ctx.config.token) {
|
|
470
530
|
client = clientFor(ctx);
|
|
471
531
|
try {
|
|
472
|
-
reply = await connect(client, result.capabilities);
|
|
532
|
+
reply = await connect(ctx, client, result.capabilities);
|
|
473
533
|
} catch (error) {
|
|
474
534
|
say(`无法从网站读取要求(${error.message}),按默认要求检查`);
|
|
475
535
|
client = null;
|
|
@@ -488,7 +548,7 @@ async function setup(values) {
|
|
|
488
548
|
if (outcome.ran) {
|
|
489
549
|
say('重新检查……');
|
|
490
550
|
result = await doctorFor(ctx);
|
|
491
|
-
if (client) reply = await connect(client, result.capabilities).catch(() => reply);
|
|
551
|
+
if (client) reply = await connect(ctx, client, result.capabilities).catch(() => reply);
|
|
492
552
|
printDoctor(result);
|
|
493
553
|
}
|
|
494
554
|
printFeatures(reply);
|
|
@@ -506,18 +566,21 @@ async function doctor(values) {
|
|
|
506
566
|
if (ctx.config.token) {
|
|
507
567
|
try {
|
|
508
568
|
// Also brings the website's copy of this machine's capabilities up to date.
|
|
509
|
-
reply = await connect(clientFor(ctx), result.capabilities);
|
|
569
|
+
reply = await connect(ctx, clientFor(ctx), result.capabilities);
|
|
510
570
|
} catch (error) {
|
|
511
571
|
note = error instanceof ApiError && error.status === 401 ? '令牌无效或已删除' : `无法连接网站:${error instanceof ApiError ? error.message : networkReason(error)}`;
|
|
512
572
|
}
|
|
513
573
|
} else note = '还没有接入令牌,无法判断各功能(运行 gitcode-agent-runner login)';
|
|
574
|
+
const system = systemInfo(ctx);
|
|
514
575
|
if (values.json) {
|
|
515
|
-
say(JSON.stringify({ version: VERSION, capabilities: result.capabilities, claudePath: result.claude.path, features: reply?.features || null, note }, null, 2));
|
|
576
|
+
say(JSON.stringify({ version: VERSION, capabilities: result.capabilities, system, claudePath: result.claude.path, features: reply?.features || null, confirmed: reply?.confirmed ?? null, note }, null, 2));
|
|
516
577
|
return 0;
|
|
517
578
|
}
|
|
518
579
|
say(`GitCode Agent 执行机器 ${VERSION} · Node ${process.versions.node} · ${process.platform}/${process.arch}`);
|
|
580
|
+
say(`系统:${describeSystem(system)}`);
|
|
519
581
|
printDoctor(result);
|
|
520
582
|
printFeatures(reply);
|
|
583
|
+
if (reply?.confirmed === false) say('这台机器还没有在网页上确认,确认后才会收到任务(在线 Agent → 模型配置 → 执行机器)');
|
|
521
584
|
if (note) say(note);
|
|
522
585
|
return 0;
|
|
523
586
|
}
|
|
@@ -531,7 +594,9 @@ async function status(values) {
|
|
|
531
594
|
say(`网站:${ctx.server}`);
|
|
532
595
|
say(`令牌:${config.token ? `${config.token.slice(0, 12)}…` : '未登录(运行 gitcode-agent-runner login)'}`);
|
|
533
596
|
say(`机器标识:${config.clientId}`);
|
|
597
|
+
say(`登记名称:${config.machineName || `${os.hostname()}(主机名)`}`);
|
|
534
598
|
say(`工作目录:${config.workRoot || defaultWorkRoot()}`);
|
|
599
|
+
say(`系统:${describeSystem(systemInfo(ctx))}`);
|
|
535
600
|
say(`配置文件:${ctx.paths.configFile}`);
|
|
536
601
|
const service = serviceStatus();
|
|
537
602
|
say(`后台服务:${service.installed ? service.state : '未安装'}${service.installed ? `(${service.logHint})` : ''}`);
|
|
@@ -553,7 +618,7 @@ async function status(values) {
|
|
|
553
618
|
404: '正常',
|
|
554
619
|
401: '令牌无效或已删除(运行 gitcode-agent-runner login)',
|
|
555
620
|
403: '这台机器已被封禁',
|
|
556
|
-
409: '令牌有效,这台机器尚未登记(运行 gitcode-agent-runner
|
|
621
|
+
409: '令牌有效,这台机器尚未登记(运行 gitcode-agent-runner 会自动登记,之后在网页上确认)',
|
|
557
622
|
}[error.status] || error.message;
|
|
558
623
|
say(`连接测试:${text}`);
|
|
559
624
|
} else say(`连接测试:失败(${networkReason(error)})`);
|
|
@@ -612,6 +677,7 @@ async function main(argv) {
|
|
|
612
677
|
options: {
|
|
613
678
|
server: { type: 'string' },
|
|
614
679
|
'work-dir': { type: 'string' },
|
|
680
|
+
name: { type: 'string' },
|
|
615
681
|
'allow-root': { type: 'boolean' },
|
|
616
682
|
'new-id': { type: 'boolean' },
|
|
617
683
|
'token-stdin': { type: 'boolean' },
|
package/lib/config.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Where the program keeps things, and its config file:
|
|
2
2
|
// config ${XDG_CONFIG_HOME:-~/.config}/gitcode-agent-runner/config.json (dir 0700, file 0600)
|
|
3
|
-
// { server, token, clientId, setupDone, workRoot?, claudePath? }
|
|
3
|
+
// { server, token, clientId, setupDone, workRoot?, claudePath?, machineName? }
|
|
4
4
|
// lock same directory, run.lock
|
|
5
5
|
// cache ${XDG_CACHE_HOME:-~/.cache}/gitcode-agent-runner/skills/
|
|
6
6
|
// work /var/tmp/gitcode-agent-runner-<uid>/ (Linux) or <tmpdir>/gitcode-agent-runner/
|
|
@@ -47,6 +47,8 @@ function normalize(raw) {
|
|
|
47
47
|
};
|
|
48
48
|
if (typeof raw.workRoot === 'string' && raw.workRoot) config.workRoot = raw.workRoot;
|
|
49
49
|
if (typeof raw.claudePath === 'string' && raw.claudePath) config.claudePath = raw.claudePath;
|
|
50
|
+
// The name sent with /connect: it names this machine when the website registers it.
|
|
51
|
+
if (typeof raw.machineName === 'string' && raw.machineName) config.machineName = raw.machineName.slice(0, 100);
|
|
50
52
|
return config;
|
|
51
53
|
}
|
|
52
54
|
|
package/lib/connection.mjs
CHANGED
|
@@ -68,12 +68,33 @@ function jitter(ms) {
|
|
|
68
68
|
* jobs JobManager (handle / cancel / runningIds)
|
|
69
69
|
* connect() POST /connect again (after 409 machine_unknown); returns its reply
|
|
70
70
|
* capabilities { current(): object } — sent when changed and after every hello
|
|
71
|
+
* system { current(): object } — system details, sent with every heartbeat (optional)
|
|
72
|
+
* confirmed whether the owner has confirmed this machine (from the connect reply);
|
|
73
|
+
* the program says so once when that changes
|
|
71
74
|
* heartbeatMs from the connect reply
|
|
72
75
|
*/
|
|
73
|
-
export async function runConnection({
|
|
76
|
+
export async function runConnection({
|
|
77
|
+
client,
|
|
78
|
+
jobs,
|
|
79
|
+
log,
|
|
80
|
+
version,
|
|
81
|
+
connect,
|
|
82
|
+
capabilities,
|
|
83
|
+
system,
|
|
84
|
+
confirmed = true,
|
|
85
|
+
heartbeatMs = 20_000,
|
|
86
|
+
signal,
|
|
87
|
+
}) {
|
|
74
88
|
const stopper = new AbortController();
|
|
75
89
|
const stop = AbortSignal.any([signal || new AbortController().signal, stopper.signal]);
|
|
76
|
-
const state = { result: null, heartbeatMs, replaced: [], sentCapabilities: '', warnedOutdated: false, toldLatest: '' };
|
|
90
|
+
const state = { result: null, heartbeatMs, replaced: [], sentCapabilities: '', warnedOutdated: false, toldLatest: '', confirmed };
|
|
91
|
+
|
|
92
|
+
const noteConfirmed = (value, name = '') => {
|
|
93
|
+
if (typeof value !== 'boolean' || value === state.confirmed) return;
|
|
94
|
+
state.confirmed = value;
|
|
95
|
+
if (value) log.info(`✓ 网页上已确认这台机器${name ? `「${name}」` : ''},可以接收任务了`);
|
|
96
|
+
else log.warn('这台机器需要在网页上(重新)确认后才会收到任务:在线 Agent → 模型配置 → 执行机器');
|
|
97
|
+
};
|
|
77
98
|
|
|
78
99
|
const end = (result) => {
|
|
79
100
|
if (state.result) return;
|
|
@@ -93,6 +114,7 @@ export async function runConnection({ client, jobs, log, version, connect, capab
|
|
|
93
114
|
const reply = await connect();
|
|
94
115
|
if (reply?.heartbeatMs) state.heartbeatMs = reply.heartbeatMs;
|
|
95
116
|
state.sentCapabilities = '';
|
|
117
|
+
noteConfirmed(reply?.confirmed, reply?.name);
|
|
96
118
|
} catch (failure) {
|
|
97
119
|
const again = fatalFor(failure);
|
|
98
120
|
if (again) end(again);
|
|
@@ -107,10 +129,14 @@ export async function runConnection({ client, jobs, log, version, connect, capab
|
|
|
107
129
|
if (Number.isInteger(event.heartbeatMs) && event.heartbeatMs >= 1000) state.heartbeatMs = event.heartbeatMs;
|
|
108
130
|
// The website may have restarted: report capabilities again with the next heartbeat.
|
|
109
131
|
state.sentCapabilities = '';
|
|
132
|
+
noteConfirmed(event.confirmed);
|
|
110
133
|
break;
|
|
111
134
|
case 'job':
|
|
112
135
|
jobs.handle(event.job);
|
|
113
136
|
break;
|
|
137
|
+
case 'confirmed':
|
|
138
|
+
noteConfirmed(true, typeof event.name === 'string' ? event.name.slice(0, 40) : '');
|
|
139
|
+
break;
|
|
114
140
|
case 'cancel':
|
|
115
141
|
if (typeof event.runId === 'string') jobs.cancel(event.runId);
|
|
116
142
|
break;
|
|
@@ -137,10 +163,18 @@ export async function runConnection({ client, jobs, log, version, connect, capab
|
|
|
137
163
|
const body = { version, running: jobs.runningIds().slice(0, 200) };
|
|
138
164
|
const current = JSON.stringify(capabilities.current());
|
|
139
165
|
if (current !== state.sentCapabilities) body.capabilities = capabilities.current();
|
|
166
|
+
if (system) {
|
|
167
|
+
try {
|
|
168
|
+
body.system = system.current();
|
|
169
|
+
} catch (error) {
|
|
170
|
+
log.warn(`读取系统信息失败:${error.message}`);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
140
173
|
try {
|
|
141
174
|
const reply = await client.request('POST', '/heartbeat', body, { signal: stop });
|
|
142
175
|
if (body.capabilities) state.sentCapabilities = current;
|
|
143
176
|
for (const runId of Array.isArray(reply?.cancel) ? reply.cancel : []) jobs.cancel(runId);
|
|
177
|
+
noteConfirmed(reply?.confirmed);
|
|
144
178
|
if (reply?.outdated && !state.warnedOutdated) {
|
|
145
179
|
state.warnedOutdated = true;
|
|
146
180
|
log.warn(`程序版本 ${version} 已低于网站要求的 ${reply.minVersion},请运行 ${UPDATE_COMMAND} 后重启`);
|
|
@@ -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/lib/prompt.mjs
CHANGED
|
@@ -51,6 +51,24 @@ export function readHidden(question, { input = process.stdin, output = process.s
|
|
|
51
51
|
});
|
|
52
52
|
}
|
|
53
53
|
|
|
54
|
+
/** One line of visible text, trimmed; Ctrl+C / Ctrl+D reject with CancelledError. */
|
|
55
|
+
export function askText(question, { input = process.stdin, output = process.stdout } = {}) {
|
|
56
|
+
return new Promise((resolve, reject) => {
|
|
57
|
+
const rl = readline.createInterface({ input, output });
|
|
58
|
+
let answered = false;
|
|
59
|
+
rl.on('close', () => {
|
|
60
|
+
if (answered) return;
|
|
61
|
+
output.write('\n');
|
|
62
|
+
reject(new CancelledError());
|
|
63
|
+
});
|
|
64
|
+
rl.question(question, (answer) => {
|
|
65
|
+
answered = true;
|
|
66
|
+
rl.close();
|
|
67
|
+
resolve(String(answer || '').trim());
|
|
68
|
+
});
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
|
|
54
72
|
/** [Y/n] question; an empty answer takes the default. */
|
|
55
73
|
export async function askYesNo(question, { defaultYes = true, input = process.stdin, output = process.stdout } = {}) {
|
|
56
74
|
const rl = readline.createInterface({ input, output });
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
// What the website shows about this machine (模型配置 → 执行机器 → 详情):
|
|
2
|
+
// system, kernel, CPU, memory, the work directory's disk, load, uptime, the
|
|
3
|
+
// account running the program, whether it looks like a container, and
|
|
4
|
+
// whether the program runs on the Node it downloaded. Sent with /connect and
|
|
5
|
+
// every heartbeat; the parts that cannot change while the program runs are
|
|
6
|
+
// read once. Display only: the website decides nothing on these.
|
|
7
|
+
|
|
8
|
+
import { spawnSync } from 'node:child_process';
|
|
9
|
+
import fs from 'node:fs';
|
|
10
|
+
import os from 'node:os';
|
|
11
|
+
|
|
12
|
+
let fixed = null;
|
|
13
|
+
|
|
14
|
+
function readText(file, max = 64 * 1024) {
|
|
15
|
+
try {
|
|
16
|
+
return fs.readFileSync(file, 'utf8').slice(0, max);
|
|
17
|
+
} catch {
|
|
18
|
+
return '';
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function output(command, args) {
|
|
23
|
+
const result = spawnSync(command, args, {
|
|
24
|
+
encoding: 'utf8',
|
|
25
|
+
timeout: 5000,
|
|
26
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
27
|
+
env: { ...process.env, LC_ALL: 'C' },
|
|
28
|
+
});
|
|
29
|
+
return result.status === 0 ? String(result.stdout || '') : '';
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** "Ubuntu 24.04.1 LTS", "macOS 15.1"… */
|
|
33
|
+
export function osName(platform = process.platform, { osRelease } = {}) {
|
|
34
|
+
if (platform === 'darwin') {
|
|
35
|
+
const name = output('sw_vers', ['-productName']).trim() || 'macOS';
|
|
36
|
+
return `${name} ${output('sw_vers', ['-productVersion']).trim()}`.trim();
|
|
37
|
+
}
|
|
38
|
+
if (platform !== 'linux') return platform;
|
|
39
|
+
const text = osRelease ?? (readText('/etc/os-release') || readText('/usr/lib/os-release'));
|
|
40
|
+
const value = (key) => {
|
|
41
|
+
const match = new RegExp(`^${key}=(.*)$`, 'm').exec(text);
|
|
42
|
+
return match ? match[1].trim().replace(/^(["'])(.*)\1$/, '$2') : '';
|
|
43
|
+
};
|
|
44
|
+
return value('PRETTY_NAME') || [value('NAME'), value('VERSION')].filter(Boolean).join(' ') || 'Linux';
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function cpuModel(platform) {
|
|
48
|
+
const model = String(os.cpus()[0]?.model || '').trim();
|
|
49
|
+
if (model && model.toLowerCase() !== 'unknown') return model;
|
|
50
|
+
// ARM Linux: /proc/cpuinfo has no model name, lscpu knows it (e.g. Kunpeng-920).
|
|
51
|
+
if (platform === 'linux') return /^Model name:\s*(.+)$/m.exec(output('lscpu', []))?.[1].trim() || '';
|
|
52
|
+
return '';
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** A guess: Docker / Podman / Kubernetes markers, or an overlay root filesystem. */
|
|
56
|
+
export function looksLikeContainer({
|
|
57
|
+
platform = process.platform,
|
|
58
|
+
env = process.env,
|
|
59
|
+
exists = fs.existsSync,
|
|
60
|
+
read = readText,
|
|
61
|
+
} = {}) {
|
|
62
|
+
if (platform !== 'linux') return false;
|
|
63
|
+
if (exists('/.dockerenv') || exists('/run/.containerenv')) return true;
|
|
64
|
+
if (env.KUBERNETES_SERVICE_HOST || env.container) return true;
|
|
65
|
+
if (/\b(docker|kubepods|containerd|libpod|lxc)\b/.test(read('/proc/1/cgroup'))) return true;
|
|
66
|
+
return /^\d+ \d+ \d+:\d+ \S+ \/ [^\n]* - overlay /m.test(read('/proc/self/mountinfo', 256 * 1024));
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function fixedPart(platform) {
|
|
70
|
+
if (!fixed) {
|
|
71
|
+
let user = '';
|
|
72
|
+
try {
|
|
73
|
+
user = os.userInfo().username;
|
|
74
|
+
} catch {
|
|
75
|
+
// No passwd entry (some containers).
|
|
76
|
+
}
|
|
77
|
+
fixed = { osName: osName(platform), cpuModel: cpuModel(platform), user, container: looksLikeContainer({ platform }) };
|
|
78
|
+
}
|
|
79
|
+
return fixed;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function disk(dir) {
|
|
83
|
+
try {
|
|
84
|
+
const stat = fs.statfsSync(dir);
|
|
85
|
+
return { diskTotal: stat.blocks * stat.bsize, diskAvailable: stat.bavail * stat.bsize };
|
|
86
|
+
} catch {
|
|
87
|
+
return { diskTotal: 0, diskAvailable: 0 };
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** The report (sizes in bytes, uptime in seconds); `workRoot` is the directory whose disk counts. */
|
|
92
|
+
export function collectSystemInfo({ workRoot = '', platform = process.platform, env = process.env } = {}) {
|
|
93
|
+
const base = fixedPart(platform);
|
|
94
|
+
const memTotal = os.totalmem();
|
|
95
|
+
// A container's limit, when there is one (unlimited reads as 0 or a huge number).
|
|
96
|
+
const constrained = Number(process.constrainedMemory?.() || 0);
|
|
97
|
+
const available = Number(process.availableMemory?.() ?? os.freemem());
|
|
98
|
+
return {
|
|
99
|
+
osName: base.osName,
|
|
100
|
+
kernel: os.release(),
|
|
101
|
+
cpuModel: base.cpuModel,
|
|
102
|
+
cpuCount: os.availableParallelism?.() || os.cpus().length || 1,
|
|
103
|
+
memTotal,
|
|
104
|
+
memAvailable: Math.max(0, Math.min(available, memTotal)),
|
|
105
|
+
memLimit: constrained > 0 && constrained < memTotal ? constrained : 0,
|
|
106
|
+
diskPath: workRoot,
|
|
107
|
+
...(workRoot ? disk(workRoot) : { diskTotal: 0, diskAvailable: 0 }),
|
|
108
|
+
uptime: Math.round(os.uptime()),
|
|
109
|
+
loadAvg: os.loadavg().map((value) => Math.round(value * 100) / 100),
|
|
110
|
+
user: base.user,
|
|
111
|
+
container: base.container,
|
|
112
|
+
nodeManaged: Boolean(env.GC_RUNNER_NODE_SWITCHED),
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
const GB = 1024 ** 3;
|
|
117
|
+
|
|
118
|
+
function size(bytes) {
|
|
119
|
+
return `${(bytes / GB).toFixed(bytes >= 100 * GB ? 0 : 1).replace(/\.0$/, '')} GB`;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** One line for doctor / status: "Ubuntu 24.04 · arm64 · 8 核 · 内存 16 GB · 工作目录可用 120 GB". */
|
|
123
|
+
export function describeSystem(info, arch = process.arch) {
|
|
124
|
+
const memory = info.memLimit || info.memTotal;
|
|
125
|
+
return [
|
|
126
|
+
`${info.osName}${info.container ? '(容器)' : ''}`,
|
|
127
|
+
arch,
|
|
128
|
+
info.cpuCount ? `${info.cpuCount} 核` : '',
|
|
129
|
+
memory ? `内存 ${size(memory)}${info.memLimit ? '(容器限制)' : ''}` : '',
|
|
130
|
+
info.diskTotal ? `工作目录可用 ${size(info.diskAvailable)} / ${size(info.diskTotal)}` : '',
|
|
131
|
+
].filter(Boolean).join(' · ');
|
|
132
|
+
}
|
package/package.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@online-tools/agent-runner",
|
|
3
|
-
"version": "0.0.1-alpha-
|
|
3
|
+
"version": "0.0.1-alpha-3",
|
|
4
4
|
"description": "GitCode 在线工具的 Agent 执行机器:在自己的机器上运行 PR 描述、代码检视任务",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
7
|
-
"bin": { "gitcode-agent-runner": "bin/gitcode-agent-runner.
|
|
7
|
+
"bin": { "gitcode-agent-runner": "bin/gitcode-agent-runner.cjs" },
|
|
8
8
|
"files": ["bin/", "lib/", "README.md", "LICENSE"],
|
|
9
|
-
"engines": { "node": ">=
|
|
9
|
+
"engines": { "node": ">=10.12.0" },
|
|
10
10
|
"os": ["linux", "darwin"],
|
|
11
11
|
"publishConfig": { "access": "public" }
|
|
12
12
|
}
|