@online-tools/work-agent-runner 0.0.0-stage → 0.0.2-alpha-1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +187 -2
- package/bin/main.mjs +990 -0
- package/bin/work-agent-runner.cjs +139 -0
- package/lib/claude-cli.mjs +85 -0
- package/lib/config.mjs +238 -0
- package/lib/connection.mjs +225 -0
- package/lib/doctor.mjs +316 -0
- package/lib/http.mjs +198 -0
- package/lib/jobs.mjs +527 -0
- package/lib/lock.mjs +70 -0
- package/lib/log.mjs +22 -0
- package/lib/node-runtime.cjs +595 -0
- package/lib/packages.mjs +78 -0
- package/lib/probe-model.mjs +129 -0
- package/lib/prompt.mjs +94 -0
- package/lib/sandbox.mjs +265 -0
- package/lib/service.mjs +226 -0
- package/lib/setup.mjs +155 -0
- package/lib/skill-text.mjs +29 -0
- package/lib/skill-tree.mjs +100 -0
- package/lib/system-info.mjs +132 -0
- package/lib/work-agent.mjs +486 -0
- package/package.json +10 -4
|
@@ -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,238 @@
|
|
|
1
|
+
// Everything the program keeps lives under one directory, its "home"
|
|
2
|
+
// (WORK_AGENT_RUNNER_HOME, default ~/.work-agent-runner, 0700):
|
|
3
|
+
//
|
|
4
|
+
// config.json { server, token, clientId, setupDone, workRoot?,
|
|
5
|
+
// claudePath?, machineName?, workAgentRepo?,
|
|
6
|
+
// workAgentRepoDir, ascendReposDir } (0600)
|
|
7
|
+
// run.lock one running instance per user
|
|
8
|
+
// work-agent/ the work-agent clone: the Skill source (lib/work-agent.mjs)
|
|
9
|
+
// work-agent.lock the clone's lock (a terminal `update` vs the service)
|
|
10
|
+
// .work-agent/ WORK_AGENT_HOME of every job: logs/ tmp/ docs/, and
|
|
11
|
+
// ascend-repos -> the shared knowledge pool
|
|
12
|
+
// node/ a downloaded Node, when the system one is too old
|
|
13
|
+
// runs/<7 chars>/ one directory per job, deleted when it ends (--work-dir
|
|
14
|
+
// moves just this one elsewhere, e.g. a bigger disk)
|
|
15
|
+
//
|
|
16
|
+
// Earlier versions kept these under XDG directories and ran jobs in /var/tmp;
|
|
17
|
+
// adoptLegacyState() moves what matters and drops the rest.
|
|
18
|
+
// Functions only; bin/ decides when to read or write.
|
|
19
|
+
|
|
20
|
+
import crypto from 'node:crypto';
|
|
21
|
+
import fs from 'node:fs';
|
|
22
|
+
import os from 'node:os';
|
|
23
|
+
import path from 'node:path';
|
|
24
|
+
|
|
25
|
+
export const DEFAULT_SERVER = 'https://online-tools.closerouter.site';
|
|
26
|
+
/** The work-agent clone is fast-forwarded every day at this hour (local time). */
|
|
27
|
+
export const REPO_UPDATE_HOUR = 8;
|
|
28
|
+
/** The knowledge pool is updated this often (every repository it holds). */
|
|
29
|
+
export const POOL_UPDATE_MS = 60 * 60_000;
|
|
30
|
+
export const PROGRAM_DIR = '.work-agent-runner';
|
|
31
|
+
/** The shared knowledge pool: work-agent's own default location. */
|
|
32
|
+
export const POOL_DIR = path.join('.work-agent', 'ascend-repos');
|
|
33
|
+
|
|
34
|
+
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}$/;
|
|
35
|
+
|
|
36
|
+
/** The program's name until 0.0.1-alpha-4 (command, directories, service). */
|
|
37
|
+
export const LEGACY_NAME = 'gitcode-agent-runner';
|
|
38
|
+
|
|
39
|
+
export class ConfigError extends Error {}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Every path the program owns. `home` is the user's home directory; the
|
|
43
|
+
* program's own home is WORK_AGENT_RUNNER_HOME or <home>/.work-agent-runner.
|
|
44
|
+
*/
|
|
45
|
+
export function configPaths(env = process.env, home = os.homedir()) {
|
|
46
|
+
const base = env.WORK_AGENT_RUNNER_HOME ? path.resolve(env.WORK_AGENT_RUNNER_HOME) : path.join(home, PROGRAM_DIR);
|
|
47
|
+
const configRoot = env.XDG_CONFIG_HOME || path.join(home, '.config');
|
|
48
|
+
return {
|
|
49
|
+
baseDir: base,
|
|
50
|
+
// saveConfig() creates this; it is the program's home, not a subdirectory.
|
|
51
|
+
configDir: base,
|
|
52
|
+
configFile: path.join(base, 'config.json'),
|
|
53
|
+
lockFile: path.join(base, 'run.lock'),
|
|
54
|
+
repoDir: path.join(base, 'work-agent'),
|
|
55
|
+
repoLockFile: path.join(base, 'work-agent.lock'),
|
|
56
|
+
// WORK_AGENT_HOME handed to every job. Its ascend-repos is a symlink to the
|
|
57
|
+
// pool, which stays outside this (writable) directory.
|
|
58
|
+
workAgentHome: path.join(base, '.work-agent'),
|
|
59
|
+
nodeDir: path.join(base, 'node'),
|
|
60
|
+
runsRoot: base,
|
|
61
|
+
poolDir: path.join(home, POOL_DIR),
|
|
62
|
+
// Where earlier versions kept things (newest first: adopt the newest).
|
|
63
|
+
legacyConfigFiles: [
|
|
64
|
+
path.join(configRoot, 'work-agent-runner', 'config.json'),
|
|
65
|
+
path.join(configRoot, LEGACY_NAME, 'config.json'),
|
|
66
|
+
],
|
|
67
|
+
legacyDirs: [
|
|
68
|
+
path.join(configRoot, 'work-agent-runner'),
|
|
69
|
+
path.join(configRoot, LEGACY_NAME),
|
|
70
|
+
path.join(env.XDG_CACHE_HOME || path.join(home, '.cache'), 'work-agent-runner'),
|
|
71
|
+
path.join(env.XDG_CACHE_HOME || path.join(home, '.cache'), LEGACY_NAME),
|
|
72
|
+
],
|
|
73
|
+
legacyNodeDirs: [
|
|
74
|
+
path.join(env.XDG_DATA_HOME || path.join(home, '.local', 'share'), 'work-agent-runner', 'node'),
|
|
75
|
+
path.join(env.XDG_DATA_HOME || path.join(home, '.local', 'share'), LEGACY_NAME, 'node'),
|
|
76
|
+
],
|
|
77
|
+
legacyRepoDir: path.join(env.XDG_DATA_HOME || path.join(home, '.local', 'share'), 'work-agent-runner', 'work-agent'),
|
|
78
|
+
legacyWorkRoots: [
|
|
79
|
+
`/var/tmp/work-agent-runner-${process.getuid?.() ?? 0}`,
|
|
80
|
+
`/var/tmp/gitcode-agent-runner-${process.getuid?.() ?? 0}`,
|
|
81
|
+
],
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* The two repository locations, from the config file when it names them (that
|
|
87
|
+
* is where the updater looks) and otherwise the defaults. Returns `paths` with
|
|
88
|
+
* repoDir / poolDir resolved, and whether the config should be written back so
|
|
89
|
+
* the file always shows both.
|
|
90
|
+
*/
|
|
91
|
+
export function withRepoPaths(paths, config) {
|
|
92
|
+
const repoDir = config.workAgentRepoDir || paths.repoDir;
|
|
93
|
+
const poolDir = config.ascendReposDir || paths.poolDir;
|
|
94
|
+
if (repoDir === poolDir) {
|
|
95
|
+
throw new ConfigError(`work-agent 仓库和知识仓不能是同一个目录(${repoDir})`);
|
|
96
|
+
}
|
|
97
|
+
return {
|
|
98
|
+
paths: { ...paths, repoDir, poolDir },
|
|
99
|
+
missing: !config.workAgentRepoDir || !config.ascendReposDir,
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** The lock file of a legacy config directory, for "is the old program running?". */
|
|
104
|
+
export function legacyLockFile(configFile) {
|
|
105
|
+
return path.join(path.dirname(configFile), 'run.lock');
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export function newClientId() {
|
|
109
|
+
return crypto.randomUUID();
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export function isClientId(value) {
|
|
113
|
+
return typeof value === 'string' && UUID_V4.test(value);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function normalize(raw) {
|
|
117
|
+
const config = {
|
|
118
|
+
server: typeof raw.server === 'string' ? raw.server : '',
|
|
119
|
+
token: typeof raw.token === 'string' ? raw.token : '',
|
|
120
|
+
clientId: isClientId(raw.clientId) ? raw.clientId : '',
|
|
121
|
+
setupDone: raw.setupDone === true,
|
|
122
|
+
};
|
|
123
|
+
if (typeof raw.workRoot === 'string' && raw.workRoot) config.workRoot = raw.workRoot;
|
|
124
|
+
if (typeof raw.claudePath === 'string' && raw.claudePath) config.claudePath = raw.claudePath;
|
|
125
|
+
// Where the two repositories are. Written on first run, so the file shows
|
|
126
|
+
// them; edit it (absolute paths) to put either somewhere else.
|
|
127
|
+
for (const key of ['workAgentRepoDir', 'ascendReposDir']) {
|
|
128
|
+
if (typeof raw[key] === 'string' && path.isAbsolute(raw[key])) config[key] = path.resolve(raw[key]);
|
|
129
|
+
}
|
|
130
|
+
// A mirror of the work-agent repository, for this machine only. http(s) only:
|
|
131
|
+
// a value starting with '-' would reach git as an option.
|
|
132
|
+
if (typeof raw.workAgentRepo === 'string' && /^https?:\/\/[^\s]{1,480}$/.test(raw.workAgentRepo)) {
|
|
133
|
+
config.workAgentRepo = raw.workAgentRepo;
|
|
134
|
+
}
|
|
135
|
+
// The name sent with /connect: it names this machine when the website registers it.
|
|
136
|
+
if (typeof raw.machineName === 'string' && raw.machineName) config.machineName = raw.machineName.slice(0, 100);
|
|
137
|
+
return config;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** The saved config (defaults when there is none); throws ConfigError when it is unreadable. */
|
|
141
|
+
export function loadConfig(paths) {
|
|
142
|
+
let text;
|
|
143
|
+
try {
|
|
144
|
+
text = fs.readFileSync(paths.configFile, 'utf8');
|
|
145
|
+
} catch (error) {
|
|
146
|
+
if (error.code === 'ENOENT') return normalize({});
|
|
147
|
+
throw new ConfigError(`无法读取配置文件 ${paths.configFile}:${error.message}`);
|
|
148
|
+
}
|
|
149
|
+
let raw;
|
|
150
|
+
try {
|
|
151
|
+
raw = JSON.parse(text);
|
|
152
|
+
} catch {
|
|
153
|
+
throw new ConfigError(`配置文件已损坏:${paths.configFile}(删除后运行 work-agent-runner login)`);
|
|
154
|
+
}
|
|
155
|
+
return normalize(raw && typeof raw === 'object' ? raw : {});
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** Writes the config atomically (temporary file, then rename); dir 0700, file 0600. */
|
|
159
|
+
export function saveConfig(paths, config) {
|
|
160
|
+
fs.mkdirSync(paths.configDir, { recursive: true, mode: 0o700 });
|
|
161
|
+
fs.chmodSync(paths.configDir, 0o700);
|
|
162
|
+
const temp = `${paths.configFile}.${process.pid}.${crypto.randomBytes(4).toString('hex')}.tmp`;
|
|
163
|
+
try {
|
|
164
|
+
fs.writeFileSync(temp, `${JSON.stringify(normalize(config), null, 2)}\n`, { mode: 0o600 });
|
|
165
|
+
fs.renameSync(temp, paths.configFile);
|
|
166
|
+
} catch (error) {
|
|
167
|
+
fs.rmSync(temp, { force: true });
|
|
168
|
+
throw error;
|
|
169
|
+
}
|
|
170
|
+
fs.chmodSync(paths.configFile, 0o600);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** The newest legacy config to adopt ('' when there is none, or one is already here). */
|
|
174
|
+
export function legacyConfigPending(paths) {
|
|
175
|
+
if (fs.existsSync(paths.configFile)) return '';
|
|
176
|
+
return paths.legacyConfigFiles.find((file) => fs.existsSync(file)) || '';
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Moves an older layout's state into the program's home: the config (so the
|
|
181
|
+
* token, machine id and name stay — the website keeps seeing the same machine)
|
|
182
|
+
* and a Node this program downloaded before. Then removes the old directories,
|
|
183
|
+
* including the Skill cache of the versions whose Skills came from the website.
|
|
184
|
+
* Throws ConfigError when the old config is unreadable.
|
|
185
|
+
*/
|
|
186
|
+
export function adoptLegacyState(paths, configFile) {
|
|
187
|
+
if (configFile) saveConfig(paths, loadConfig({ configFile }));
|
|
188
|
+
if (!fs.existsSync(paths.nodeDir)) {
|
|
189
|
+
const node = paths.legacyNodeDirs.find((dir) => fs.existsSync(dir));
|
|
190
|
+
if (node) {
|
|
191
|
+
try {
|
|
192
|
+
fs.mkdirSync(path.dirname(paths.nodeDir), { recursive: true, mode: 0o700 });
|
|
193
|
+
fs.renameSync(node, paths.nodeDir);
|
|
194
|
+
} catch {
|
|
195
|
+
// A different filesystem, or gone: it will be downloaded again when needed.
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
// One machine id must not be used by two programs, and nothing reads these now.
|
|
200
|
+
for (const dir of [...paths.legacyDirs, paths.legacyRepoDir, ...paths.legacyWorkRoots]) {
|
|
201
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
export function isInside(child, parent) {
|
|
206
|
+
return child === parent || child.startsWith(parent.endsWith(path.sep) ? parent : `${parent}${path.sep}`);
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
function realpathOr(value) {
|
|
210
|
+
try {
|
|
211
|
+
return fs.realpathSync(value);
|
|
212
|
+
} catch {
|
|
213
|
+
return path.resolve(value);
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
export class WorkRootError extends Error {}
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* Creates (0700) and checks the directory that holds `runs/`: not a symlink,
|
|
221
|
+
* not the home directory itself, owned by this user. Returns its real path,
|
|
222
|
+
* which everything else uses. Jobs live inside the program's home now, so the
|
|
223
|
+
* sandbox is told about that one subtree (lib/sandbox.mjs) instead of being
|
|
224
|
+
* kept out of the home directory entirely.
|
|
225
|
+
*/
|
|
226
|
+
export function prepareWorkRoot(dir, { home = os.homedir(), uid = process.getuid?.() ?? 0 } = {}) {
|
|
227
|
+
const resolved = path.resolve(dir);
|
|
228
|
+
if (resolved === path.resolve(home) || resolved === realpathOr(home)) {
|
|
229
|
+
throw new WorkRootError(`工作目录不能是主目录本身(${resolved}),请用 --work-dir 指定一个子目录`);
|
|
230
|
+
}
|
|
231
|
+
fs.mkdirSync(resolved, { recursive: true, mode: 0o700 });
|
|
232
|
+
const stat = fs.lstatSync(resolved);
|
|
233
|
+
if (stat.isSymbolicLink()) throw new WorkRootError(`工作目录 ${resolved} 不能是符号链接`);
|
|
234
|
+
if (!stat.isDirectory()) throw new WorkRootError(`${resolved} 不是目录`);
|
|
235
|
+
if (stat.uid !== uid) throw new WorkRootError(`工作目录 ${resolved} 的属主不是当前用户,请删除它或用 --work-dir 换一个目录`);
|
|
236
|
+
if ((stat.mode & 0o777) !== 0o700) fs.chmodSync(resolved, 0o700);
|
|
237
|
+
return fs.realpathSync(resolved);
|
|
238
|
+
}
|
|
@@ -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
|
+
}
|