@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.
@@ -0,0 +1,74 @@
1
+ // The only software `setup` may install, and how (Appendix C of the design).
2
+ // The website can only name tools from this list; anything else is ignored.
3
+
4
+ // Tools the Skills need (the website's requiredTools draws from these).
5
+ export const SKILL_TOOLS = ['git', 'curl', 'python3', 'jq', 'sed', 'base64'];
6
+ // What the Linux sandbox needs.
7
+ export const SANDBOX_TOOLS = ['bwrap', 'socat'];
8
+
9
+ const LINUX_PACKAGES = {
10
+ git: 'git',
11
+ curl: 'curl',
12
+ python3: 'python3',
13
+ jq: 'jq',
14
+ sed: 'sed',
15
+ base64: 'coreutils',
16
+ bwrap: 'bubblewrap',
17
+ socat: 'socat',
18
+ };
19
+
20
+ // null: comes with the system (macOS) or not needed there.
21
+ export const PACKAGE_NAMES = {
22
+ apt: LINUX_PACKAGES,
23
+ dnf: LINUX_PACKAGES,
24
+ yum: LINUX_PACKAGES,
25
+ zypper: LINUX_PACKAGES,
26
+ pacman: { ...LINUX_PACKAGES, python3: 'python' },
27
+ apk: LINUX_PACKAGES,
28
+ brew: { git: 'git', curl: null, python3: 'python', jq: 'jq', sed: null, base64: null, bwrap: null, socat: null },
29
+ };
30
+
31
+ export const LINUX_MANAGERS = ['apt', 'dnf', 'yum', 'zypper', 'pacman', 'apk'];
32
+ export const MANAGER_COMMANDS = {
33
+ apt: 'apt-get',
34
+ dnf: 'dnf',
35
+ yum: 'yum',
36
+ zypper: 'zypper',
37
+ pacman: 'pacman',
38
+ apk: 'apk',
39
+ brew: 'brew',
40
+ };
41
+
42
+ export const CLAUDE_PACKAGE = '@anthropic-ai/claude-code@latest';
43
+
44
+ /** The first package manager found (apt-get, dnf, yum, zypper, pacman, apk; brew on macOS). */
45
+ export function detectPackageManager({ platform = process.platform, which }) {
46
+ if (platform === 'darwin') return which('brew') ? 'brew' : '';
47
+ for (const manager of LINUX_MANAGERS) {
48
+ if (which(MANAGER_COMMANDS[manager])) return manager;
49
+ }
50
+ return '';
51
+ }
52
+
53
+ /** Install commands (argument arrays, run without a shell) for `packages`. */
54
+ export function installCommands(manager, packages) {
55
+ if (!packages.length) return [];
56
+ switch (manager) {
57
+ case 'apt':
58
+ return [['apt-get', 'update'], ['apt-get', 'install', '-y', ...packages]];
59
+ case 'dnf':
60
+ return [['dnf', 'install', '-y', ...packages]];
61
+ case 'yum':
62
+ return [['yum', 'install', '-y', ...packages]];
63
+ case 'zypper':
64
+ return [['zypper', '--non-interactive', 'install', ...packages]];
65
+ case 'pacman':
66
+ return [['pacman', '-S', '--needed', '--noconfirm', ...packages]];
67
+ case 'apk':
68
+ return [['apk', 'add', ...packages]];
69
+ case 'brew':
70
+ return [['brew', 'install', ...packages]];
71
+ default:
72
+ return [];
73
+ }
74
+ }
package/lib/prompt.mjs ADDED
@@ -0,0 +1,76 @@
1
+ // Terminal input: hidden token entry, yes/no questions, reading stdin.
2
+
3
+ import readline from 'node:readline';
4
+
5
+ export class CancelledError extends Error {
6
+ constructor() {
7
+ super('已取消');
8
+ }
9
+ }
10
+
11
+ export function isInteractive(input = process.stdin, output = process.stdout) {
12
+ return Boolean(input.isTTY && output.isTTY);
13
+ }
14
+
15
+ /** Reads one line without echoing it (raw mode). Ctrl+C rejects with CancelledError. */
16
+ export function readHidden(question, { input = process.stdin, output = process.stdout } = {}) {
17
+ return new Promise((resolve, reject) => {
18
+ output.write(question);
19
+ const wasRaw = Boolean(input.isRaw);
20
+ input.setRawMode?.(true);
21
+ input.setEncoding('utf8');
22
+ input.resume();
23
+ let value = '';
24
+ const finish = (settle) => {
25
+ input.off('data', onData);
26
+ input.setRawMode?.(wasRaw);
27
+ input.pause();
28
+ output.write('\n');
29
+ settle();
30
+ };
31
+ function onData(chunk) {
32
+ for (const char of chunk) {
33
+ if (char === '\r' || char === '\n') {
34
+ // Bracketed-paste markers and other escape sequences are not part of the token.
35
+ finish(() => resolve(value.replace(/\x1b\[[0-9;]*[~A-Za-z]/g, '').trim()));
36
+ return;
37
+ }
38
+ if (char === '\u0003') {
39
+ finish(() => reject(new CancelledError()));
40
+ return;
41
+ }
42
+ if (char === '\u0004' && !value) {
43
+ finish(() => resolve(''));
44
+ return;
45
+ }
46
+ if (char === '\u007f' || char === '\b') value = value.slice(0, -1);
47
+ else if (char >= ' ' || char === '\x1b') value += char;
48
+ }
49
+ }
50
+ input.on('data', onData);
51
+ });
52
+ }
53
+
54
+ /** [Y/n] question; an empty answer takes the default. */
55
+ export async function askYesNo(question, { defaultYes = true, input = process.stdin, output = process.stdout } = {}) {
56
+ const rl = readline.createInterface({ input, output });
57
+ try {
58
+ const answer = await new Promise((resolve) => rl.question(`${question} ${defaultYes ? '[Y/n]' : '[y/N]'} `, resolve));
59
+ const value = String(answer || '').trim().toLowerCase();
60
+ if (!value) return defaultYes;
61
+ return ['y', 'yes', '是', '好'].includes(value);
62
+ } finally {
63
+ rl.close();
64
+ }
65
+ }
66
+
67
+ /** Everything on stdin (for --token-stdin). */
68
+ export async function readStdin(input = process.stdin, limit = 64 * 1024) {
69
+ let data = '';
70
+ input.setEncoding('utf8');
71
+ for await (const chunk of input) {
72
+ data += chunk;
73
+ if (data.length > limit) break;
74
+ }
75
+ return data.trim();
76
+ }
@@ -0,0 +1,110 @@
1
+ // Claude Code sandbox settings for every job on this machine (passed with
2
+ // --settings, so project settings cannot weaken them) and the run directory
3
+ // layout they assume:
4
+ // <runDir>/settings.json --settings (outside the sandbox's writable area)
5
+ // <runDir>/claude-home/ CLAUDE_CONFIG_DIR (written by claude itself, unsandboxed)
6
+ // <runDir>/work/ cwd: the only place sandboxed commands may write
7
+ // .claude/skills/ the Skill copy (Edit denied)
8
+ // workagent/ what /tmp/work-agent in the Skills points to
9
+ // .home/ .tmp/ HOME and TMPDIR of the job
10
+ // Paths are real paths: claude's HOME is the run's, so `~` cannot be used,
11
+ // and on macOS /var is a symlink to /private/var.
12
+
13
+ import fs from 'node:fs';
14
+ import path from 'node:path';
15
+
16
+ // The Skills only talk to GitCode; claude's own model requests do not go
17
+ // through the sandbox. Changing this list means publishing a new program.
18
+ export const ALLOWED_DOMAINS = ['gitcode.com', '*.gitcode.com'];
19
+
20
+ function fromRoot(absolute) {
21
+ return absolute.replace(/^\/+/, '');
22
+ }
23
+
24
+ /** The settings object (Appendix D of the design). */
25
+ export function sandboxSettings({ workDir, realHome, readAllow = [] }) {
26
+ return {
27
+ sandbox: {
28
+ enabled: true,
29
+ // Without it claude would warn and run commands unsandboxed.
30
+ failIfUnavailable: true,
31
+ // Ignore the model's dangerouslyDisableSandbox (project settings cannot override this).
32
+ allowUnsandboxedCommands: false,
33
+ network: { allowedDomains: [...ALLOWED_DOMAINS], strictAllowlist: true },
34
+ filesystem: { allowRead: [...readAllow] },
35
+ credentials: { envVars: [{ name: 'ANTHROPIC_AUTH_TOKEN', mode: 'deny' }] },
36
+ },
37
+ permissions: {
38
+ deny: [
39
+ `Read(//${fromRoot(realHome)}/**)`,
40
+ `Edit(//${fromRoot(realHome)}/**)`,
41
+ `Edit(//${fromRoot(workDir)}/.claude/**)`,
42
+ ],
43
+ },
44
+ // Hooks run outside the sandbox.
45
+ disableAllHooks: true,
46
+ };
47
+ }
48
+
49
+ export function writeSandboxSettings(file, input) {
50
+ fs.writeFileSync(file, `${JSON.stringify(sandboxSettings(input), null, 2)}\n`, { mode: 0o600 });
51
+ }
52
+
53
+ /**
54
+ * Directories / files inside HOME that sandboxed commands still need to read:
55
+ * PATH entries (e.g. ~/.local/bin, nvm) and CA bundles passed through.
56
+ * Returns their real paths.
57
+ */
58
+ export function homeReadAllow({ realHome, pathEnv = '', caPaths = [] }) {
59
+ const allowed = new Set();
60
+ for (const entry of [...String(pathEnv).split(path.delimiter), ...caPaths]) {
61
+ if (!entry || !path.isAbsolute(entry)) continue;
62
+ let real;
63
+ try {
64
+ real = fs.realpathSync(entry);
65
+ } catch {
66
+ continue;
67
+ }
68
+ if (real === realHome || real.startsWith(`${realHome}/`)) allowed.add(real);
69
+ }
70
+ return [...allowed];
71
+ }
72
+
73
+ /** Creates the run directory tree (0700) and returns its paths. */
74
+ export function createRunLayout(runDir) {
75
+ fs.mkdirSync(runDir, { recursive: true, mode: 0o700 });
76
+ const workDir = path.join(runDir, 'work');
77
+ const layout = {
78
+ runDir,
79
+ settingsFile: path.join(runDir, 'settings.json'),
80
+ configDir: path.join(runDir, 'claude-home'),
81
+ workDir,
82
+ skillsDir: path.join(workDir, '.claude', 'skills'),
83
+ workAgentDir: path.join(workDir, 'workagent'),
84
+ homeDir: path.join(workDir, '.home'),
85
+ tmpDir: path.join(workDir, '.tmp'),
86
+ };
87
+ for (const dir of [layout.configDir, layout.skillsDir, layout.workAgentDir, layout.homeDir, layout.tmpDir]) {
88
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
89
+ }
90
+ return layout;
91
+ }
92
+
93
+ // Variables passed through to claude (and written into the background
94
+ // service): proxies, CA bundles, language and time zone. Nothing else from
95
+ // this machine's environment reaches a job.
96
+ export const PROXY_VARIABLES = ['HTTPS_PROXY', 'HTTP_PROXY', 'NO_PROXY', 'ALL_PROXY', 'https_proxy', 'http_proxy', 'no_proxy', 'all_proxy'];
97
+ export const CA_VARIABLES = ['NODE_EXTRA_CA_CERTS', 'SSL_CERT_FILE', 'SSL_CERT_DIR', 'REQUESTS_CA_BUNDLE', 'CURL_CA_BUNDLE', 'GIT_SSL_CAINFO'];
98
+ export const PASS_THROUGH_VARIABLES = [...PROXY_VARIABLES, ...CA_VARIABLES, 'LANG', 'LC_ALL', 'TZ'];
99
+
100
+ export function passThroughEnv(env = process.env, platform = process.platform) {
101
+ const passed = {};
102
+ for (const name of PASS_THROUGH_VARIABLES) if (env[name]) passed[name] = env[name];
103
+ if (!passed.LANG) passed.LANG = platform === 'darwin' ? 'en_US.UTF-8' : 'C.UTF-8';
104
+ return passed;
105
+ }
106
+
107
+ /** CA files / directories named by the pass-through variables. */
108
+ export function caPaths(env = process.env) {
109
+ return CA_VARIABLES.map((name) => env[name]).filter(Boolean);
110
+ }
@@ -0,0 +1,187 @@
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 = 'gitcode-agent-runner';
15
+ export const LAUNCHD_LABEL = 'site.closerouter.gitcode-agent-runner';
16
+ export const EXIT_NEEDS_ATTENTION = 78;
17
+
18
+ /** launchd cannot exempt one exit code from KeepAlive: 78 becomes 0 there. */
19
+ export function serviceExitCode(code, env = process.env) {
20
+ return code === EXIT_NEEDS_ATTENTION && env.GC_RUNNER_SERVICE === 'launchd' ? 0 : code;
21
+ }
22
+
23
+ /** PATH, the pass-through variables that are set, NODE_USE_ENV_PROXY with a proxy, and the service marker. */
24
+ export function serviceEnvironment(env, kind) {
25
+ const out = { PATH: env.PATH || '/usr/local/bin:/usr/bin:/bin' };
26
+ for (const name of PASS_THROUGH_VARIABLES) if (env[name]) out[name] = env[name];
27
+ if (PROXY_VARIABLES.some((name) => env[name] && !/^no_proxy$/i.test(name))) out.NODE_USE_ENV_PROXY = '1';
28
+ out.GC_RUNNER_SERVICE = kind;
29
+ return out;
30
+ }
31
+
32
+ /** "NAME=value" lines for the user to check, proxy credentials masked. */
33
+ export function describeEnvironment(environment) {
34
+ return Object.entries(environment).map(([name, value]) => `${name}=${PROXY_VARIABLES.includes(name) ? redactUrl(value) : value}`);
35
+ }
36
+
37
+ // systemd: one double-quoted word; % starts specifiers, \ and " are escaped.
38
+ function systemdWord(value) {
39
+ const text = String(value);
40
+ if (/[\n\r]/.test(text)) throw new Error('服务配置不能包含换行');
41
+ return `"${text.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/%/g, '%%')}"`;
42
+ }
43
+
44
+ function systemdExecWord(value) {
45
+ // ExecStart also expands $VAR.
46
+ return systemdWord(value).replace(/\$/g, '$$$$');
47
+ }
48
+
49
+ export function systemdUnit({ nodePath, entry, args = ['start'], environment }) {
50
+ const lines = [
51
+ '[Unit]',
52
+ 'Description=GitCode Agent Runner',
53
+ 'After=network-online.target',
54
+ 'Wants=network-online.target',
55
+ 'StartLimitIntervalSec=300',
56
+ 'StartLimitBurst=10',
57
+ '',
58
+ '[Service]',
59
+ 'Type=simple',
60
+ `ExecStart=${[nodePath, entry, ...args].map(systemdExecWord).join(' ')}`,
61
+ 'Restart=on-failure',
62
+ 'RestartSec=5',
63
+ `RestartPreventExitStatus=${EXIT_NEEDS_ATTENTION}`,
64
+ ...Object.entries(environment).map(([name, value]) => `Environment=${systemdWord(`${name}=${value}`)}`),
65
+ '',
66
+ '[Install]',
67
+ 'WantedBy=default.target',
68
+ '',
69
+ ];
70
+ return lines.join('\n');
71
+ }
72
+
73
+ function xml(value) {
74
+ return String(value).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
75
+ }
76
+
77
+ export function launchdPlist({ nodePath, entry, args = ['start'], environment, logFile }) {
78
+ const strings = (items) => items.map((item) => ` <string>${xml(item)}</string>`).join('\n');
79
+ const variables = Object.entries(environment)
80
+ .map(([name, value]) => ` <key>${xml(name)}</key>\n <string>${xml(value)}</string>`)
81
+ .join('\n');
82
+ return `<?xml version="1.0" encoding="UTF-8"?>
83
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
84
+ <plist version="1.0">
85
+ <dict>
86
+ <key>Label</key>
87
+ <string>${LAUNCHD_LABEL}</string>
88
+ <key>ProgramArguments</key>
89
+ <array>
90
+ ${strings([nodePath, entry, ...args])}
91
+ </array>
92
+ <key>EnvironmentVariables</key>
93
+ <dict>
94
+ ${variables}
95
+ </dict>
96
+ <key>RunAtLoad</key>
97
+ <true/>
98
+ <key>KeepAlive</key>
99
+ <dict>
100
+ <key>SuccessfulExit</key>
101
+ <false/>
102
+ </dict>
103
+ <key>StandardOutPath</key>
104
+ <string>${xml(logFile)}</string>
105
+ <key>StandardErrorPath</key>
106
+ <string>${xml(logFile)}</string>
107
+ </dict>
108
+ </plist>
109
+ `;
110
+ }
111
+
112
+ export function servicePaths({ platform = process.platform, home = os.homedir(), env = process.env } = {}) {
113
+ if (platform === 'darwin') {
114
+ return {
115
+ kind: 'launchd',
116
+ file: path.join(home, 'Library', 'LaunchAgents', `${LAUNCHD_LABEL}.plist`),
117
+ logFile: path.join(home, 'Library', 'Logs', `${SERVICE_NAME}.log`),
118
+ };
119
+ }
120
+ return {
121
+ kind: 'systemd',
122
+ file: path.join(env.XDG_CONFIG_HOME || path.join(home, '.config'), 'systemd', 'user', `${SERVICE_NAME}.service`),
123
+ logFile: '',
124
+ };
125
+ }
126
+
127
+ function run(command, args, { quiet = false } = {}) {
128
+ const result = spawnSync(command, args, { encoding: 'utf8', stdio: quiet ? ['ignore', 'pipe', 'pipe'] : 'inherit' });
129
+ return { ok: result.status === 0, status: result.status, stdout: result.stdout || '', stderr: result.stderr || '', error: result.error };
130
+ }
131
+
132
+ /** Writes the definition (0600), loads it and (re)starts the service. */
133
+ export function installService({ platform = process.platform, nodePath, entry, args, env = process.env, say }) {
134
+ const paths = servicePaths({ platform, env });
135
+ const environment = serviceEnvironment(env, paths.kind);
136
+ say('服务将使用以下环境变量(来自当前终端):');
137
+ for (const line of describeEnvironment(environment)) say(` ${line}`);
138
+ fs.mkdirSync(path.dirname(paths.file), { recursive: true, mode: 0o700 });
139
+ if (paths.kind === 'launchd') {
140
+ fs.mkdirSync(path.dirname(paths.logFile), { recursive: true });
141
+ fs.writeFileSync(paths.file, launchdPlist({ nodePath, entry, args, environment, logFile: paths.logFile }), { mode: 0o600 });
142
+ fs.chmodSync(paths.file, 0o600);
143
+ const domain = `gui/${process.getuid()}`;
144
+ run('launchctl', ['bootout', `${domain}/${LAUNCHD_LABEL}`], { quiet: true }); // an older definition, if loaded
145
+ const loaded = run('launchctl', ['bootstrap', domain, paths.file]);
146
+ if (!loaded.ok) throw new Error('launchctl bootstrap 失败');
147
+ say(`已安装并启动后台服务(launchd)。日志:${paths.logFile}`);
148
+ return paths;
149
+ }
150
+ fs.writeFileSync(paths.file, systemdUnit({ nodePath, entry, args, environment }), { mode: 0o600 });
151
+ fs.chmodSync(paths.file, 0o600);
152
+ for (const command of [['daemon-reload'], ['enable', SERVICE_NAME], ['restart', SERVICE_NAME]]) {
153
+ const result = run('systemctl', ['--user', ...command]);
154
+ if (!result.ok) throw new Error(`systemctl --user ${command.join(' ')} 失败`);
155
+ }
156
+ say('已安装并启动后台服务(systemd 用户服务)。');
157
+ say('退出登录后服务会停止;要让它一直运行,请让管理员执行一次:loginctl enable-linger $USER');
158
+ say(`查看日志:journalctl --user -u ${SERVICE_NAME} -f`);
159
+ return paths;
160
+ }
161
+
162
+ export function uninstallService({ platform = process.platform, env = process.env, say }) {
163
+ const paths = servicePaths({ platform, env });
164
+ if (paths.kind === 'launchd') {
165
+ run('launchctl', ['bootout', `gui/${process.getuid()}/${LAUNCHD_LABEL}`], { quiet: true });
166
+ } else {
167
+ run('systemctl', ['--user', 'disable', '--now', SERVICE_NAME], { quiet: true });
168
+ }
169
+ const existed = fs.existsSync(paths.file);
170
+ fs.rmSync(paths.file, { force: true });
171
+ if (paths.kind === 'systemd') run('systemctl', ['--user', 'daemon-reload'], { quiet: true });
172
+ say(existed ? '已停止并删除后台服务' : '没有安装后台服务');
173
+ }
174
+
175
+ /** { installed, state, logHint } */
176
+ export function serviceStatus({ platform = process.platform, env = process.env } = {}) {
177
+ const paths = servicePaths({ platform, env });
178
+ const installed = fs.existsSync(paths.file);
179
+ if (paths.kind === 'launchd') {
180
+ const result = run('launchctl', ['print', `gui/${process.getuid()}/${LAUNCHD_LABEL}`], { quiet: true });
181
+ const state = result.ok ? /state = (\w+)/.exec(result.stdout)?.[1] || '已加载' : '未加载';
182
+ return { installed, state, logHint: `日志:${paths.logFile}` };
183
+ }
184
+ const active = run('systemctl', ['--user', 'is-active', SERVICE_NAME], { quiet: true });
185
+ const state = active.error ? '无法读取(systemctl 不可用)' : active.stdout.trim() || 'unknown';
186
+ return { installed, state, logHint: `日志:journalctl --user -u ${SERVICE_NAME} -f` };
187
+ }
package/lib/setup.mjs ADDED
@@ -0,0 +1,152 @@
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
+ * tools doctor's { [name]: { ok } }
39
+ * claudeVersion '' when missing
40
+ * manager 'apt' | … | 'brew' | ''
41
+ * isRoot, sudo absolute path of sudo or ''
42
+ * npm, npmWritable absolute path of npm, and whether its global dir is writable
43
+ * Returns { commands: [[file, ...args]], manual: [[...]], missing: [names], ignored: [names], notes: [text] }.
44
+ */
45
+ export function planSetup({
46
+ platform,
47
+ requiredTools = DEFAULT_REQUIRED_TOOLS,
48
+ tools,
49
+ claudeVersion = '',
50
+ minClaudeVersion = '',
51
+ manager = '',
52
+ isRoot = false,
53
+ sudo = '',
54
+ npm = '',
55
+ npmWritable = false,
56
+ }) {
57
+ const ignored = requiredTools.filter((name) => !SKILL_TOOLS.includes(name));
58
+ const wanted = SKILL_TOOLS.filter((name) => requiredTools.includes(name));
59
+ if (platform === 'linux') wanted.push(...SANDBOX_TOOLS);
60
+ const missing = wanted.filter((name) => !tools?.[name]?.ok);
61
+ const notes = [];
62
+ if (ignored.length) notes.push(`网站要求的 ${ignored.join('、')} 不在本程序可安装的范围内,请升级程序:npm i -g @online-tools/agent-runner@latest`);
63
+
64
+ const commands = [];
65
+ const manual = [];
66
+ const names = PACKAGE_NAMES[manager] || null;
67
+ const packages = [];
68
+ for (const tool of missing) {
69
+ const name = names?.[tool];
70
+ if (name) packages.push(name);
71
+ else if (names && name === null) notes.push(`${tool} 应由系统自带,请检查系统环境`);
72
+ }
73
+ const unique = [...new Set(packages)];
74
+ if (missing.length && !manager) {
75
+ notes.push(
76
+ platform === 'darwin'
77
+ ? '没有找到 Homebrew(https://brew.sh);git 和 python3 也可以用 xcode-select --install 安装'
78
+ : '没有识别出包管理器,请让管理员手动安装缺少的软件',
79
+ );
80
+ }
81
+ const packageCommands = installCommands(manager, unique);
82
+ if (packageCommands.length) {
83
+ if (manager === 'brew') commands.push(...packageCommands); // Homebrew refuses sudo
84
+ else if (isRoot) commands.push(...packageCommands);
85
+ else if (sudo) commands.push(...packageCommands.map((command) => [sudo, ...command]));
86
+ else {
87
+ manual.push(...packageCommands.map((command) => ['sudo', ...command]));
88
+ notes.push('没有找到 sudo:以下命令需要管理员执行');
89
+ }
90
+ }
91
+
92
+ const needsClaude = !claudeVersion || (minClaudeVersion && compareVersions(claudeVersion, minClaudeVersion) < 0);
93
+ if (needsClaude) {
94
+ if (!npm) {
95
+ notes.push('没有找到 npm,无法安装 claude');
96
+ } else {
97
+ const command = [npm, 'install', '-g', CLAUDE_PACKAGE];
98
+ if (npmWritable || isRoot) commands.push(command);
99
+ else if (sudo) commands.push([sudo, ...command]);
100
+ else manual.push(['sudo', ...command]);
101
+ }
102
+ }
103
+ return { commands, manual, missing: needsClaude ? [...missing, 'claude'] : missing, ignored, notes };
104
+ }
105
+
106
+ export function formatCommand(command) {
107
+ return command.map((part) => (/^[\w@./:=+-]+$/.test(part) ? part : JSON.stringify(part))).join(' ');
108
+ }
109
+
110
+ /** Runs one command with the terminal attached (no shell); resolves with its exit code. */
111
+ export function runCommand(command) {
112
+ return new Promise((resolve) => {
113
+ const child = spawn(command[0], command.slice(1), { stdio: 'inherit' });
114
+ child.once('error', () => resolve(127));
115
+ child.once('close', (code) => resolve(code ?? 1));
116
+ });
117
+ }
118
+
119
+ /**
120
+ * Shows the plan, asks (unless `yes`), runs it. `interactive` false: prints
121
+ * what is missing and installs nothing. Returns { ran, failed: [commands] }.
122
+ */
123
+ export async function runSetup({ plan, interactive, yes = false, confirm, say, run = runCommand }) {
124
+ for (const note of plan.notes) say(` ${note}`);
125
+ if (plan.manual.length) {
126
+ say('需要管理员执行:');
127
+ for (const command of plan.manual) say(` ${formatCommand(command)}`);
128
+ }
129
+ if (!plan.commands.length) {
130
+ if (!plan.missing.length) say('依赖都已就绪');
131
+ return { ran: false, failed: [] };
132
+ }
133
+ if (!interactive) {
134
+ say('需要安装依赖:请在终端运行 gitcode-agent-runner setup');
135
+ return { ran: false, failed: [] };
136
+ }
137
+ say('将执行以下命令:');
138
+ for (const command of plan.commands) say(` ${formatCommand(command)}`);
139
+ if (!yes && !(await confirm('是否执行?'))) {
140
+ say('已跳过安装;缺少的依赖只影响用到它的功能');
141
+ return { ran: false, failed: [] };
142
+ }
143
+ const failed = [];
144
+ for (const command of plan.commands) {
145
+ const code = await run(command);
146
+ if (code !== 0) {
147
+ failed.push(command);
148
+ say(`命令失败(退出码 ${code}):${formatCommand(command)}`);
149
+ }
150
+ }
151
+ return { ran: true, failed };
152
+ }
@@ -0,0 +1,29 @@
1
+ // How Skill text files are rewritten for a run, shared by the website
2
+ // (lib/skill-bundle.js for server runs, lib/skill-manifest.js for the files
3
+ // sent to execution machines) and the machine program (lib/skills.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
+ }