@online-tools/work-agent-runner 0.0.0-stage → 0.0.1-alpha-5

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.
@@ -0,0 +1,139 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+ // work-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/work-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('在终端里运行 work-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
+ }
@@ -0,0 +1,85 @@
1
+ // Claude Code command line and environment, shared by the website
2
+ // (lib/agent-runners.js re-exports these for server runs) and the execution
3
+ // machine program (lib/jobs.mjs, lib/doctor.mjs). One copy only: the machine
4
+ // builds the exact command line the server uses, plus its sandbox settings.
5
+ //
6
+ // Only node: built-ins and files in this directory may be imported here, and
7
+ // importing must have no side effects.
8
+
9
+ export const CLAUDE_TOOLS = 'Bash,Read,Glob,Grep,Edit,Write,Skill,Agent';
10
+
11
+ const DEFAULT_PATH = '/usr/local/bin:/usr/bin:/bin';
12
+
13
+ /**
14
+ * `interactive` (交互执行): the task and our answers go over stdin as stream-json,
15
+ * and permission prompts come to us (`--permission-prompt-tool stdio`, see
16
+ * lib/agent-interaction.js). AskUserQuestion is offered but deliberately not
17
+ * pre-allowed, so each call becomes a prompt we forward to the user.
18
+ *
19
+ * `settingsFile` (execution machines): appended as `--settings <file>`, which
20
+ * carries the sandbox settings; without it the arguments are exactly the
21
+ * server's.
22
+ */
23
+ export function claudeArgs({ addDirs = [], interactive = false, settingsFile = '' } = {}) {
24
+ const args = [
25
+ '-p',
26
+ '--output-format',
27
+ 'stream-json',
28
+ '--verbose',
29
+ ...(interactive
30
+ ? ['--input-format', 'stream-json', '--permission-prompt-tool', 'stdio']
31
+ : []),
32
+ // The service runs as root, where bypassPermissions is refused; an explicit
33
+ // allowlist plus acceptEdits runs unattended (anything else is auto-denied).
34
+ '--permission-mode',
35
+ 'acceptEdits',
36
+ '--tools',
37
+ interactive ? `${CLAUDE_TOOLS},AskUserQuestion` : CLAUDE_TOOLS,
38
+ '--allowedTools',
39
+ CLAUDE_TOOLS,
40
+ // Only the per-run project (.claude/skills copy); never the host's user settings.
41
+ '--setting-sources',
42
+ 'project',
43
+ '--strict-mcp-config',
44
+ '--no-session-persistence',
45
+ ];
46
+ for (const dir of addDirs) args.push('--add-dir', dir);
47
+ if (settingsFile) args.push('--settings', settingsFile);
48
+ return args;
49
+ }
50
+
51
+ // Claude Code appends /v1/messages itself.
52
+ export function claudeBaseUrl(baseUrl) {
53
+ return String(baseUrl || '').replace(/\/+$/, '').replace(/\/v1$/, '');
54
+ }
55
+
56
+ /**
57
+ * Environment of one claude process: run-local homes, the user's key and
58
+ * model, nothing else from the caller's environment except `path`. `extra`
59
+ * comes last (Skill credentials, run markers, pass-through proxy variables).
60
+ */
61
+ export function claudeEnv({ path, runDir, homeDir, configDir, tmpDir = runDir, baseUrl, apiKey, model, extra = {} }) {
62
+ return {
63
+ PATH: path || DEFAULT_PATH,
64
+ HOME: homeDir,
65
+ CLAUDE_CONFIG_DIR: configDir,
66
+ TMPDIR: tmpDir,
67
+ LANG: 'C.UTF-8',
68
+ ANTHROPIC_BASE_URL: claudeBaseUrl(baseUrl),
69
+ ANTHROPIC_AUTH_TOKEN: apiKey,
70
+ // Every model slot (main, subagents, background helpers) uses the chosen model,
71
+ // so third-party endpoints never receive an unknown Claude model id.
72
+ ANTHROPIC_MODEL: model,
73
+ ANTHROPIC_DEFAULT_OPUS_MODEL: model,
74
+ ANTHROPIC_DEFAULT_SONNET_MODEL: model,
75
+ ANTHROPIC_DEFAULT_HAIKU_MODEL: model,
76
+ ANTHROPIC_SMALL_FAST_MODEL: model,
77
+ CLAUDE_CODE_SUBAGENT_MODEL: model,
78
+ API_TIMEOUT_MS: '600000',
79
+ CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: '1',
80
+ DISABLE_AUTOUPDATER: '1',
81
+ DISABLE_TELEMETRY: '1',
82
+ DISABLE_ERROR_REPORTING: '1',
83
+ ...extra,
84
+ };
85
+ }
package/lib/config.mjs ADDED
@@ -0,0 +1,157 @@
1
+ // Where the program keeps things, and its config file:
2
+ // config ${XDG_CONFIG_HOME:-~/.config}/work-agent-runner/config.json (dir 0700, file 0600)
3
+ // { server, token, clientId, setupDone, workRoot?, claudePath?, machineName? }
4
+ // lock same directory, run.lock
5
+ // cache ${XDG_CACHE_HOME:-~/.cache}/work-agent-runner/skills/
6
+ // work /var/tmp/work-agent-runner-<uid>/ (Linux) or <tmpdir>/work-agent-runner/
7
+ // (macOS): never inside HOME, which the sandbox may not read.
8
+ // Until 0.0.1-alpha-4 the program was npm @online-tools/agent-runner and every
9
+ // name above was gitcode-agent-runner; adoptLegacyConfig() moves that config.
10
+ // Functions only; bin/ decides when to read or write.
11
+
12
+ import crypto from 'node:crypto';
13
+ import fs from 'node:fs';
14
+ import os from 'node:os';
15
+ import path from 'node:path';
16
+
17
+ export const DEFAULT_SERVER = 'https://online-tools.closerouter.site';
18
+
19
+ const UUID_V4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
20
+
21
+ /** The program's name until 0.0.1-alpha-4 (command, directories, service). */
22
+ export const LEGACY_NAME = 'gitcode-agent-runner';
23
+
24
+ export class ConfigError extends Error {}
25
+
26
+ export function configPaths(env = process.env, home = os.homedir()) {
27
+ const configRoot = env.XDG_CONFIG_HOME || path.join(home, '.config');
28
+ const cacheRoot = env.XDG_CACHE_HOME || path.join(home, '.cache');
29
+ const configDir = path.join(configRoot, 'work-agent-runner');
30
+ const cacheDir = path.join(cacheRoot, 'work-agent-runner');
31
+ const legacyConfigDir = path.join(configRoot, LEGACY_NAME);
32
+ return {
33
+ configDir,
34
+ configFile: path.join(configDir, 'config.json'),
35
+ lockFile: path.join(configDir, 'run.lock'),
36
+ cacheDir,
37
+ skillsDir: path.join(cacheDir, 'skills'),
38
+ legacyConfigDir,
39
+ legacyConfigFile: path.join(legacyConfigDir, 'config.json'),
40
+ legacyLockFile: path.join(legacyConfigDir, 'run.lock'),
41
+ legacyCacheDir: path.join(cacheRoot, LEGACY_NAME),
42
+ };
43
+ }
44
+
45
+ export function newClientId() {
46
+ return crypto.randomUUID();
47
+ }
48
+
49
+ export function isClientId(value) {
50
+ return typeof value === 'string' && UUID_V4.test(value);
51
+ }
52
+
53
+ function normalize(raw) {
54
+ const config = {
55
+ server: typeof raw.server === 'string' ? raw.server : '',
56
+ token: typeof raw.token === 'string' ? raw.token : '',
57
+ clientId: isClientId(raw.clientId) ? raw.clientId : '',
58
+ setupDone: raw.setupDone === true,
59
+ };
60
+ if (typeof raw.workRoot === 'string' && raw.workRoot) config.workRoot = raw.workRoot;
61
+ if (typeof raw.claudePath === 'string' && raw.claudePath) config.claudePath = raw.claudePath;
62
+ // The name sent with /connect: it names this machine when the website registers it.
63
+ if (typeof raw.machineName === 'string' && raw.machineName) config.machineName = raw.machineName.slice(0, 100);
64
+ return config;
65
+ }
66
+
67
+ /** The saved config (defaults when there is none); throws ConfigError when it is unreadable. */
68
+ export function loadConfig(paths) {
69
+ let text;
70
+ try {
71
+ text = fs.readFileSync(paths.configFile, 'utf8');
72
+ } catch (error) {
73
+ if (error.code === 'ENOENT') return normalize({});
74
+ throw new ConfigError(`无法读取配置文件 ${paths.configFile}:${error.message}`);
75
+ }
76
+ let raw;
77
+ try {
78
+ raw = JSON.parse(text);
79
+ } catch {
80
+ throw new ConfigError(`配置文件已损坏:${paths.configFile}(删除后运行 work-agent-runner login)`);
81
+ }
82
+ return normalize(raw && typeof raw === 'object' ? raw : {});
83
+ }
84
+
85
+ /** Writes the config atomically (temporary file, then rename); dir 0700, file 0600. */
86
+ export function saveConfig(paths, config) {
87
+ fs.mkdirSync(paths.configDir, { recursive: true, mode: 0o700 });
88
+ fs.chmodSync(paths.configDir, 0o700);
89
+ const temp = `${paths.configFile}.${process.pid}.${crypto.randomBytes(4).toString('hex')}.tmp`;
90
+ try {
91
+ fs.writeFileSync(temp, `${JSON.stringify(normalize(config), null, 2)}\n`, { mode: 0o600 });
92
+ fs.renameSync(temp, paths.configFile);
93
+ } catch (error) {
94
+ fs.rmSync(temp, { force: true });
95
+ throw error;
96
+ }
97
+ fs.chmodSync(paths.configFile, 0o600);
98
+ }
99
+
100
+ /** True when the old name's config should move here: none here yet, one there. */
101
+ export function legacyConfigPending(paths) {
102
+ return !fs.existsSync(paths.configFile) && fs.existsSync(paths.legacyConfigFile);
103
+ }
104
+
105
+ /**
106
+ * Moves the old name's config here, so the token, machine id and name stay
107
+ * (the website keeps seeing the same machine), then deletes the old config
108
+ * directory — one machine id must not be used by two programs — and the old
109
+ * Skill cache. Throws ConfigError when the old config is unreadable.
110
+ */
111
+ export function adoptLegacyConfig(paths) {
112
+ saveConfig(paths, loadConfig({ configFile: paths.legacyConfigFile }));
113
+ fs.rmSync(paths.legacyConfigDir, { recursive: true, force: true });
114
+ fs.rmSync(paths.legacyCacheDir, { recursive: true, force: true });
115
+ }
116
+
117
+ export function defaultWorkRoot({ platform = process.platform, uid = process.getuid?.() ?? 0, tmpdir = os.tmpdir() } = {}) {
118
+ return platform === 'darwin' ? path.join(tmpdir, 'work-agent-runner') : `/var/tmp/work-agent-runner-${uid}`;
119
+ }
120
+
121
+ export function isInside(child, parent) {
122
+ return child === parent || child.startsWith(parent.endsWith(path.sep) ? parent : `${parent}${path.sep}`);
123
+ }
124
+
125
+ function realpathOr(value) {
126
+ try {
127
+ return fs.realpathSync(value);
128
+ } catch {
129
+ return path.resolve(value);
130
+ }
131
+ }
132
+
133
+ export class WorkRootError extends Error {}
134
+
135
+ /**
136
+ * Creates (0700) and checks the work root: not inside HOME (also after
137
+ * resolving symlinks), not a symlink itself, owned by this user. Returns its
138
+ * real path, which everything else uses.
139
+ */
140
+ export function prepareWorkRoot(dir, { home = os.homedir(), uid = process.getuid?.() ?? 0 } = {}) {
141
+ const resolved = path.resolve(dir);
142
+ const realHome = realpathOr(home);
143
+ const inHome = (value) => isInside(value, path.resolve(home)) || isInside(value, realHome);
144
+ const message = `工作目录 ${resolved} 在主目录(${home})之内;沙箱不允许读取主目录,请用 --work-dir 换到主目录之外`;
145
+ if (inHome(resolved) || inHome(path.join(realpathOr(path.dirname(resolved)), path.basename(resolved)))) {
146
+ throw new WorkRootError(message);
147
+ }
148
+ fs.mkdirSync(resolved, { recursive: true, mode: 0o700 });
149
+ const stat = fs.lstatSync(resolved);
150
+ if (stat.isSymbolicLink()) throw new WorkRootError(`工作目录 ${resolved} 不能是符号链接`);
151
+ if (!stat.isDirectory()) throw new WorkRootError(`${resolved} 不是目录`);
152
+ if (stat.uid !== uid) throw new WorkRootError(`工作目录 ${resolved} 的属主不是当前用户,请删除它或用 --work-dir 换一个目录`);
153
+ if ((stat.mode & 0o777) !== 0o700) fs.chmodSync(resolved, 0o700);
154
+ const real = fs.realpathSync(resolved);
155
+ if (inHome(real)) throw new WorkRootError(message);
156
+ return real;
157
+ }
@@ -0,0 +1,225 @@
1
+ // Staying connected: the SSE control channel (jobs, cancels, revocation) and
2
+ // heartbeats, independent of each other. The channel reconnects with backoff
3
+ // (1 s doubling to 60 s, ±20 % jitter, reset after 60 s connected); heartbeats
4
+ // keep going while it is down, so running jobs are not lost.
5
+ //
6
+ // Ends with { code, message, clearToken? }: code 78 when someone must act
7
+ // (token deleted, machine blocked, the same config running twice), 0 when
8
+ // stopped through `signal`.
9
+
10
+ import { ApiError, IdleError } from './http.mjs';
11
+
12
+ export const UPDATE_COMMAND = 'npm i -g @online-tools/work-agent-runner@latest';
13
+ const IDLE_MS = 45_000;
14
+ const BACKOFF_START_MS = 1000;
15
+ const BACKOFF_MAX_MS = 60_000;
16
+ const STABLE_MS = 60_000;
17
+ const REPLACED_WINDOW_MS = 10 * 60_000;
18
+ const REPLACED_LIMIT = 3;
19
+
20
+ export const FATAL = {
21
+ tokenDeleted: {
22
+ code: 78,
23
+ clearToken: true,
24
+ message: '接入令牌已失效或已在网页上删除,已清除本机保存的令牌;请新建令牌后运行 work-agent-runner login',
25
+ },
26
+ blocked: { code: 78, message: '这台机器已在网页上被封禁;解除封禁后请重新启动程序或服务' },
27
+ replaced: {
28
+ code: 78,
29
+ message: '控制通道 10 分钟内被挤掉 3 次:可能有另一台机器使用了相同的配置,请在复制出来的那台上运行 work-agent-runner login --new-id',
30
+ },
31
+ };
32
+
33
+ /** The fatal result an API error means, or null. */
34
+ export function fatalFor(error) {
35
+ if (!(error instanceof ApiError)) return null;
36
+ if (error.status === 401) return FATAL.tokenDeleted;
37
+ if (error.status === 403 && error.code === 'machine_blocked') return FATAL.blocked;
38
+ return null;
39
+ }
40
+
41
+ function compareVersions(a, b) {
42
+ const parse = (value) => (/^(\d+)\.(\d+)\.(\d+)/.exec(String(value)) || [0, 0, 0, 0]).slice(1, 4).map(Number);
43
+ const [x, y] = [parse(a), parse(b)];
44
+ for (let index = 0; index < 3; index += 1) if (x[index] !== y[index]) return x[index] < y[index] ? -1 : 1;
45
+ return 0;
46
+ }
47
+
48
+ function sleep(ms, signal) {
49
+ return new Promise((resolve) => {
50
+ if (signal?.aborted) return resolve();
51
+ const timer = setTimeout(done, ms);
52
+ function done() {
53
+ clearTimeout(timer);
54
+ signal?.removeEventListener('abort', done);
55
+ resolve();
56
+ }
57
+ signal?.addEventListener('abort', done, { once: true });
58
+ });
59
+ }
60
+
61
+ function jitter(ms) {
62
+ return Math.round(ms * (0.8 + Math.random() * 0.4));
63
+ }
64
+
65
+ /**
66
+ * Runs until stopped or fatal.
67
+ * client http.mjs client
68
+ * jobs JobManager (handle / cancel / runningIds)
69
+ * connect() POST /connect again (after 409 machine_unknown); returns its reply
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
74
+ * heartbeatMs from the connect reply
75
+ */
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
+ }) {
88
+ const stopper = new AbortController();
89
+ const stop = AbortSignal.any([signal || new AbortController().signal, stopper.signal]);
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
+ };
98
+
99
+ const end = (result) => {
100
+ if (state.result) return;
101
+ state.result = result;
102
+ stopper.abort();
103
+ };
104
+
105
+ const handleError = async (error) => {
106
+ const fatal = fatalFor(error);
107
+ if (fatal) {
108
+ end(fatal);
109
+ return;
110
+ }
111
+ if (error instanceof ApiError && error.status === 409 && error.code === 'machine_unknown') {
112
+ log.warn('网站上没有这台机器的记录(可能已被移除),重新登记');
113
+ try {
114
+ const reply = await connect();
115
+ if (reply?.heartbeatMs) state.heartbeatMs = reply.heartbeatMs;
116
+ state.sentCapabilities = '';
117
+ noteConfirmed(reply?.confirmed, reply?.name);
118
+ } catch (failure) {
119
+ const again = fatalFor(failure);
120
+ if (again) end(again);
121
+ else log.warn(`重新登记失败:${failure.message}`);
122
+ }
123
+ }
124
+ };
125
+
126
+ const onEvent = (event) => {
127
+ switch (event?.type) {
128
+ case 'hello':
129
+ if (Number.isInteger(event.heartbeatMs) && event.heartbeatMs >= 1000) state.heartbeatMs = event.heartbeatMs;
130
+ // The website may have restarted: report capabilities again with the next heartbeat.
131
+ state.sentCapabilities = '';
132
+ noteConfirmed(event.confirmed);
133
+ break;
134
+ case 'job':
135
+ jobs.handle(event.job);
136
+ break;
137
+ case 'confirmed':
138
+ noteConfirmed(true, typeof event.name === 'string' ? event.name.slice(0, 40) : '');
139
+ break;
140
+ case 'cancel':
141
+ if (typeof event.runId === 'string') jobs.cancel(event.runId);
142
+ break;
143
+ case 'revoked':
144
+ if (event.reason === 'token_deleted') end(FATAL.tokenDeleted);
145
+ else if (event.reason === 'machine_blocked') end(FATAL.blocked);
146
+ else if (event.reason === 'replaced') {
147
+ const now = Date.now();
148
+ state.replaced = state.replaced.filter((at) => now - at < REPLACED_WINDOW_MS);
149
+ state.replaced.push(now);
150
+ if (state.replaced.length >= REPLACED_LIMIT) end(FATAL.replaced);
151
+ else log.warn('控制通道被同一台机器的另一个连接替换,稍后重连');
152
+ }
153
+ break;
154
+ default:
155
+ break;
156
+ }
157
+ };
158
+
159
+ const heartbeats = (async () => {
160
+ while (!stop.aborted) {
161
+ await sleep(state.heartbeatMs, stop);
162
+ if (stop.aborted) break;
163
+ const body = { version, running: jobs.runningIds().slice(0, 200) };
164
+ const current = JSON.stringify(capabilities.current());
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
+ }
173
+ try {
174
+ const reply = await client.request('POST', '/heartbeat', body, { signal: stop });
175
+ if (body.capabilities) state.sentCapabilities = current;
176
+ for (const runId of Array.isArray(reply?.cancel) ? reply.cancel : []) jobs.cancel(runId);
177
+ noteConfirmed(reply?.confirmed);
178
+ if (reply?.outdated && !state.warnedOutdated) {
179
+ state.warnedOutdated = true;
180
+ log.warn(`程序版本 ${version} 已低于网站要求的 ${reply.minVersion},请运行 ${UPDATE_COMMAND} 后重启`);
181
+ } else if (reply?.latestVersion && reply.latestVersion !== state.toldLatest && compareVersions(version, reply.latestVersion) < 0) {
182
+ state.toldLatest = reply.latestVersion;
183
+ log.info(`有新版本 ${reply.latestVersion}:${UPDATE_COMMAND}`);
184
+ }
185
+ } catch (error) {
186
+ if (stop.aborted) break;
187
+ await handleError(error);
188
+ }
189
+ }
190
+ })();
191
+
192
+ const channel = (async () => {
193
+ let delay = BACKOFF_START_MS;
194
+ while (!stop.aborted) {
195
+ let openedAt = 0;
196
+ try {
197
+ await client.stream('/stream', {
198
+ signal: stop,
199
+ idleMs: IDLE_MS,
200
+ onOpen: () => {
201
+ openedAt = Date.now();
202
+ log.info('控制通道已连接,等待任务');
203
+ },
204
+ onEvent,
205
+ });
206
+ if (!stop.aborted) log.warn('控制通道已断开,稍后重连');
207
+ } catch (error) {
208
+ if (stop.aborted) break;
209
+ if (error instanceof IdleError) log.warn(`${error.message},重新连接`);
210
+ else if (error instanceof ApiError) {
211
+ await handleError(error);
212
+ if (error.status === 429 && error.retryAfterMs) await sleep(error.retryAfterMs, stop);
213
+ else if (!state.result) log.warn(`控制通道连接失败:${error.message}`);
214
+ } else log.warn(`控制通道连接失败:${error?.cause?.code || error.message}`);
215
+ }
216
+ if (stop.aborted) break;
217
+ if (openedAt && Date.now() - openedAt >= STABLE_MS) delay = BACKOFF_START_MS;
218
+ await sleep(jitter(delay), stop);
219
+ delay = Math.min(BACKOFF_MAX_MS, delay * 2);
220
+ }
221
+ })();
222
+
223
+ await Promise.allSettled([heartbeats, channel]);
224
+ return state.result || { code: 0, message: '' };
225
+ }