@online-tools/agent-runner 0.0.0-stage → 0.0.1-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/lib/lock.mjs ADDED
@@ -0,0 +1,66 @@
1
+ // One running instance per user: run.lock holds the owner's pid. A lock
2
+ // whose pid is gone (or now belongs to some other program) is taken over.
3
+
4
+ import { spawnSync } from 'node:child_process';
5
+ import fs from 'node:fs';
6
+
7
+ export class LockedError extends Error {
8
+ constructor(pid) {
9
+ super(`已有实例在运行(pid ${pid},可能是后台服务,见 gitcode-agent-runner service status)`);
10
+ this.pid = pid;
11
+ }
12
+ }
13
+
14
+ /** True when `pid` is a live gitcode-agent-runner process (unknown commands count as live). */
15
+ export function isRunnerAlive(pid) {
16
+ if (!Number.isInteger(pid) || pid <= 0) return false;
17
+ try {
18
+ process.kill(pid, 0);
19
+ } catch (error) {
20
+ if (error.code !== 'EPERM') return false;
21
+ }
22
+ let command = '';
23
+ if (process.platform === 'linux') {
24
+ try {
25
+ command = fs.readFileSync(`/proc/${pid}/cmdline`, 'utf8');
26
+ } catch {
27
+ return true;
28
+ }
29
+ } else {
30
+ const result = spawnSync('ps', ['-o', 'command=', '-p', String(pid)], { encoding: 'utf8', timeout: 5000 });
31
+ if (result.status !== 0) return true;
32
+ command = result.stdout;
33
+ }
34
+ // A reused pid that runs something else is not our instance.
35
+ return command.includes('gitcode-agent-runner');
36
+ }
37
+
38
+ function owner(file) {
39
+ try {
40
+ return Number(fs.readFileSync(file, 'utf8').trim());
41
+ } catch {
42
+ return Number.NaN;
43
+ }
44
+ }
45
+
46
+ /** Takes the lock or throws LockedError. Returns { release() }. */
47
+ export function acquireLock(file, { pid = process.pid, isAlive = isRunnerAlive } = {}) {
48
+ const release = () => {
49
+ if (owner(file) === pid) fs.rmSync(file, { force: true });
50
+ };
51
+ for (let attempt = 0; attempt < 5; attempt += 1) {
52
+ try {
53
+ const fd = fs.openSync(file, 'wx', 0o600);
54
+ fs.writeSync(fd, String(pid));
55
+ fs.closeSync(fd);
56
+ return { release };
57
+ } catch (error) {
58
+ if (error.code !== 'EEXIST') throw error;
59
+ }
60
+ const holder = owner(file);
61
+ if (holder === pid) return { release };
62
+ if (Number.isInteger(holder) && holder > 0 && isAlive(holder)) throw new LockedError(holder);
63
+ fs.rmSync(file, { force: true }); // left behind by a dead instance
64
+ }
65
+ throw new Error(`无法获取运行锁 ${file}`);
66
+ }
package/lib/log.mjs ADDED
@@ -0,0 +1,22 @@
1
+ // Timestamped Chinese log lines on stdout / stderr (systemd puts them in the
2
+ // journal, launchd in ~/Library/Logs). Never log a token, an API key,
3
+ // GITCODE_CRED or a proxy password: use redactUrl() for anything URL-like.
4
+
5
+ function stamp(date = new Date()) {
6
+ const pad = (value) => String(value).padStart(2, '0');
7
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
8
+ }
9
+
10
+ export function createLogger({ out = process.stdout, err = process.stderr } = {}) {
11
+ const write = (stream, prefix, message) => stream.write(`${stamp()} ${prefix}${message}\n`);
12
+ return {
13
+ info: (message) => write(out, '', message),
14
+ warn: (message) => write(err, '警告:', message),
15
+ error: (message) => write(err, '错误:', message),
16
+ };
17
+ }
18
+
19
+ /** Masks the account part of URLs (proxy addresses may carry user:password). */
20
+ export function redactUrl(value) {
21
+ return String(value ?? '').replace(/(\/\/)[^/@\s]*@/g, '$1***@');
22
+ }
@@ -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
+ }