@online-tools/agent-runner 0.0.1-alpha-2 → 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 +13 -5
- package/bin/main.mjs +86 -16
- package/lib/config.mjs +3 -1
- package/lib/connection.mjs +36 -2
- package/lib/prompt.mjs +18 -0
- package/lib/system-info.mjs +132 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -10,12 +10,16 @@ GitCode 在线工具的 Agent 执行机器:把「在线 Agent」里的 **PR
|
|
|
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,15 +35,15 @@ 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
|
|
|
@@ -48,6 +52,10 @@ gitcode-agent-runner service install # 可选:注册为后台服务,开
|
|
|
48
52
|
- 自动下载的 Node(只有系统 Node 过旧时才有):`${XDG_DATA_HOME:-~/.local/share}/gitcode-agent-runner/node/`
|
|
49
53
|
- 工作目录:Linux `/var/tmp/gitcode-agent-runner-<uid>/`,macOS `$TMPDIR/gitcode-agent-runner/`。**不能在主目录之内**(沙箱不允许读取主目录)
|
|
50
54
|
|
|
55
|
+
## 上报给网站的信息
|
|
56
|
+
|
|
57
|
+
除了程序版本和各项依赖是否可用,程序还会在连接和每次心跳(约 20 秒)时上报这台机器的概况,显示在网页「执行机器」的「资源」和「详情」里(只有你和网站管理员看得到):系统和内核、CPU 型号和核数、内存总量和可用量(容器有内存限制时同时显示限制)、工作目录所在磁盘的总量和可用量、负载、系统运行时间、运行程序的账号、是否在容器内、是否在用程序自动下载的 Node。不上报文件内容、环境变量或进程列表。
|
|
58
|
+
|
|
51
59
|
## 任务怎么运行
|
|
52
60
|
|
|
53
61
|
网站只下发任务数据:任务文本、模型、你的模型 API Key、GitCode 授权、超时和 Skill 版本。claude 的命令行、环境变量、工具白名单和沙箱设置都由本程序生成,网站改不了。
|
package/bin/main.mjs
CHANGED
|
@@ -33,15 +33,17 @@ import { FEATURE_LABELS, JobManager } from '../lib/jobs.mjs';
|
|
|
33
33
|
import { LockedError, acquireLock, isRunnerAlive } from '../lib/lock.mjs';
|
|
34
34
|
import { NODE_REQUIREMENT, nodeSupported } from '../lib/node-runtime.cjs';
|
|
35
35
|
import { createLogger } from '../lib/log.mjs';
|
|
36
|
-
import { CancelledError, askYesNo, isInteractive, readHidden, readStdin } from '../lib/prompt.mjs';
|
|
36
|
+
import { CancelledError, askText, askYesNo, isInteractive, readHidden, readStdin } from '../lib/prompt.mjs';
|
|
37
37
|
import { EXIT_NEEDS_ATTENTION, installService, serviceExitCode, serviceStatus, uninstallService } from '../lib/service.mjs';
|
|
38
38
|
import { DEFAULT_REQUIRED_TOOLS, npmPrefixWritable, planSetup, runSetup } from '../lib/setup.mjs';
|
|
39
39
|
import { SkillCache } from '../lib/skills.mjs';
|
|
40
|
+
import { collectSystemInfo, describeSystem } from '../lib/system-info.mjs';
|
|
40
41
|
|
|
41
42
|
// The command's entry point (it checks the Node version, then loads this file).
|
|
42
43
|
const ENTRY = fileURLToPath(new URL('./gitcode-agent-runner.cjs', import.meta.url));
|
|
43
44
|
const VERSION = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
|
|
44
45
|
const TOKEN_PATTERN = /^gcm_[A-Za-z0-9_-]{43}$/;
|
|
46
|
+
const NAME_MAX_CHARS = 40; // the website's limit (normalizeMachineName)
|
|
45
47
|
const DOCTOR_INTERVAL_MS = 60 * 60_000;
|
|
46
48
|
const ATTENTION = EXIT_NEEDS_ATTENTION;
|
|
47
49
|
|
|
@@ -58,7 +60,7 @@ const USAGE = `GitCode Agent 执行机器 ${VERSION}
|
|
|
58
60
|
|
|
59
61
|
命令:
|
|
60
62
|
start 连接网站并等待任务(默认)
|
|
61
|
-
login [--new-id] [--token-stdin]
|
|
63
|
+
login [--new-id] [--token-stdin] [--name <名称>]
|
|
62
64
|
输入接入令牌(校验通过才保存);--new-id 重新生成机器标识
|
|
63
65
|
logout 清除本机保存的令牌(机器标识保留)
|
|
64
66
|
setup [--yes] 检查并安装缺少的依赖(需在终端里运行)
|
|
@@ -71,6 +73,7 @@ const USAGE = `GitCode Agent 执行机器 ${VERSION}
|
|
|
71
73
|
选项:
|
|
72
74
|
--server <url> 网站地址(默认 ${DEFAULT_SERVER},会保存)
|
|
73
75
|
--work-dir <dir> 工作目录(不能在主目录之内,会保存)
|
|
76
|
+
--name <名称> 这台机器登记时用的名称(默认主机名,会保存;登记后在网页上修改)
|
|
74
77
|
--allow-root 允许以 root 运行(仅限容器等确有需要的场合)`;
|
|
75
78
|
|
|
76
79
|
class ExitError extends Error {
|
|
@@ -113,7 +116,14 @@ function realHome() {
|
|
|
113
116
|
}
|
|
114
117
|
}
|
|
115
118
|
|
|
116
|
-
/**
|
|
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. */
|
|
117
127
|
function loadContext(values, { workRoot: needWorkRoot = true } = {}) {
|
|
118
128
|
const paths = configPaths();
|
|
119
129
|
const config = loadConfig(paths);
|
|
@@ -132,6 +142,14 @@ function loadContext(values, { workRoot: needWorkRoot = true } = {}) {
|
|
|
132
142
|
config.server = server;
|
|
133
143
|
changed = true;
|
|
134
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
|
+
}
|
|
135
153
|
if (values['work-dir']) {
|
|
136
154
|
const dir = path.resolve(values['work-dir']);
|
|
137
155
|
if (dir !== config.workRoot) {
|
|
@@ -152,8 +170,49 @@ function clientFor(ctx, token = ctx.config.token) {
|
|
|
152
170
|
return createClient({ server: ctx.server, token, clientId: ctx.config.clientId, version: VERSION });
|
|
153
171
|
}
|
|
154
172
|
|
|
155
|
-
|
|
156
|
-
|
|
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
|
+
}
|
|
157
216
|
}
|
|
158
217
|
|
|
159
218
|
function networkReason(error) {
|
|
@@ -193,12 +252,13 @@ async function obtainToken(ctx, { fromStdin = false, capabilities }) {
|
|
|
193
252
|
say('令牌格式不正确(应为 gcm_ 开头的 47 个字符),请重新粘贴');
|
|
194
253
|
continue;
|
|
195
254
|
}
|
|
255
|
+
if (!fromStdin && !ctx.config.machineName) await askMachineName(ctx);
|
|
196
256
|
const client = clientFor(ctx, token);
|
|
197
257
|
try {
|
|
198
|
-
const reply = await connect(client, capabilities);
|
|
258
|
+
const reply = await connect(ctx, client, capabilities);
|
|
199
259
|
ctx.config.token = token;
|
|
200
260
|
save(ctx);
|
|
201
|
-
|
|
261
|
+
sayRegistered(ctx, reply);
|
|
202
262
|
return { client, reply };
|
|
203
263
|
} catch (error) {
|
|
204
264
|
if (error instanceof ApiError && error.status === 401) {
|
|
@@ -218,7 +278,7 @@ async function connectSaved(ctx, client, capabilities) {
|
|
|
218
278
|
let delay = 1000;
|
|
219
279
|
for (;;) {
|
|
220
280
|
try {
|
|
221
|
-
return await connect(client, capabilities);
|
|
281
|
+
return await connect(ctx, client, capabilities);
|
|
222
282
|
} catch (error) {
|
|
223
283
|
const fatal = fatalFor(error);
|
|
224
284
|
if (fatal) {
|
|
@@ -337,7 +397,7 @@ async function start(values) {
|
|
|
337
397
|
} else {
|
|
338
398
|
client = clientFor(ctx);
|
|
339
399
|
reply = await connectSaved(ctx, client, result.capabilities);
|
|
340
|
-
|
|
400
|
+
sayRegistered(ctx, reply);
|
|
341
401
|
}
|
|
342
402
|
printDoctor(result);
|
|
343
403
|
if (!ctx.config.setupDone && interactive) {
|
|
@@ -409,8 +469,10 @@ async function serve(ctx, client, initial, reply) {
|
|
|
409
469
|
jobs,
|
|
410
470
|
log,
|
|
411
471
|
version: VERSION,
|
|
412
|
-
connect: () => connect(client, capabilities),
|
|
472
|
+
connect: () => connect(ctx, client, capabilities),
|
|
413
473
|
capabilities: { current: () => capabilities },
|
|
474
|
+
system: { current: () => systemInfo(ctx) },
|
|
475
|
+
confirmed: reply.confirmed !== false,
|
|
414
476
|
heartbeatMs: reply.heartbeatMs,
|
|
415
477
|
signal: controller.signal,
|
|
416
478
|
});
|
|
@@ -433,8 +495,10 @@ async function login(values) {
|
|
|
433
495
|
const ctx = loadContext(values);
|
|
434
496
|
if (values['new-id']) {
|
|
435
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 = '';
|
|
436
500
|
save(ctx);
|
|
437
|
-
say('
|
|
501
|
+
say('已生成新的机器标识:这台机器在网页上会作为新机器出现,需要在网页上确认');
|
|
438
502
|
}
|
|
439
503
|
if (!values['token-stdin'] && !isInteractive()) throw new ExitError(ATTENTION, 'login 需要在终端里运行(脚本里请用 --token-stdin)');
|
|
440
504
|
say('检查依赖和沙箱……');
|
|
@@ -465,7 +529,7 @@ async function setup(values) {
|
|
|
465
529
|
if (ctx.config.token) {
|
|
466
530
|
client = clientFor(ctx);
|
|
467
531
|
try {
|
|
468
|
-
reply = await connect(client, result.capabilities);
|
|
532
|
+
reply = await connect(ctx, client, result.capabilities);
|
|
469
533
|
} catch (error) {
|
|
470
534
|
say(`无法从网站读取要求(${error.message}),按默认要求检查`);
|
|
471
535
|
client = null;
|
|
@@ -484,7 +548,7 @@ async function setup(values) {
|
|
|
484
548
|
if (outcome.ran) {
|
|
485
549
|
say('重新检查……');
|
|
486
550
|
result = await doctorFor(ctx);
|
|
487
|
-
if (client) reply = await connect(client, result.capabilities).catch(() => reply);
|
|
551
|
+
if (client) reply = await connect(ctx, client, result.capabilities).catch(() => reply);
|
|
488
552
|
printDoctor(result);
|
|
489
553
|
}
|
|
490
554
|
printFeatures(reply);
|
|
@@ -502,18 +566,21 @@ async function doctor(values) {
|
|
|
502
566
|
if (ctx.config.token) {
|
|
503
567
|
try {
|
|
504
568
|
// Also brings the website's copy of this machine's capabilities up to date.
|
|
505
|
-
reply = await connect(clientFor(ctx), result.capabilities);
|
|
569
|
+
reply = await connect(ctx, clientFor(ctx), result.capabilities);
|
|
506
570
|
} catch (error) {
|
|
507
571
|
note = error instanceof ApiError && error.status === 401 ? '令牌无效或已删除' : `无法连接网站:${error instanceof ApiError ? error.message : networkReason(error)}`;
|
|
508
572
|
}
|
|
509
573
|
} else note = '还没有接入令牌,无法判断各功能(运行 gitcode-agent-runner login)';
|
|
574
|
+
const system = systemInfo(ctx);
|
|
510
575
|
if (values.json) {
|
|
511
|
-
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));
|
|
512
577
|
return 0;
|
|
513
578
|
}
|
|
514
579
|
say(`GitCode Agent 执行机器 ${VERSION} · Node ${process.versions.node} · ${process.platform}/${process.arch}`);
|
|
580
|
+
say(`系统:${describeSystem(system)}`);
|
|
515
581
|
printDoctor(result);
|
|
516
582
|
printFeatures(reply);
|
|
583
|
+
if (reply?.confirmed === false) say('这台机器还没有在网页上确认,确认后才会收到任务(在线 Agent → 模型配置 → 执行机器)');
|
|
517
584
|
if (note) say(note);
|
|
518
585
|
return 0;
|
|
519
586
|
}
|
|
@@ -527,7 +594,9 @@ async function status(values) {
|
|
|
527
594
|
say(`网站:${ctx.server}`);
|
|
528
595
|
say(`令牌:${config.token ? `${config.token.slice(0, 12)}…` : '未登录(运行 gitcode-agent-runner login)'}`);
|
|
529
596
|
say(`机器标识:${config.clientId}`);
|
|
597
|
+
say(`登记名称:${config.machineName || `${os.hostname()}(主机名)`}`);
|
|
530
598
|
say(`工作目录:${config.workRoot || defaultWorkRoot()}`);
|
|
599
|
+
say(`系统:${describeSystem(systemInfo(ctx))}`);
|
|
531
600
|
say(`配置文件:${ctx.paths.configFile}`);
|
|
532
601
|
const service = serviceStatus();
|
|
533
602
|
say(`后台服务:${service.installed ? service.state : '未安装'}${service.installed ? `(${service.logHint})` : ''}`);
|
|
@@ -549,7 +618,7 @@ async function status(values) {
|
|
|
549
618
|
404: '正常',
|
|
550
619
|
401: '令牌无效或已删除(运行 gitcode-agent-runner login)',
|
|
551
620
|
403: '这台机器已被封禁',
|
|
552
|
-
409: '令牌有效,这台机器尚未登记(运行 gitcode-agent-runner
|
|
621
|
+
409: '令牌有效,这台机器尚未登记(运行 gitcode-agent-runner 会自动登记,之后在网页上确认)',
|
|
553
622
|
}[error.status] || error.message;
|
|
554
623
|
say(`连接测试:${text}`);
|
|
555
624
|
} else say(`连接测试:失败(${networkReason(error)})`);
|
|
@@ -608,6 +677,7 @@ async function main(argv) {
|
|
|
608
677
|
options: {
|
|
609
678
|
server: { type: 'string' },
|
|
610
679
|
'work-dir': { type: 'string' },
|
|
680
|
+
name: { type: 'string' },
|
|
611
681
|
'allow-root': { type: 'boolean' },
|
|
612
682
|
'new-id': { type: 'boolean' },
|
|
613
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} 后重启`);
|
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
|
+
}
|