@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.
@@ -0,0 +1,226 @@
1
+ // Background service: a systemd user unit (Linux) or a launchd agent (macOS).
2
+ // Services do not inherit the shell environment, so PATH and the
3
+ // pass-through variables (proxies, CA bundles, language) present now are
4
+ // written into the definition (file mode 0600: proxy URLs may hold passwords).
5
+
6
+ import { spawnSync } from 'node:child_process';
7
+ import fs from 'node:fs';
8
+ import os from 'node:os';
9
+ import path from 'node:path';
10
+
11
+ import { PASS_THROUGH_VARIABLES, PROXY_VARIABLES } from './sandbox.mjs';
12
+ import { redactUrl } from './log.mjs';
13
+
14
+ export const SERVICE_NAME = 'work-agent-runner';
15
+ export const LAUNCHD_LABEL = 'site.closerouter.work-agent-runner';
16
+ // What the program installed until 0.0.1-alpha-4, as gitcode-agent-runner.
17
+ const LEGACY_SERVICE_NAME = 'gitcode-agent-runner';
18
+ const LEGACY_LAUNCHD_LABEL = 'site.closerouter.gitcode-agent-runner';
19
+ export const EXIT_NEEDS_ATTENTION = 78;
20
+
21
+ /** launchd cannot exempt one exit code from KeepAlive: 78 becomes 0 there. */
22
+ export function serviceExitCode(code, env = process.env) {
23
+ return code === EXIT_NEEDS_ATTENTION && env.GC_RUNNER_SERVICE === 'launchd' ? 0 : code;
24
+ }
25
+
26
+ /**
27
+ * PATH, the pass-through variables that are set, WORK_AGENT_HOME when this
28
+ * terminal has one (else the service would use a different knowledge pool than
29
+ * the user's own work-agent), NODE_USE_ENV_PROXY with a proxy, and the service
30
+ * marker.
31
+ */
32
+ export function serviceEnvironment(env, kind) {
33
+ const out = { PATH: env.PATH || '/usr/local/bin:/usr/bin:/bin' };
34
+ for (const name of PASS_THROUGH_VARIABLES) if (env[name]) out[name] = env[name];
35
+ if (env.WORK_AGENT_HOME) out.WORK_AGENT_HOME = env.WORK_AGENT_HOME;
36
+ if (PROXY_VARIABLES.some((name) => env[name] && !/^no_proxy$/i.test(name))) out.NODE_USE_ENV_PROXY = '1';
37
+ out.GC_RUNNER_SERVICE = kind;
38
+ return out;
39
+ }
40
+
41
+ /** "NAME=value" lines for the user to check, proxy credentials masked. */
42
+ export function describeEnvironment(environment) {
43
+ return Object.entries(environment).map(([name, value]) => `${name}=${PROXY_VARIABLES.includes(name) ? redactUrl(value) : value}`);
44
+ }
45
+
46
+ // systemd: one double-quoted word; % starts specifiers, \ and " are escaped.
47
+ function systemdWord(value) {
48
+ const text = String(value);
49
+ if (/[\n\r]/.test(text)) throw new Error('服务配置不能包含换行');
50
+ return `"${text.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/%/g, '%%')}"`;
51
+ }
52
+
53
+ function systemdExecWord(value) {
54
+ // ExecStart also expands $VAR.
55
+ return systemdWord(value).replace(/\$/g, '$$$$');
56
+ }
57
+
58
+ export function systemdUnit({ nodePath, entry, args = ['start'], environment }) {
59
+ const lines = [
60
+ '[Unit]',
61
+ 'Description=work-agent-runner(GitCode 在线工具执行机器)',
62
+ 'After=network-online.target',
63
+ 'Wants=network-online.target',
64
+ 'StartLimitIntervalSec=300',
65
+ 'StartLimitBurst=10',
66
+ '',
67
+ '[Service]',
68
+ 'Type=simple',
69
+ `ExecStart=${[nodePath, entry, ...args].map(systemdExecWord).join(' ')}`,
70
+ 'Restart=on-failure',
71
+ 'RestartSec=5',
72
+ `RestartPreventExitStatus=${EXIT_NEEDS_ATTENTION}`,
73
+ ...Object.entries(environment).map(([name, value]) => `Environment=${systemdWord(`${name}=${value}`)}`),
74
+ '',
75
+ '[Install]',
76
+ 'WantedBy=default.target',
77
+ '',
78
+ ];
79
+ return lines.join('\n');
80
+ }
81
+
82
+ function xml(value) {
83
+ return String(value).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
84
+ }
85
+
86
+ export function launchdPlist({ nodePath, entry, args = ['start'], environment, logFile }) {
87
+ const strings = (items) => items.map((item) => ` <string>${xml(item)}</string>`).join('\n');
88
+ const variables = Object.entries(environment)
89
+ .map(([name, value]) => ` <key>${xml(name)}</key>\n <string>${xml(value)}</string>`)
90
+ .join('\n');
91
+ return `<?xml version="1.0" encoding="UTF-8"?>
92
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
93
+ <plist version="1.0">
94
+ <dict>
95
+ <key>Label</key>
96
+ <string>${LAUNCHD_LABEL}</string>
97
+ <key>ProgramArguments</key>
98
+ <array>
99
+ ${strings([nodePath, entry, ...args])}
100
+ </array>
101
+ <key>EnvironmentVariables</key>
102
+ <dict>
103
+ ${variables}
104
+ </dict>
105
+ <key>RunAtLoad</key>
106
+ <true/>
107
+ <key>KeepAlive</key>
108
+ <dict>
109
+ <key>SuccessfulExit</key>
110
+ <false/>
111
+ </dict>
112
+ <key>StandardOutPath</key>
113
+ <string>${xml(logFile)}</string>
114
+ <key>StandardErrorPath</key>
115
+ <string>${xml(logFile)}</string>
116
+ </dict>
117
+ </plist>
118
+ `;
119
+ }
120
+
121
+ export function servicePaths({ platform = process.platform, home = os.homedir(), env = process.env } = {}) {
122
+ if (platform === 'darwin') {
123
+ const agents = path.join(home, 'Library', 'LaunchAgents');
124
+ return {
125
+ kind: 'launchd',
126
+ name: LAUNCHD_LABEL,
127
+ file: path.join(agents, `${LAUNCHD_LABEL}.plist`),
128
+ legacyName: LEGACY_LAUNCHD_LABEL,
129
+ legacyFile: path.join(agents, `${LEGACY_LAUNCHD_LABEL}.plist`),
130
+ logFile: path.join(home, 'Library', 'Logs', `${SERVICE_NAME}.log`),
131
+ };
132
+ }
133
+ const units = path.join(env.XDG_CONFIG_HOME || path.join(home, '.config'), 'systemd', 'user');
134
+ return {
135
+ kind: 'systemd',
136
+ name: SERVICE_NAME,
137
+ file: path.join(units, `${SERVICE_NAME}.service`),
138
+ legacyName: LEGACY_SERVICE_NAME,
139
+ legacyFile: path.join(units, `${LEGACY_SERVICE_NAME}.service`),
140
+ logFile: '',
141
+ };
142
+ }
143
+
144
+ function run(command, args, { quiet = false } = {}) {
145
+ const result = spawnSync(command, args, { encoding: 'utf8', stdio: quiet ? ['ignore', 'pipe', 'pipe'] : 'inherit' });
146
+ return { ok: result.status === 0, status: result.status, stdout: result.stdout || '', stderr: result.stderr || '', error: result.error };
147
+ }
148
+
149
+ /** Writes the definition (0600), loads it and (re)starts the service. */
150
+ export function installService({ platform = process.platform, nodePath, entry, args, env = process.env, say }) {
151
+ const paths = servicePaths({ platform, env });
152
+ const environment = serviceEnvironment(env, paths.kind);
153
+ say('服务将使用以下环境变量(来自当前终端):');
154
+ for (const line of describeEnvironment(environment)) say(` ${line}`);
155
+ fs.mkdirSync(path.dirname(paths.file), { recursive: true, mode: 0o700 });
156
+ if (paths.kind === 'launchd') {
157
+ fs.mkdirSync(path.dirname(paths.logFile), { recursive: true });
158
+ fs.writeFileSync(paths.file, launchdPlist({ nodePath, entry, args, environment, logFile: paths.logFile }), { mode: 0o600 });
159
+ fs.chmodSync(paths.file, 0o600);
160
+ const domain = `gui/${process.getuid()}`;
161
+ run('launchctl', ['bootout', `${domain}/${LAUNCHD_LABEL}`], { quiet: true }); // an older definition, if loaded
162
+ const loaded = run('launchctl', ['bootstrap', domain, paths.file]);
163
+ if (!loaded.ok) throw new Error('launchctl bootstrap 失败');
164
+ say(`已安装并启动后台服务(launchd)。日志:${paths.logFile}`);
165
+ return paths;
166
+ }
167
+ fs.writeFileSync(paths.file, systemdUnit({ nodePath, entry, args, environment }), { mode: 0o600 });
168
+ fs.chmodSync(paths.file, 0o600);
169
+ for (const command of [['daemon-reload'], ['enable', SERVICE_NAME], ['restart', SERVICE_NAME]]) {
170
+ const result = run('systemctl', ['--user', ...command]);
171
+ if (!result.ok) throw new Error(`systemctl --user ${command.join(' ')} 失败`);
172
+ }
173
+ say('已安装并启动后台服务(systemd 用户服务)。');
174
+ say('退出登录后服务会停止;要让它一直运行,请让管理员执行一次:loginctl enable-linger $USER');
175
+ say(`查看日志:journalctl --user -u ${SERVICE_NAME} -f`);
176
+ return paths;
177
+ }
178
+
179
+ /** Stops a service and deletes its definition; true when the definition existed. */
180
+ function removeService(kind, name, file) {
181
+ if (kind === 'launchd') run('launchctl', ['bootout', `gui/${process.getuid()}/${name}`], { quiet: true });
182
+ else run('systemctl', ['--user', 'disable', '--now', name], { quiet: true });
183
+ const existed = fs.existsSync(file);
184
+ fs.rmSync(file, { force: true });
185
+ if (kind === 'systemd') run('systemctl', ['--user', 'daemon-reload'], { quiet: true });
186
+ return existed;
187
+ }
188
+
189
+ /** Whether the old name's service (gitcode-agent-runner) is still installed. */
190
+ export function legacyServiceInstalled({ platform = process.platform, env = process.env } = {}) {
191
+ return fs.existsSync(servicePaths({ platform, env }).legacyFile);
192
+ }
193
+
194
+ /**
195
+ * Stops and deletes the old name's service, if installed: otherwise it keeps
196
+ * running the old program, or fails over and over once that package is gone.
197
+ * True when there was one.
198
+ */
199
+ export function removeLegacyService({ platform = process.platform, env = process.env, say }) {
200
+ const paths = servicePaths({ platform, env });
201
+ if (!fs.existsSync(paths.legacyFile)) return false;
202
+ removeService(paths.kind, paths.legacyName, paths.legacyFile);
203
+ say(`已停止并删除旧版程序的后台服务(${paths.legacyName})`);
204
+ return true;
205
+ }
206
+
207
+ export function uninstallService({ platform = process.platform, env = process.env, say }) {
208
+ const paths = servicePaths({ platform, env });
209
+ const legacy = removeLegacyService({ platform, env, say });
210
+ if (removeService(paths.kind, paths.name, paths.file)) say('已停止并删除后台服务');
211
+ else if (!legacy) say('没有安装后台服务');
212
+ }
213
+
214
+ /** { installed, state, logHint } */
215
+ export function serviceStatus({ platform = process.platform, env = process.env } = {}) {
216
+ const paths = servicePaths({ platform, env });
217
+ const installed = fs.existsSync(paths.file);
218
+ if (paths.kind === 'launchd') {
219
+ const result = run('launchctl', ['print', `gui/${process.getuid()}/${LAUNCHD_LABEL}`], { quiet: true });
220
+ const state = result.ok ? /state = (\w+)/.exec(result.stdout)?.[1] || '已加载' : '未加载';
221
+ return { installed, state, logHint: `日志:${paths.logFile}` };
222
+ }
223
+ const active = run('systemctl', ['--user', 'is-active', SERVICE_NAME], { quiet: true });
224
+ const state = active.error ? '无法读取(systemctl 不可用)' : active.stdout.trim() || 'unknown';
225
+ return { installed, state, logHint: `日志:journalctl --user -u ${SERVICE_NAME} -f` };
226
+ }
package/lib/setup.mjs ADDED
@@ -0,0 +1,155 @@
1
+ // `setup`: installs missing dependencies after the user confirms, in a
2
+ // terminal only (the background service never installs anything). What can
3
+ // be installed and the commands are fixed in packages.mjs; the website only
4
+ // names tools from that list (requiredTools). Commands run without a shell,
5
+ // one after another; a failure does not stop the rest.
6
+
7
+ import { spawn } from 'node:child_process';
8
+ import fs from 'node:fs';
9
+ import path from 'node:path';
10
+
11
+ import { CLAUDE_PACKAGE, PACKAGE_NAMES, SANDBOX_TOOLS, SKILL_TOOLS, installCommands } from './packages.mjs';
12
+
13
+ export const DEFAULT_REQUIRED_TOOLS = [...SKILL_TOOLS];
14
+
15
+ function compareVersions(a, b) {
16
+ const parse = (value) => (/^(\d+)\.(\d+)\.(\d+)/.exec(String(value)) || [0, 0, 0, 0]).slice(1, 4).map(Number);
17
+ const [x, y] = [parse(a), parse(b)];
18
+ for (let index = 0; index < 3; index += 1) if (x[index] !== y[index]) return x[index] < y[index] ? -1 : 1;
19
+ return 0;
20
+ }
21
+
22
+ /** Whether the npm global directory is writable by this user (else sudo). */
23
+ export function npmPrefixWritable(prefix) {
24
+ for (const dir of [path.join(prefix, 'lib', 'node_modules'), path.join(prefix, 'lib'), prefix]) {
25
+ try {
26
+ fs.accessSync(dir, fs.constants.W_OK);
27
+ return true;
28
+ } catch (error) {
29
+ if (error.code !== 'ENOENT') return false;
30
+ }
31
+ }
32
+ return false;
33
+ }
34
+
35
+ /**
36
+ * The install plan (pure; tested with fake inputs):
37
+ * requiredTools from the website (or DEFAULT_REQUIRED_TOOLS without a token)
38
+ * extraTools what this machine wants regardless of the website (rg for
39
+ * the knowledge pool); must also be in SKILL_TOOLS
40
+ * tools doctor's { [name]: { ok } }
41
+ * claudeVersion '' when missing
42
+ * manager 'apt' | … | 'brew' | ''
43
+ * isRoot, sudo absolute path of sudo or ''
44
+ * npm, npmWritable absolute path of npm, and whether its global dir is writable
45
+ * Returns { commands: [[file, ...args]], manual: [[...]], missing: [names], ignored: [names], notes: [text] }.
46
+ */
47
+ export function planSetup({
48
+ platform,
49
+ requiredTools = DEFAULT_REQUIRED_TOOLS,
50
+ extraTools = [],
51
+ tools,
52
+ claudeVersion = '',
53
+ minClaudeVersion = '',
54
+ manager = '',
55
+ isRoot = false,
56
+ sudo = '',
57
+ npm = '',
58
+ npmWritable = false,
59
+ }) {
60
+ const ignored = requiredTools.filter((name) => !SKILL_TOOLS.includes(name));
61
+ const wanted = SKILL_TOOLS.filter((name) => requiredTools.includes(name) || extraTools.includes(name));
62
+ if (platform === 'linux') wanted.push(...SANDBOX_TOOLS);
63
+ const missing = wanted.filter((name) => !tools?.[name]?.ok);
64
+ const notes = [];
65
+ if (ignored.length) notes.push(`网站要求的 ${ignored.join('、')} 不在本程序可安装的范围内,请升级程序:npm i -g @online-tools/work-agent-runner@latest`);
66
+
67
+ const commands = [];
68
+ const manual = [];
69
+ const names = PACKAGE_NAMES[manager] || null;
70
+ const packages = [];
71
+ for (const tool of missing) {
72
+ const name = names?.[tool];
73
+ if (name) packages.push(name);
74
+ else if (names && name === null) notes.push(`${tool} 应由系统自带,请检查系统环境`);
75
+ }
76
+ const unique = [...new Set(packages)];
77
+ if (missing.length && !manager) {
78
+ notes.push(
79
+ platform === 'darwin'
80
+ ? '没有找到 Homebrew(https://brew.sh);git 和 python3 也可以用 xcode-select --install 安装'
81
+ : '没有识别出包管理器,请让管理员手动安装缺少的软件',
82
+ );
83
+ }
84
+ const packageCommands = installCommands(manager, unique);
85
+ if (packageCommands.length) {
86
+ if (manager === 'brew') commands.push(...packageCommands); // Homebrew refuses sudo
87
+ else if (isRoot) commands.push(...packageCommands);
88
+ else if (sudo) commands.push(...packageCommands.map((command) => [sudo, ...command]));
89
+ else {
90
+ manual.push(...packageCommands.map((command) => ['sudo', ...command]));
91
+ notes.push('没有找到 sudo:以下命令需要管理员执行');
92
+ }
93
+ }
94
+
95
+ const needsClaude = !claudeVersion || (minClaudeVersion && compareVersions(claudeVersion, minClaudeVersion) < 0);
96
+ if (needsClaude) {
97
+ if (!npm) {
98
+ notes.push('没有找到 npm,无法安装 claude');
99
+ } else {
100
+ const command = [npm, 'install', '-g', CLAUDE_PACKAGE];
101
+ if (npmWritable || isRoot) commands.push(command);
102
+ else if (sudo) commands.push([sudo, ...command]);
103
+ else manual.push(['sudo', ...command]);
104
+ }
105
+ }
106
+ return { commands, manual, missing: needsClaude ? [...missing, 'claude'] : missing, ignored, notes };
107
+ }
108
+
109
+ export function formatCommand(command) {
110
+ return command.map((part) => (/^[\w@./:=+-]+$/.test(part) ? part : JSON.stringify(part))).join(' ');
111
+ }
112
+
113
+ /** Runs one command with the terminal attached (no shell); resolves with its exit code. */
114
+ export function runCommand(command) {
115
+ return new Promise((resolve) => {
116
+ const child = spawn(command[0], command.slice(1), { stdio: 'inherit' });
117
+ child.once('error', () => resolve(127));
118
+ child.once('close', (code) => resolve(code ?? 1));
119
+ });
120
+ }
121
+
122
+ /**
123
+ * Shows the plan, asks (unless `yes`), runs it. `interactive` false: prints
124
+ * what is missing and installs nothing. Returns { ran, failed: [commands] }.
125
+ */
126
+ export async function runSetup({ plan, interactive, yes = false, confirm, say, run = runCommand }) {
127
+ for (const note of plan.notes) say(` ${note}`);
128
+ if (plan.manual.length) {
129
+ say('需要管理员执行:');
130
+ for (const command of plan.manual) say(` ${formatCommand(command)}`);
131
+ }
132
+ if (!plan.commands.length) {
133
+ if (!plan.missing.length) say('依赖都已就绪');
134
+ return { ran: false, failed: [] };
135
+ }
136
+ if (!interactive) {
137
+ say('需要安装依赖:请在终端运行 work-agent-runner setup');
138
+ return { ran: false, failed: [] };
139
+ }
140
+ say('将执行以下命令:');
141
+ for (const command of plan.commands) say(` ${formatCommand(command)}`);
142
+ if (!yes && !(await confirm('是否执行?'))) {
143
+ say('已跳过安装;缺少的依赖只影响用到它的功能');
144
+ return { ran: false, failed: [] };
145
+ }
146
+ const failed = [];
147
+ for (const command of plan.commands) {
148
+ const code = await run(command);
149
+ if (code !== 0) {
150
+ failed.push(command);
151
+ say(`命令失败(退出码 ${code}):${formatCommand(command)}`);
152
+ }
153
+ }
154
+ return { ran: true, failed };
155
+ }
@@ -0,0 +1,29 @@
1
+ // How Skill text files are rewritten for a run, shared by the website
2
+ // (lib/skill-bundle.js, server runs) and the machine program
3
+ // (lib/work-agent.mjs), through lib/skill-tree.mjs.
4
+ //
5
+ // Only node: built-ins and files in this directory may be imported here, and
6
+ // importing must have no side effects.
7
+
8
+ import path from 'node:path';
9
+
10
+ export const TEXT_EXTENSIONS = new Set([
11
+ '.md', '.txt', '.sh', '.bash', '.py', '.js', '.mjs', '.cjs', '.ts',
12
+ '.json', '.yaml', '.yml', '.toml', '.ini', '.cfg', '.conf',
13
+ ]);
14
+
15
+ /** True for files whose text is rewritten (by extension, case-insensitive). */
16
+ export function isSkillTextFile(name) {
17
+ return TEXT_EXTENSIONS.has(path.extname(String(name || '')).toLowerCase());
18
+ }
19
+
20
+ // Agent clients scrub variables named *TOKEN*/*KEY*/*SECRET* from the
21
+ // environment, so Skills read the GitCode credential as GITCODE_CRED.
22
+ export function renameTokenVariable(text) {
23
+ return String(text).split('GITCODE_TOKEN').join('GITCODE_CRED');
24
+ }
25
+
26
+ /** Points the Skills' scratch directory `/tmp/work-agent` at the run's own directory. */
27
+ export function rewriteWorkAgentPath(text, replacement) {
28
+ return String(text).split('/tmp/work-agent').join(replacement);
29
+ }
@@ -0,0 +1,100 @@
1
+ // Reading a Skill tree and copying it into a run, shared by the website
2
+ // (lib/skill-bundle.js, for server runs) and the execution machine program
3
+ // (lib/work-agent.mjs, for jobs). One implementation, so a job's Skill copy is
4
+ // byte for byte what a server run gets from the same source.
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
+ import fs from 'node:fs';
10
+ import path from 'node:path';
11
+
12
+ import { isSkillTextFile, renameTokenVariable, rewriteWorkAgentPath } from './skill-text.mjs';
13
+
14
+ // Far above the real tree (work-agent f0588e8: 102 files, 2.4 MB, largest 1 MB).
15
+ // They are here to stop a source that is not what we think it is — a clone
16
+ // made with submodule.recurse=true pulls ~1 GB into the Skill tree.
17
+ export const MAX_FILES = 10_000;
18
+ export const MAX_FILE_BYTES = 100 * 1024 * 1024;
19
+ export const MAX_TOTAL_BYTES = 512 * 1024 * 1024;
20
+
21
+ /**
22
+ * Visits a Skill tree the way every consumer (server run copies, a machine's
23
+ * run copies) must see it:
24
+ * - symlinks are followed and reported as what they point to (dangling ones are skipped)
25
+ * - `.git` entries (nested submodule pointers into the source .git) are skipped
26
+ * - sockets / fifos / devices are skipped
27
+ * - a directory reached again through a symlink loop is not entered twice
28
+ * `onFile(relPath, absPath, stats)` gets every regular file; `onDir(relPath,
29
+ * absPath)` every directory ('' is the root) before its contents. Relative
30
+ * paths use '/'.
31
+ */
32
+ export function walkSkillTree(sourceDir, onFile, onDir = () => {}) {
33
+ const seen = new Set();
34
+ const walk = (dir, rel) => {
35
+ const real = fs.realpathSync(dir);
36
+ if (seen.has(real)) return; // symlink loop
37
+ seen.add(real);
38
+ onDir(rel, dir);
39
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
40
+ if (entry.name === '.git') continue;
41
+ const from = path.join(dir, entry.name);
42
+ const childRel = rel ? `${rel}/${entry.name}` : entry.name;
43
+ let stats;
44
+ try {
45
+ stats = fs.statSync(from); // follows symlinks
46
+ } catch {
47
+ continue; // dangling symlink
48
+ }
49
+ if (stats.isDirectory()) walk(from, childRel);
50
+ else if (stats.isFile()) onFile(childRel, from, stats);
51
+ }
52
+ seen.delete(real);
53
+ };
54
+ walk(sourceDir, '');
55
+ }
56
+
57
+ /**
58
+ * Copies `source` into `target` as plain files and directories only (0700 /
59
+ * 0600), so the run copy can never write back into the source repository (see
60
+ * walkSkillTree for what is followed and skipped). The directory layout is
61
+ * preserved, so relative references between Skills (`../gitcode-toolkit/...`)
62
+ * keep working. Throws when the tree is larger than the limits above.
63
+ */
64
+ export function copyTreeDetached(source, target, limits = {}) {
65
+ const maxFiles = limits.maxFiles ?? MAX_FILES;
66
+ const maxFileBytes = limits.maxFileBytes ?? MAX_FILE_BYTES;
67
+ const maxTotalBytes = limits.maxTotalBytes ?? MAX_TOTAL_BYTES;
68
+ let files = 0;
69
+ let bytes = 0;
70
+ walkSkillTree(
71
+ source,
72
+ (rel, from, stats) => {
73
+ files += 1;
74
+ bytes += stats.size;
75
+ if (files > maxFiles) throw new Error(`Skill 文件过多(超过 ${maxFiles} 个):${source} 可能不是 Skill 目录`);
76
+ if (stats.size > maxFileBytes) throw new Error(`Skill 文件过大:${rel}`);
77
+ if (bytes > maxTotalBytes) throw new Error(`Skill 目录过大(超过 ${Math.round(maxTotalBytes / 1048576)} MB):${source} 可能不是 Skill 目录`);
78
+ const to = path.join(target, rel);
79
+ fs.copyFileSync(from, to);
80
+ fs.chmodSync(to, (stats.mode & 0o777) | 0o600);
81
+ },
82
+ (rel) => fs.mkdirSync(path.join(target, rel), { recursive: true, mode: 0o700 }),
83
+ );
84
+ return { files, bytes };
85
+ }
86
+
87
+ /** Points `/tmp/work-agent` at the run's scratch dir and renames GITCODE_TOKEN (AGENTS.md 5.1). */
88
+ export function rewriteSkillPaths(directory, replacement) {
89
+ for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
90
+ const target = path.join(directory, entry.name);
91
+ if (entry.isDirectory()) {
92
+ rewriteSkillPaths(target, replacement);
93
+ continue;
94
+ }
95
+ if (!entry.isFile() || !isSkillTextFile(entry.name)) continue;
96
+ const text = fs.readFileSync(target, 'utf8');
97
+ if (!text.includes('/tmp/work-agent') && !text.includes('GITCODE_TOKEN')) continue;
98
+ fs.writeFileSync(target, renameTokenVariable(rewriteWorkAgentPath(text, replacement)));
99
+ }
100
+ }
@@ -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
+ }