@online-tools/agent-runner 0.0.0-stage → 0.0.1-alpha-2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +104 -2
- package/bin/gitcode-agent-runner.cjs +139 -0
- package/bin/main.mjs +675 -0
- package/lib/claude-cli.mjs +85 -0
- package/lib/config.mjs +126 -0
- package/lib/connection.mjs +191 -0
- package/lib/doctor.mjs +240 -0
- package/lib/http.mjs +198 -0
- package/lib/jobs.mjs +494 -0
- package/lib/lock.mjs +66 -0
- package/lib/log.mjs +22 -0
- package/lib/node-runtime.cjs +594 -0
- package/lib/packages.mjs +74 -0
- package/lib/prompt.mjs +76 -0
- package/lib/sandbox.mjs +110 -0
- package/lib/service.mjs +187 -0
- package/lib/setup.mjs +152 -0
- package/lib/skill-text.mjs +29 -0
- package/lib/skills.mjs +211 -0
- package/package.json +10 -4
package/bin/main.mjs
ADDED
|
@@ -0,0 +1,675 @@
|
|
|
1
|
+
// gitcode-agent-runner: runs GitCode 在线工具's 在线 Agent jobs (PR 描述 /
|
|
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
|
+
//
|
|
6
|
+
// Exit codes: 0 stopped normally, 1 error, 78 needs a person (no token, token
|
|
7
|
+
// deleted, machine blocked, same config running twice, unsupported system,
|
|
8
|
+
// root, another instance) — services do not restart on 78 (launchd: 0).
|
|
9
|
+
|
|
10
|
+
import { spawn, spawnSync } from 'node:child_process';
|
|
11
|
+
import { once } from 'node:events';
|
|
12
|
+
import fs from 'node:fs';
|
|
13
|
+
import os from 'node:os';
|
|
14
|
+
import path from 'node:path';
|
|
15
|
+
import { fileURLToPath } from 'node:url';
|
|
16
|
+
import { parseArgs } from 'node:util';
|
|
17
|
+
|
|
18
|
+
import {
|
|
19
|
+
ConfigError,
|
|
20
|
+
DEFAULT_SERVER,
|
|
21
|
+
WorkRootError,
|
|
22
|
+
configPaths,
|
|
23
|
+
defaultWorkRoot,
|
|
24
|
+
loadConfig,
|
|
25
|
+
newClientId,
|
|
26
|
+
prepareWorkRoot,
|
|
27
|
+
saveConfig,
|
|
28
|
+
} from '../lib/config.mjs';
|
|
29
|
+
import { fatalFor, runConnection } from '../lib/connection.mjs';
|
|
30
|
+
import { SANDBOX_DOCS, runDoctor, which } from '../lib/doctor.mjs';
|
|
31
|
+
import { ApiError, createClient, normalizeServerUrl, proxyMode } from '../lib/http.mjs';
|
|
32
|
+
import { FEATURE_LABELS, JobManager } from '../lib/jobs.mjs';
|
|
33
|
+
import { LockedError, acquireLock, isRunnerAlive } from '../lib/lock.mjs';
|
|
34
|
+
import { NODE_REQUIREMENT, nodeSupported } from '../lib/node-runtime.cjs';
|
|
35
|
+
import { createLogger } from '../lib/log.mjs';
|
|
36
|
+
import { CancelledError, askYesNo, isInteractive, readHidden, readStdin } from '../lib/prompt.mjs';
|
|
37
|
+
import { EXIT_NEEDS_ATTENTION, installService, serviceExitCode, serviceStatus, uninstallService } from '../lib/service.mjs';
|
|
38
|
+
import { DEFAULT_REQUIRED_TOOLS, npmPrefixWritable, planSetup, runSetup } from '../lib/setup.mjs';
|
|
39
|
+
import { SkillCache } from '../lib/skills.mjs';
|
|
40
|
+
|
|
41
|
+
// The command's entry point (it checks the Node version, then loads this file).
|
|
42
|
+
const ENTRY = fileURLToPath(new URL('./gitcode-agent-runner.cjs', import.meta.url));
|
|
43
|
+
const VERSION = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
|
|
44
|
+
const TOKEN_PATTERN = /^gcm_[A-Za-z0-9_-]{43}$/;
|
|
45
|
+
const DOCTOR_INTERVAL_MS = 60 * 60_000;
|
|
46
|
+
const ATTENTION = EXIT_NEEDS_ATTENTION;
|
|
47
|
+
|
|
48
|
+
// Which tools each feature needs — for the messages here only; the website decides.
|
|
49
|
+
const FEATURE_TOOLS = {
|
|
50
|
+
'pr-desc-issue-gen': ['git', 'curl', 'python3'],
|
|
51
|
+
'ascend-code-review': ['git', 'python3', 'curl', 'jq', 'sed'],
|
|
52
|
+
'code-review-flash': ['python3', 'git', 'base64'],
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
const USAGE = `GitCode Agent 执行机器 ${VERSION}
|
|
56
|
+
|
|
57
|
+
用法:gitcode-agent-runner [命令] [选项]
|
|
58
|
+
|
|
59
|
+
命令:
|
|
60
|
+
start 连接网站并等待任务(默认)
|
|
61
|
+
login [--new-id] [--token-stdin]
|
|
62
|
+
输入接入令牌(校验通过才保存);--new-id 重新生成机器标识
|
|
63
|
+
logout 清除本机保存的令牌(机器标识保留)
|
|
64
|
+
setup [--yes] 检查并安装缺少的依赖(需在终端里运行)
|
|
65
|
+
doctor [--json] 检查依赖、沙箱和各功能是否可用
|
|
66
|
+
status 显示网站、令牌、机器标识、工作目录、服务状态,并测试连接
|
|
67
|
+
service install|uninstall|status
|
|
68
|
+
注册 / 删除 / 查看后台服务(开机自启)
|
|
69
|
+
version 显示版本
|
|
70
|
+
|
|
71
|
+
选项:
|
|
72
|
+
--server <url> 网站地址(默认 ${DEFAULT_SERVER},会保存)
|
|
73
|
+
--work-dir <dir> 工作目录(不能在主目录之内,会保存)
|
|
74
|
+
--allow-root 允许以 root 运行(仅限容器等确有需要的场合)`;
|
|
75
|
+
|
|
76
|
+
class ExitError extends Error {
|
|
77
|
+
constructor(code, message = '') {
|
|
78
|
+
super(message);
|
|
79
|
+
this.code = code;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const say = (text = '') => process.stdout.write(`${text}\n`);
|
|
84
|
+
const log = createLogger();
|
|
85
|
+
|
|
86
|
+
function checkSystem() {
|
|
87
|
+
if (!['linux', 'darwin'].includes(process.platform)) throw new ExitError(ATTENTION, '暂不支持此系统(只支持 Linux 和 macOS)');
|
|
88
|
+
// gitcode-agent-runner.cjs already switched to a supported Node when it could.
|
|
89
|
+
if (!nodeSupported(process.versions.node)) throw new ExitError(ATTENTION, `需要 Node ${NODE_REQUIREMENT}(当前 ${process.versions.node})`);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Proxies for this program's own requests. Node before 24.14 / 25.4 reads
|
|
94
|
+
* NODE_USE_ENV_PROXY only at startup: run once more with it set and pass
|
|
95
|
+
* signals and the exit code through. Returns that exit code, or null.
|
|
96
|
+
*/
|
|
97
|
+
async function applyProxy() {
|
|
98
|
+
if (proxyMode() !== 'restart') return null;
|
|
99
|
+
const child = spawn(process.execPath, [...process.execArgv, ENTRY, ...process.argv.slice(2)], {
|
|
100
|
+
stdio: 'inherit',
|
|
101
|
+
env: { ...process.env, NODE_USE_ENV_PROXY: '1', GC_RUNNER_REEXEC: '1' },
|
|
102
|
+
});
|
|
103
|
+
for (const signal of ['SIGINT', 'SIGTERM']) process.on(signal, () => child.kill(signal));
|
|
104
|
+
const [code, signal] = await once(child, 'exit');
|
|
105
|
+
return code ?? (signal ? 128 + (os.constants.signals[signal] || 0) : 1);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function realHome() {
|
|
109
|
+
try {
|
|
110
|
+
return fs.realpathSync(os.homedir());
|
|
111
|
+
} catch {
|
|
112
|
+
return path.resolve(os.homedir());
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** Config, server, client id and work root; --server / --work-dir are saved. */
|
|
117
|
+
function loadContext(values, { workRoot: needWorkRoot = true } = {}) {
|
|
118
|
+
const paths = configPaths();
|
|
119
|
+
const config = loadConfig(paths);
|
|
120
|
+
let changed = false;
|
|
121
|
+
if (!config.clientId) {
|
|
122
|
+
config.clientId = newClientId();
|
|
123
|
+
changed = true;
|
|
124
|
+
}
|
|
125
|
+
let server;
|
|
126
|
+
try {
|
|
127
|
+
server = normalizeServerUrl(values.server || config.server || DEFAULT_SERVER);
|
|
128
|
+
} catch (error) {
|
|
129
|
+
throw new ExitError(ATTENTION, error.message);
|
|
130
|
+
}
|
|
131
|
+
if (values.server && server !== config.server) {
|
|
132
|
+
config.server = server;
|
|
133
|
+
changed = true;
|
|
134
|
+
}
|
|
135
|
+
if (values['work-dir']) {
|
|
136
|
+
const dir = path.resolve(values['work-dir']);
|
|
137
|
+
if (dir !== config.workRoot) {
|
|
138
|
+
config.workRoot = dir;
|
|
139
|
+
changed = true;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
const workRoot = needWorkRoot ? prepareWorkRoot(config.workRoot || defaultWorkRoot()) : '';
|
|
143
|
+
if (changed) saveConfig(paths, config);
|
|
144
|
+
return { paths, config, server, workRoot, realHome: realHome() };
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function save(ctx) {
|
|
148
|
+
saveConfig(ctx.paths, ctx.config);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function clientFor(ctx, token = ctx.config.token) {
|
|
152
|
+
return createClient({ server: ctx.server, token, clientId: ctx.config.clientId, version: VERSION });
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function connect(client, capabilities) {
|
|
156
|
+
return client.request('POST', '/connect', { hostname: os.hostname(), version: VERSION, capabilities });
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function networkReason(error) {
|
|
160
|
+
return error?.cause?.code || error?.cause?.message || error?.message || String(error);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** doctor + remembering a claude found outside PATH. */
|
|
164
|
+
async function doctorFor(ctx) {
|
|
165
|
+
const result = await runDoctor({ configuredClaude: ctx.config.claudePath || '', workRoot: ctx.workRoot, realHome: ctx.realHome });
|
|
166
|
+
const remembered = result.claude.viaNpmPrefix || result.claude.path === ctx.config.claudePath ? result.claude.path : '';
|
|
167
|
+
if ((ctx.config.claudePath || '') !== remembered) {
|
|
168
|
+
ctx.config.claudePath = remembered;
|
|
169
|
+
save(ctx);
|
|
170
|
+
}
|
|
171
|
+
return result;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function connectFailure(error, server) {
|
|
175
|
+
if (error instanceof ApiError) {
|
|
176
|
+
if (error.status === 403) return new ExitError(ATTENTION, error.message);
|
|
177
|
+
if (error.status === 400) return new ExitError(1, `网站拒绝了连接:${error.message}`);
|
|
178
|
+
}
|
|
179
|
+
return new ExitError(1, `无法连接 ${server}:${networkReason(error)}`);
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* Asks for the token (or reads it from stdin), checks it with POST /connect
|
|
184
|
+
* and saves it only then. Up to 3 tries in a terminal.
|
|
185
|
+
*/
|
|
186
|
+
async function obtainToken(ctx, { fromStdin = false, capabilities }) {
|
|
187
|
+
if (!fromStdin && !isInteractive()) throw new ExitError(ATTENTION, '还没有接入令牌:请先在终端运行 gitcode-agent-runner login');
|
|
188
|
+
if (!fromStdin) say('请在「在线 Agent → 模型配置 → 接入令牌」复制令牌并粘贴(输入不显示):');
|
|
189
|
+
for (let attempt = 1; attempt <= 3; attempt += 1) {
|
|
190
|
+
const token = fromStdin ? await readStdin() : await readHidden('令牌:');
|
|
191
|
+
if (!TOKEN_PATTERN.test(token)) {
|
|
192
|
+
if (fromStdin) throw new ExitError(ATTENTION, '令牌格式不正确(应为 gcm_ 开头的 47 个字符)');
|
|
193
|
+
say('令牌格式不正确(应为 gcm_ 开头的 47 个字符),请重新粘贴');
|
|
194
|
+
continue;
|
|
195
|
+
}
|
|
196
|
+
const client = clientFor(ctx, token);
|
|
197
|
+
try {
|
|
198
|
+
const reply = await connect(client, capabilities);
|
|
199
|
+
ctx.config.token = token;
|
|
200
|
+
save(ctx);
|
|
201
|
+
say(`✓ 已连接 ${ctx.server},本机登记为「${reply.name}」(令牌:${reply.tokenName})`);
|
|
202
|
+
return { client, reply };
|
|
203
|
+
} catch (error) {
|
|
204
|
+
if (error instanceof ApiError && error.status === 401) {
|
|
205
|
+
if (fromStdin) throw new ExitError(ATTENTION, '令牌无效或已删除');
|
|
206
|
+
say('令牌无效或已删除,请重新粘贴');
|
|
207
|
+
continue;
|
|
208
|
+
}
|
|
209
|
+
if (error instanceof ApiError && error.status === 429) throw new ExitError(1, '请求过于频繁,请稍后再试');
|
|
210
|
+
throw connectFailure(error, ctx.server);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
throw new ExitError(ATTENTION, '令牌 3 次都不正确,已退出');
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** POST /connect with the saved token; waits out network trouble (services must not give up). */
|
|
217
|
+
async function connectSaved(ctx, client, capabilities) {
|
|
218
|
+
let delay = 1000;
|
|
219
|
+
for (;;) {
|
|
220
|
+
try {
|
|
221
|
+
return await connect(client, capabilities);
|
|
222
|
+
} catch (error) {
|
|
223
|
+
const fatal = fatalFor(error);
|
|
224
|
+
if (fatal) {
|
|
225
|
+
if (fatal.clearToken) {
|
|
226
|
+
ctx.config.token = '';
|
|
227
|
+
save(ctx);
|
|
228
|
+
}
|
|
229
|
+
throw new ExitError(fatal.code, fatal.message);
|
|
230
|
+
}
|
|
231
|
+
if (error instanceof ApiError && error.status !== 429 && error.status < 500) throw connectFailure(error, ctx.server);
|
|
232
|
+
log.warn(`无法连接 ${ctx.server}(${error instanceof ApiError ? error.message : networkReason(error)}),${Math.round(delay / 1000)} 秒后重试`);
|
|
233
|
+
await new Promise((resolve) => setTimeout(resolve, error?.retryAfterMs || delay));
|
|
234
|
+
delay = Math.min(60_000, delay * 2);
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
function toolLabel(name) {
|
|
240
|
+
return name === 'bwrap' ? 'bubblewrap' : name;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
function neededBy(tool) {
|
|
244
|
+
if (tool === 'bwrap' || tool === 'socat') return '沙箱需要(所有功能)';
|
|
245
|
+
const features = Object.entries(FEATURE_TOOLS).filter(([, tools]) => tools.includes(tool)).map(([feature]) => FEATURE_LABELS[feature]);
|
|
246
|
+
return features.length === 3 ? '所有功能需要' : `${features.join('、')}需要`;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
function printDoctor(result) {
|
|
250
|
+
const ready = [];
|
|
251
|
+
const missing = [];
|
|
252
|
+
for (const [name, info] of Object.entries(result.tools)) {
|
|
253
|
+
if (info.ok) ready.push(`✓ ${toolLabel(name)}${info.version ? ` ${info.version.split('.').slice(0, 2).join('.')}` : ''}`);
|
|
254
|
+
else missing.push(name);
|
|
255
|
+
}
|
|
256
|
+
if (ready.length) say(` ${ready.join(' ')}`);
|
|
257
|
+
for (const name of missing) say(` ✗ ${toolLabel(name).padEnd(11)} ${neededBy(name)}`);
|
|
258
|
+
if (!result.claude.path) say(` ✗ ${'claude'.padEnd(11)} 所有功能需要`);
|
|
259
|
+
else {
|
|
260
|
+
say(` ✓ claude ${result.claudeVersion || '(无法读取版本)'}`);
|
|
261
|
+
if (result.claude.viaNpmPrefix) say(` 提示:claude 在 ${path.dirname(result.claude.path)},建议把这个目录加入 PATH`);
|
|
262
|
+
}
|
|
263
|
+
const { sandbox } = result.capabilities;
|
|
264
|
+
if (sandbox.ok) say('✓ 沙箱可用');
|
|
265
|
+
else say(`✗ 沙箱不可用:${sandbox.reason}(说明:${SANDBOX_DOCS})`);
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
function printFeatures(reply) {
|
|
269
|
+
if (!reply?.features) return;
|
|
270
|
+
const entries = Object.entries(reply.features);
|
|
271
|
+
const ok = entries.filter(([, verdict]) => verdict.ok).map(([feature]) => FEATURE_LABELS[feature] || feature);
|
|
272
|
+
say(ok.length ? `可运行:${ok.join('、')}` : '暂时没有可运行的功能');
|
|
273
|
+
for (const [feature, verdict] of entries) {
|
|
274
|
+
if (!verdict.ok) say(`不可运行:${FEATURE_LABELS[feature] || feature}(${verdict.reason})`);
|
|
275
|
+
}
|
|
276
|
+
if (reply.outdated) say(`程序版本过低,请运行 npm i -g @online-tools/agent-runner@latest`);
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
function setupPlan(result, reply) {
|
|
280
|
+
const npm = which('npm');
|
|
281
|
+
let npmWritable = false;
|
|
282
|
+
if (npm) {
|
|
283
|
+
const prefix = spawnSync(npm, ['prefix', '-g'], { encoding: 'utf8', timeout: 20_000, stdio: ['ignore', 'pipe', 'ignore'] }).stdout?.trim();
|
|
284
|
+
npmWritable = prefix ? npmPrefixWritable(prefix) : false;
|
|
285
|
+
}
|
|
286
|
+
return planSetup({
|
|
287
|
+
platform: process.platform,
|
|
288
|
+
requiredTools: Array.isArray(reply?.requiredTools) ? reply.requiredTools : DEFAULT_REQUIRED_TOOLS,
|
|
289
|
+
tools: result.tools,
|
|
290
|
+
claudeVersion: result.claudeVersion,
|
|
291
|
+
minClaudeVersion: reply?.minClaudeVersion || '',
|
|
292
|
+
manager: result.packageManager,
|
|
293
|
+
isRoot: process.getuid() === 0,
|
|
294
|
+
sudo: which('sudo'),
|
|
295
|
+
npm,
|
|
296
|
+
npmWritable,
|
|
297
|
+
});
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
// ---- Commands ------------------------------------------------------------------
|
|
301
|
+
|
|
302
|
+
async function start(values) {
|
|
303
|
+
checkSystem();
|
|
304
|
+
const restarted = await applyProxy();
|
|
305
|
+
if (restarted !== null) return restarted;
|
|
306
|
+
if (process.getuid() === 0) {
|
|
307
|
+
if (!values['allow-root']) {
|
|
308
|
+
throw new ExitError(ATTENTION, '不要以 root 运行:任务中的命令会拥有 root 权限。请用普通账号运行;容器等确有需要时加 --allow-root');
|
|
309
|
+
}
|
|
310
|
+
log.warn('正以 root 运行(--allow-root):沙箱内的命令拥有 root 权限,建议改用专用的低权限账号');
|
|
311
|
+
}
|
|
312
|
+
const ctx = loadContext(values);
|
|
313
|
+
let lock;
|
|
314
|
+
try {
|
|
315
|
+
lock = acquireLock(ctx.paths.lockFile);
|
|
316
|
+
} catch (error) {
|
|
317
|
+
if (error instanceof LockedError) throw new ExitError(ATTENTION, error.message);
|
|
318
|
+
throw error;
|
|
319
|
+
}
|
|
320
|
+
try {
|
|
321
|
+
say(`GitCode Agent 执行机器 ${VERSION}`);
|
|
322
|
+
// Whatever a previous run left behind.
|
|
323
|
+
fs.rmSync(path.join(ctx.workRoot, 'runs'), { recursive: true, force: true });
|
|
324
|
+
for (const name of fs.readdirSync(ctx.workRoot)) {
|
|
325
|
+
if (name.startsWith('probe-')) fs.rmSync(path.join(ctx.workRoot, name), { recursive: true, force: true });
|
|
326
|
+
}
|
|
327
|
+
const interactive = isInteractive() && !process.env.GC_RUNNER_SERVICE;
|
|
328
|
+
if (!ctx.config.token && !interactive) {
|
|
329
|
+
throw new ExitError(ATTENTION, '还没有接入令牌:请先在终端运行 gitcode-agent-runner login');
|
|
330
|
+
}
|
|
331
|
+
say('检查依赖和沙箱……');
|
|
332
|
+
let result = await doctorFor(ctx);
|
|
333
|
+
let client;
|
|
334
|
+
let reply;
|
|
335
|
+
if (!ctx.config.token) {
|
|
336
|
+
({ client, reply } = await obtainToken(ctx, { capabilities: result.capabilities }));
|
|
337
|
+
} else {
|
|
338
|
+
client = clientFor(ctx);
|
|
339
|
+
reply = await connectSaved(ctx, client, result.capabilities);
|
|
340
|
+
say(`✓ 已连接 ${ctx.server},本机登记为「${reply.name}」(令牌:${reply.tokenName})`);
|
|
341
|
+
}
|
|
342
|
+
printDoctor(result);
|
|
343
|
+
if (!ctx.config.setupDone && interactive) {
|
|
344
|
+
const outcome = await runSetup({
|
|
345
|
+
plan: setupPlan(result, reply),
|
|
346
|
+
interactive: true,
|
|
347
|
+
confirm: (question) => askYesNo(question),
|
|
348
|
+
say,
|
|
349
|
+
});
|
|
350
|
+
// Asked once: missing items stay visible in status and on the website.
|
|
351
|
+
ctx.config.setupDone = true;
|
|
352
|
+
save(ctx);
|
|
353
|
+
if (outcome.ran) {
|
|
354
|
+
say('重新检查……');
|
|
355
|
+
result = await doctorFor(ctx);
|
|
356
|
+
reply = await connectSaved(ctx, client, result.capabilities);
|
|
357
|
+
printDoctor(result);
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
printFeatures(reply);
|
|
361
|
+
say('等待任务……(Ctrl+C 退出;后台运行:gitcode-agent-runner service install)');
|
|
362
|
+
return await serve(ctx, client, result, reply);
|
|
363
|
+
} finally {
|
|
364
|
+
lock.release();
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
async function serve(ctx, client, initial, reply) {
|
|
369
|
+
const controller = new AbortController();
|
|
370
|
+
let fatal = null;
|
|
371
|
+
const onFatal = (error) => {
|
|
372
|
+
const result = fatalFor(error);
|
|
373
|
+
if (result && !fatal) {
|
|
374
|
+
fatal = result;
|
|
375
|
+
controller.abort();
|
|
376
|
+
}
|
|
377
|
+
};
|
|
378
|
+
const jobs = new JobManager({
|
|
379
|
+
client,
|
|
380
|
+
skills: new SkillCache({ dir: ctx.paths.skillsDir, client }),
|
|
381
|
+
workRoot: ctx.workRoot,
|
|
382
|
+
claudePath: initial.claude.path,
|
|
383
|
+
realHome: ctx.realHome,
|
|
384
|
+
log,
|
|
385
|
+
onFatal,
|
|
386
|
+
});
|
|
387
|
+
let capabilities = initial.capabilities;
|
|
388
|
+
const doctorTimer = setInterval(async () => {
|
|
389
|
+
try {
|
|
390
|
+
const fresh = await doctorFor(ctx);
|
|
391
|
+
capabilities = fresh.capabilities;
|
|
392
|
+
if (fresh.claude.path) jobs.claudePath = fresh.claude.path;
|
|
393
|
+
} catch (error) {
|
|
394
|
+
log.warn(`定期检查失败:${error.message}`);
|
|
395
|
+
}
|
|
396
|
+
}, DOCTOR_INTERVAL_MS);
|
|
397
|
+
doctorTimer.unref();
|
|
398
|
+
let stopping = false;
|
|
399
|
+
const onSignal = (signal) => {
|
|
400
|
+
if (stopping) return;
|
|
401
|
+
stopping = true;
|
|
402
|
+
log.info(`收到 ${signal},正在停止(结束运行中的任务)……`);
|
|
403
|
+
controller.abort();
|
|
404
|
+
};
|
|
405
|
+
process.on('SIGINT', onSignal);
|
|
406
|
+
process.on('SIGTERM', onSignal);
|
|
407
|
+
const result = await runConnection({
|
|
408
|
+
client,
|
|
409
|
+
jobs,
|
|
410
|
+
log,
|
|
411
|
+
version: VERSION,
|
|
412
|
+
connect: () => connect(client, capabilities),
|
|
413
|
+
capabilities: { current: () => capabilities },
|
|
414
|
+
heartbeatMs: reply.heartbeatMs,
|
|
415
|
+
signal: controller.signal,
|
|
416
|
+
});
|
|
417
|
+
clearInterval(doctorTimer);
|
|
418
|
+
const outcome = fatal || result;
|
|
419
|
+
await jobs.stopAll(5000);
|
|
420
|
+
if (outcome.clearToken) {
|
|
421
|
+
ctx.config.token = '';
|
|
422
|
+
save(ctx);
|
|
423
|
+
}
|
|
424
|
+
if (outcome.code) log.error(outcome.message);
|
|
425
|
+
else log.info('已停止');
|
|
426
|
+
return outcome.code || 0;
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
async function login(values) {
|
|
430
|
+
checkSystem();
|
|
431
|
+
const restarted = await applyProxy();
|
|
432
|
+
if (restarted !== null) return restarted;
|
|
433
|
+
const ctx = loadContext(values);
|
|
434
|
+
if (values['new-id']) {
|
|
435
|
+
ctx.config.clientId = newClientId();
|
|
436
|
+
save(ctx);
|
|
437
|
+
say('已生成新的机器标识:这台机器在网页上会作为新机器出现');
|
|
438
|
+
}
|
|
439
|
+
if (!values['token-stdin'] && !isInteractive()) throw new ExitError(ATTENTION, 'login 需要在终端里运行(脚本里请用 --token-stdin)');
|
|
440
|
+
say('检查依赖和沙箱……');
|
|
441
|
+
const result = await doctorFor(ctx);
|
|
442
|
+
await obtainToken(ctx, { fromStdin: Boolean(values['token-stdin']), capabilities: result.capabilities });
|
|
443
|
+
return 0;
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
function logout(values) {
|
|
447
|
+
const ctx = loadContext(values, { workRoot: false });
|
|
448
|
+
const had = Boolean(ctx.config.token);
|
|
449
|
+
ctx.config.token = '';
|
|
450
|
+
save(ctx);
|
|
451
|
+
say(had ? '已清除本机保存的令牌(机器标识保留)' : '本机没有保存令牌');
|
|
452
|
+
return 0;
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
async function setup(values) {
|
|
456
|
+
checkSystem();
|
|
457
|
+
const restarted = await applyProxy();
|
|
458
|
+
if (restarted !== null) return restarted;
|
|
459
|
+
if (!isInteractive()) throw new ExitError(ATTENTION, 'setup 需要在终端里运行(安装前会请你确认)');
|
|
460
|
+
const ctx = loadContext(values);
|
|
461
|
+
say('检查依赖和沙箱……');
|
|
462
|
+
let result = await doctorFor(ctx);
|
|
463
|
+
let client = null;
|
|
464
|
+
let reply = null;
|
|
465
|
+
if (ctx.config.token) {
|
|
466
|
+
client = clientFor(ctx);
|
|
467
|
+
try {
|
|
468
|
+
reply = await connect(client, result.capabilities);
|
|
469
|
+
} catch (error) {
|
|
470
|
+
say(`无法从网站读取要求(${error.message}),按默认要求检查`);
|
|
471
|
+
client = null;
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
printDoctor(result);
|
|
475
|
+
const outcome = await runSetup({
|
|
476
|
+
plan: setupPlan(result, reply),
|
|
477
|
+
interactive: true,
|
|
478
|
+
yes: Boolean(values.yes),
|
|
479
|
+
confirm: (question) => askYesNo(question),
|
|
480
|
+
say,
|
|
481
|
+
});
|
|
482
|
+
ctx.config.setupDone = true;
|
|
483
|
+
save(ctx);
|
|
484
|
+
if (outcome.ran) {
|
|
485
|
+
say('重新检查……');
|
|
486
|
+
result = await doctorFor(ctx);
|
|
487
|
+
if (client) reply = await connect(client, result.capabilities).catch(() => reply);
|
|
488
|
+
printDoctor(result);
|
|
489
|
+
}
|
|
490
|
+
printFeatures(reply);
|
|
491
|
+
return outcome.failed.length ? 1 : 0;
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
async function doctor(values) {
|
|
495
|
+
checkSystem();
|
|
496
|
+
const restarted = await applyProxy();
|
|
497
|
+
if (restarted !== null) return restarted;
|
|
498
|
+
const ctx = loadContext(values);
|
|
499
|
+
const result = await doctorFor(ctx);
|
|
500
|
+
let reply = null;
|
|
501
|
+
let note = '';
|
|
502
|
+
if (ctx.config.token) {
|
|
503
|
+
try {
|
|
504
|
+
// Also brings the website's copy of this machine's capabilities up to date.
|
|
505
|
+
reply = await connect(clientFor(ctx), result.capabilities);
|
|
506
|
+
} catch (error) {
|
|
507
|
+
note = error instanceof ApiError && error.status === 401 ? '令牌无效或已删除' : `无法连接网站:${error instanceof ApiError ? error.message : networkReason(error)}`;
|
|
508
|
+
}
|
|
509
|
+
} else note = '还没有接入令牌,无法判断各功能(运行 gitcode-agent-runner login)';
|
|
510
|
+
if (values.json) {
|
|
511
|
+
say(JSON.stringify({ version: VERSION, capabilities: result.capabilities, claudePath: result.claude.path, features: reply?.features || null, note }, null, 2));
|
|
512
|
+
return 0;
|
|
513
|
+
}
|
|
514
|
+
say(`GitCode Agent 执行机器 ${VERSION} · Node ${process.versions.node} · ${process.platform}/${process.arch}`);
|
|
515
|
+
printDoctor(result);
|
|
516
|
+
printFeatures(reply);
|
|
517
|
+
if (note) say(note);
|
|
518
|
+
return 0;
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
async function status(values) {
|
|
522
|
+
checkSystem();
|
|
523
|
+
const restarted = await applyProxy();
|
|
524
|
+
if (restarted !== null) return restarted;
|
|
525
|
+
const ctx = loadContext(values, { workRoot: false });
|
|
526
|
+
const { config } = ctx;
|
|
527
|
+
say(`网站:${ctx.server}`);
|
|
528
|
+
say(`令牌:${config.token ? `${config.token.slice(0, 12)}…` : '未登录(运行 gitcode-agent-runner login)'}`);
|
|
529
|
+
say(`机器标识:${config.clientId}`);
|
|
530
|
+
say(`工作目录:${config.workRoot || defaultWorkRoot()}`);
|
|
531
|
+
say(`配置文件:${ctx.paths.configFile}`);
|
|
532
|
+
const service = serviceStatus();
|
|
533
|
+
say(`后台服务:${service.installed ? service.state : '未安装'}${service.installed ? `(${service.logHint})` : ''}`);
|
|
534
|
+
let holder = Number.NaN;
|
|
535
|
+
try {
|
|
536
|
+
holder = Number(fs.readFileSync(ctx.paths.lockFile, 'utf8').trim());
|
|
537
|
+
} catch {
|
|
538
|
+
// No lock.
|
|
539
|
+
}
|
|
540
|
+
say(`运行中的实例:${Number.isInteger(holder) && isRunnerAlive(holder) ? `pid ${holder}` : '无'}`);
|
|
541
|
+
if (!config.token) return 0;
|
|
542
|
+
try {
|
|
543
|
+
// A request with no effect: a registered machine gets 404 for an unknown version.
|
|
544
|
+
await clientFor(ctx).request('GET', `/skills/manifest?hash=${'0'.repeat(64)}`);
|
|
545
|
+
say('连接测试:正常');
|
|
546
|
+
} catch (error) {
|
|
547
|
+
if (error instanceof ApiError) {
|
|
548
|
+
const text = {
|
|
549
|
+
404: '正常',
|
|
550
|
+
401: '令牌无效或已删除(运行 gitcode-agent-runner login)',
|
|
551
|
+
403: '这台机器已被封禁',
|
|
552
|
+
409: '令牌有效,这台机器尚未登记(运行 gitcode-agent-runner 会自动登记)',
|
|
553
|
+
}[error.status] || error.message;
|
|
554
|
+
say(`连接测试:${text}`);
|
|
555
|
+
} else say(`连接测试:失败(${networkReason(error)})`);
|
|
556
|
+
}
|
|
557
|
+
return 0;
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
async function service(action, values) {
|
|
561
|
+
checkSystem();
|
|
562
|
+
if (action === 'install') {
|
|
563
|
+
const ctx = loadContext(values);
|
|
564
|
+
if (!ctx.config.token) {
|
|
565
|
+
if (!isInteractive()) throw new ExitError(ATTENTION, '还没有接入令牌:请先在终端运行 gitcode-agent-runner login');
|
|
566
|
+
const restarted = await applyProxy();
|
|
567
|
+
if (restarted !== null) return restarted;
|
|
568
|
+
say('检查依赖和沙箱……');
|
|
569
|
+
const result = await doctorFor(ctx);
|
|
570
|
+
await obtainToken(ctx, { capabilities: result.capabilities });
|
|
571
|
+
}
|
|
572
|
+
let holder = Number.NaN;
|
|
573
|
+
try {
|
|
574
|
+
holder = Number(fs.readFileSync(ctx.paths.lockFile, 'utf8').trim());
|
|
575
|
+
} catch {
|
|
576
|
+
// No lock.
|
|
577
|
+
}
|
|
578
|
+
if (Number.isInteger(holder) && isRunnerAlive(holder) && !process.env.GC_RUNNER_SERVICE) {
|
|
579
|
+
say(`注意:已有实例在运行(pid ${holder})。如果是前台运行的程序,请先按 Ctrl+C 停止它,否则服务无法启动。`);
|
|
580
|
+
}
|
|
581
|
+
installService({
|
|
582
|
+
nodePath: process.execPath,
|
|
583
|
+
entry: fs.realpathSync(ENTRY),
|
|
584
|
+
args: ['start', ...(values['allow-root'] ? ['--allow-root'] : [])],
|
|
585
|
+
say,
|
|
586
|
+
});
|
|
587
|
+
return 0;
|
|
588
|
+
}
|
|
589
|
+
if (action === 'uninstall') {
|
|
590
|
+
uninstallService({ say });
|
|
591
|
+
return 0;
|
|
592
|
+
}
|
|
593
|
+
if (action === 'status') {
|
|
594
|
+
const state = serviceStatus();
|
|
595
|
+
say(state.installed ? `后台服务:${state.state}` : '后台服务:未安装');
|
|
596
|
+
say(state.logHint);
|
|
597
|
+
return 0;
|
|
598
|
+
}
|
|
599
|
+
throw new ExitError(1, '用法:gitcode-agent-runner service install | uninstall | status');
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
async function main(argv) {
|
|
603
|
+
let parsed;
|
|
604
|
+
try {
|
|
605
|
+
parsed = parseArgs({
|
|
606
|
+
args: argv,
|
|
607
|
+
allowPositionals: true,
|
|
608
|
+
options: {
|
|
609
|
+
server: { type: 'string' },
|
|
610
|
+
'work-dir': { type: 'string' },
|
|
611
|
+
'allow-root': { type: 'boolean' },
|
|
612
|
+
'new-id': { type: 'boolean' },
|
|
613
|
+
'token-stdin': { type: 'boolean' },
|
|
614
|
+
yes: { type: 'boolean', short: 'y' },
|
|
615
|
+
json: { type: 'boolean' },
|
|
616
|
+
version: { type: 'boolean', short: 'v' },
|
|
617
|
+
help: { type: 'boolean', short: 'h' },
|
|
618
|
+
},
|
|
619
|
+
});
|
|
620
|
+
} catch (error) {
|
|
621
|
+
throw new ExitError(1, `${error.message}\n\n${USAGE}`);
|
|
622
|
+
}
|
|
623
|
+
const { values, positionals } = parsed;
|
|
624
|
+
if (values.version) return say(VERSION) ?? 0;
|
|
625
|
+
if (values.help) return say(USAGE) ?? 0;
|
|
626
|
+
const [command = 'start', action] = positionals;
|
|
627
|
+
switch (command) {
|
|
628
|
+
case 'start':
|
|
629
|
+
return start(values);
|
|
630
|
+
case 'login':
|
|
631
|
+
return login(values);
|
|
632
|
+
case 'logout':
|
|
633
|
+
return logout(values);
|
|
634
|
+
case 'setup':
|
|
635
|
+
return setup(values);
|
|
636
|
+
case 'doctor':
|
|
637
|
+
return doctor(values);
|
|
638
|
+
case 'status':
|
|
639
|
+
return status(values);
|
|
640
|
+
case 'service':
|
|
641
|
+
return service(action, values);
|
|
642
|
+
case 'version':
|
|
643
|
+
say(VERSION);
|
|
644
|
+
return 0;
|
|
645
|
+
case 'help':
|
|
646
|
+
say(USAGE);
|
|
647
|
+
return 0;
|
|
648
|
+
default:
|
|
649
|
+
throw new ExitError(1, `未知的命令:${command}\n\n${USAGE}`);
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
function finish(code) {
|
|
654
|
+
const exitCode = serviceExitCode(code);
|
|
655
|
+
// Let buffered output reach a pipe before exiting.
|
|
656
|
+
process.stdout.write('', () => process.exit(exitCode));
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
main(process.argv.slice(2)).then(
|
|
660
|
+
(code) => finish(Number.isInteger(code) ? code : 0),
|
|
661
|
+
(error) => {
|
|
662
|
+
if (error instanceof ExitError) {
|
|
663
|
+
if (error.message) process.stderr.write(`${error.message}\n`);
|
|
664
|
+
finish(error.code);
|
|
665
|
+
} else if (error instanceof CancelledError) {
|
|
666
|
+
finish(0);
|
|
667
|
+
} else if (error instanceof ConfigError || error instanceof WorkRootError) {
|
|
668
|
+
process.stderr.write(`${error.message}\n`);
|
|
669
|
+
finish(ATTENTION);
|
|
670
|
+
} else {
|
|
671
|
+
process.stderr.write(`出错:${error?.message || error}\n`);
|
|
672
|
+
finish(1);
|
|
673
|
+
}
|
|
674
|
+
},
|
|
675
|
+
);
|