@online-tools/work-agent-runner 0.0.0-stage → 0.0.1-alpha-5
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 +127 -2
- package/bin/main.mjs +775 -0
- package/bin/work-agent-runner.cjs +139 -0
- package/lib/claude-cli.mjs +85 -0
- package/lib/config.mjs +157 -0
- package/lib/connection.mjs +225 -0
- package/lib/doctor.mjs +289 -0
- package/lib/http.mjs +198 -0
- package/lib/jobs.mjs +505 -0
- package/lib/lock.mjs +70 -0
- package/lib/log.mjs +22 -0
- package/lib/node-runtime.cjs +594 -0
- package/lib/packages.mjs +74 -0
- package/lib/probe-model.mjs +129 -0
- package/lib/prompt.mjs +94 -0
- package/lib/sandbox.mjs +136 -0
- package/lib/service.mjs +220 -0
- package/lib/setup.mjs +152 -0
- package/lib/skill-text.mjs +29 -0
- package/lib/skills.mjs +211 -0
- package/lib/system-info.mjs +132 -0
- package/package.json +10 -4
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
// A stand-in model for the sandbox check (doctor.mjs probeSandbox): an
|
|
2
|
+
// Anthropic Messages API on 127.0.0.1 that answers Claude Code's first request
|
|
3
|
+
// with one Bash call, `echo <PROBE_MARKER>`, and everything else with a short
|
|
4
|
+
// text. Claude Code then runs that command in its sandbox exactly as in a job,
|
|
5
|
+
// so the check sees what a job would see (the sandbox only starts on the
|
|
6
|
+
// first command; a started claude proves little). No request leaves the
|
|
7
|
+
// machine and no key is involved.
|
|
8
|
+
|
|
9
|
+
import http from 'node:http';
|
|
10
|
+
|
|
11
|
+
export const PROBE_TOOL_ID = 'toolu_01GitcodeSandboxProbe';
|
|
12
|
+
export const PROBE_MARKER = 'gitcode-sandbox-probe-ok';
|
|
13
|
+
const BODY_LIMIT = 16 * 1024 * 1024;
|
|
14
|
+
|
|
15
|
+
function hasProbeResult(messages) {
|
|
16
|
+
return messages.some(
|
|
17
|
+
(message) =>
|
|
18
|
+
Array.isArray(message?.content) &&
|
|
19
|
+
message.content.some((block) => block?.type === 'tool_result' && block.tool_use_id === PROBE_TOOL_ID),
|
|
20
|
+
);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** The probe call for the main conversation (it offers Bash); text for anything else. */
|
|
24
|
+
export function probeReply(request) {
|
|
25
|
+
const messages = Array.isArray(request?.messages) ? request.messages : [];
|
|
26
|
+
const offersBash = Array.isArray(request?.tools) && request.tools.some((tool) => tool?.name === 'Bash');
|
|
27
|
+
if (offersBash && !hasProbeResult(messages)) {
|
|
28
|
+
return {
|
|
29
|
+
block: { type: 'tool_use', id: PROBE_TOOL_ID, name: 'Bash', input: { command: `echo ${PROBE_MARKER}`, description: 'Sandbox check' } },
|
|
30
|
+
stopReason: 'tool_use',
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
return { block: { type: 'text', text: 'ok' }, stopReason: 'end_turn' };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function send(res, status, body) {
|
|
37
|
+
res.writeHead(status, { 'content-type': 'application/json' });
|
|
38
|
+
res.end(JSON.stringify(body));
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function stream(res, message, { block, stopReason }) {
|
|
42
|
+
const events = [
|
|
43
|
+
{ type: 'message_start', message },
|
|
44
|
+
{
|
|
45
|
+
type: 'content_block_start',
|
|
46
|
+
index: 0,
|
|
47
|
+
content_block: block.type === 'tool_use' ? { ...block, input: {} } : { type: 'text', text: '' },
|
|
48
|
+
},
|
|
49
|
+
{
|
|
50
|
+
type: 'content_block_delta',
|
|
51
|
+
index: 0,
|
|
52
|
+
delta:
|
|
53
|
+
block.type === 'tool_use'
|
|
54
|
+
? { type: 'input_json_delta', partial_json: JSON.stringify(block.input) }
|
|
55
|
+
: { type: 'text_delta', text: block.text },
|
|
56
|
+
},
|
|
57
|
+
{ type: 'content_block_stop', index: 0 },
|
|
58
|
+
{ type: 'message_delta', delta: { stop_reason: stopReason, stop_sequence: null }, usage: { output_tokens: 1 } },
|
|
59
|
+
{ type: 'message_stop' },
|
|
60
|
+
];
|
|
61
|
+
res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-cache' });
|
|
62
|
+
for (const event of events) res.write(`event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`);
|
|
63
|
+
res.end();
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function handle(req, res, body) {
|
|
67
|
+
const url = String(req.url || '');
|
|
68
|
+
if (req.method !== 'POST' || !url.startsWith('/v1/messages')) {
|
|
69
|
+
send(res, 404, { type: 'error', error: { type: 'not_found_error', message: 'not found' } });
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
let request = {};
|
|
73
|
+
try {
|
|
74
|
+
request = JSON.parse(body || '{}');
|
|
75
|
+
} catch {
|
|
76
|
+
send(res, 400, { type: 'error', error: { type: 'invalid_request_error', message: 'invalid JSON' } });
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
if (url.startsWith('/v1/messages/count_tokens')) {
|
|
80
|
+
send(res, 200, { input_tokens: 1 });
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
const reply = probeReply(request);
|
|
84
|
+
const message = {
|
|
85
|
+
id: 'msg_gitcode_sandbox_probe',
|
|
86
|
+
type: 'message',
|
|
87
|
+
role: 'assistant',
|
|
88
|
+
model: typeof request.model === 'string' ? request.model : 'probe',
|
|
89
|
+
content: [],
|
|
90
|
+
stop_reason: null,
|
|
91
|
+
stop_sequence: null,
|
|
92
|
+
usage: { input_tokens: 1, output_tokens: 1 },
|
|
93
|
+
};
|
|
94
|
+
if (request.stream === true) stream(res, message, reply);
|
|
95
|
+
else send(res, 200, { ...message, content: [reply.block], stop_reason: reply.stopReason });
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** Starts the stand-in on a free port of 127.0.0.1: { baseUrl, close() }. */
|
|
99
|
+
export async function startProbeModel() {
|
|
100
|
+
const server = http.createServer((req, res) => {
|
|
101
|
+
const chunks = [];
|
|
102
|
+
let size = 0;
|
|
103
|
+
req.on('data', (chunk) => {
|
|
104
|
+
size += chunk.length;
|
|
105
|
+
if (size > BODY_LIMIT) {
|
|
106
|
+
send(res, 413, { type: 'error', error: { type: 'request_too_large', message: 'too large' } });
|
|
107
|
+
req.destroy();
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
chunks.push(chunk);
|
|
111
|
+
});
|
|
112
|
+
req.on('end', () => {
|
|
113
|
+
if (!res.headersSent) handle(req, res, Buffer.concat(chunks).toString('utf8'));
|
|
114
|
+
});
|
|
115
|
+
req.on('error', () => {});
|
|
116
|
+
});
|
|
117
|
+
await new Promise((resolve, reject) => {
|
|
118
|
+
server.once('error', reject);
|
|
119
|
+
server.listen(0, '127.0.0.1', resolve);
|
|
120
|
+
});
|
|
121
|
+
return {
|
|
122
|
+
baseUrl: `http://127.0.0.1:${server.address().port}`,
|
|
123
|
+
close: () =>
|
|
124
|
+
new Promise((resolve) => {
|
|
125
|
+
server.closeAllConnections();
|
|
126
|
+
server.close(() => resolve());
|
|
127
|
+
}),
|
|
128
|
+
};
|
|
129
|
+
}
|
package/lib/prompt.mjs
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
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
|
+
/** One line of visible text, trimmed; Ctrl+C / Ctrl+D reject with CancelledError. */
|
|
55
|
+
export function askText(question, { input = process.stdin, output = process.stdout } = {}) {
|
|
56
|
+
return new Promise((resolve, reject) => {
|
|
57
|
+
const rl = readline.createInterface({ input, output });
|
|
58
|
+
let answered = false;
|
|
59
|
+
rl.on('close', () => {
|
|
60
|
+
if (answered) return;
|
|
61
|
+
output.write('\n');
|
|
62
|
+
reject(new CancelledError());
|
|
63
|
+
});
|
|
64
|
+
rl.question(question, (answer) => {
|
|
65
|
+
answered = true;
|
|
66
|
+
rl.close();
|
|
67
|
+
resolve(String(answer || '').trim());
|
|
68
|
+
});
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** [Y/n] question; an empty answer takes the default. */
|
|
73
|
+
export async function askYesNo(question, { defaultYes = true, input = process.stdin, output = process.stdout } = {}) {
|
|
74
|
+
const rl = readline.createInterface({ input, output });
|
|
75
|
+
try {
|
|
76
|
+
const answer = await new Promise((resolve) => rl.question(`${question} ${defaultYes ? '[Y/n]' : '[y/N]'} `, resolve));
|
|
77
|
+
const value = String(answer || '').trim().toLowerCase();
|
|
78
|
+
if (!value) return defaultYes;
|
|
79
|
+
return ['y', 'yes', '是', '好'].includes(value);
|
|
80
|
+
} finally {
|
|
81
|
+
rl.close();
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Everything on stdin (for --token-stdin). */
|
|
86
|
+
export async function readStdin(input = process.stdin, limit = 64 * 1024) {
|
|
87
|
+
let data = '';
|
|
88
|
+
input.setEncoding('utf8');
|
|
89
|
+
for await (const chunk of input) {
|
|
90
|
+
data += chunk;
|
|
91
|
+
if (data.length > limit) break;
|
|
92
|
+
}
|
|
93
|
+
return data.trim();
|
|
94
|
+
}
|
package/lib/sandbox.mjs
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
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
|
+
// Claude Code's Linux sandbox bridges its network proxies into the sandbox
|
|
74
|
+
// through Unix sockets named $TMPDIR/claude-http-<16 hex>.sock and
|
|
75
|
+
// claude-socks-<16 hex>.sock, and a Unix socket path holds at most 107 bytes.
|
|
76
|
+
// With a longer TMPDIR every sandboxed command fails ("Failed to create bridge
|
|
77
|
+
// sockets"), so run directories are kept short: <work root>/runs/<7 characters>,
|
|
78
|
+
// TMPDIR <run>/work/.tmp. Jobs and the sandbox check use the same shape, so the
|
|
79
|
+
// check sees the same path lengths a job does.
|
|
80
|
+
const UNIX_SOCKET_PATH_MAX = 107;
|
|
81
|
+
const BRIDGE_SOCKET_NAME = '/claude-socks-0123456789abcdef.sock';
|
|
82
|
+
const RUN_TMP_SUFFIX = '/runs/r123456/work/.tmp';
|
|
83
|
+
export const WORK_ROOT_MAX_BYTES = UNIX_SOCKET_PATH_MAX - BRIDGE_SOCKET_NAME.length - RUN_TMP_SUFFIX.length;
|
|
84
|
+
|
|
85
|
+
/** Why the sandbox cannot start with this TMPDIR ('' = it can). Linux only: macOS bridges over TCP. */
|
|
86
|
+
export function socketPathProblem(tmpDir, platform = process.platform) {
|
|
87
|
+
if (platform !== 'linux') return '';
|
|
88
|
+
const bytes = Buffer.byteLength(String(tmpDir)) + BRIDGE_SOCKET_NAME.length;
|
|
89
|
+
if (bytes <= UNIX_SOCKET_PATH_MAX) return '';
|
|
90
|
+
return `工作目录的路径太长:沙箱的通信 socket 路径要 ${bytes} 字节,超过 Linux 的上限 ${UNIX_SOCKET_PATH_MAX};请用 --work-dir 换一个不超过 ${WORK_ROOT_MAX_BYTES} 字节的目录`;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** A new, empty run directory <runsDir>/<prefix + 6 random characters> (0700); `prefix` is one character. */
|
|
94
|
+
export function newRunDir(runsDir, prefix) {
|
|
95
|
+
fs.mkdirSync(runsDir, { recursive: true, mode: 0o700 });
|
|
96
|
+
return fs.mkdtempSync(path.join(runsDir, prefix));
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Creates the run directory tree (0700) and returns its paths. */
|
|
100
|
+
export function createRunLayout(runDir) {
|
|
101
|
+
fs.mkdirSync(runDir, { recursive: true, mode: 0o700 });
|
|
102
|
+
const workDir = path.join(runDir, 'work');
|
|
103
|
+
const layout = {
|
|
104
|
+
runDir,
|
|
105
|
+
settingsFile: path.join(runDir, 'settings.json'),
|
|
106
|
+
configDir: path.join(runDir, 'claude-home'),
|
|
107
|
+
workDir,
|
|
108
|
+
skillsDir: path.join(workDir, '.claude', 'skills'),
|
|
109
|
+
workAgentDir: path.join(workDir, 'workagent'),
|
|
110
|
+
homeDir: path.join(workDir, '.home'),
|
|
111
|
+
tmpDir: path.join(workDir, '.tmp'),
|
|
112
|
+
};
|
|
113
|
+
for (const dir of [layout.configDir, layout.skillsDir, layout.workAgentDir, layout.homeDir, layout.tmpDir]) {
|
|
114
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
115
|
+
}
|
|
116
|
+
return layout;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// Variables passed through to claude (and written into the background
|
|
120
|
+
// service): proxies, CA bundles, language and time zone. Nothing else from
|
|
121
|
+
// this machine's environment reaches a job.
|
|
122
|
+
export const PROXY_VARIABLES = ['HTTPS_PROXY', 'HTTP_PROXY', 'NO_PROXY', 'ALL_PROXY', 'https_proxy', 'http_proxy', 'no_proxy', 'all_proxy'];
|
|
123
|
+
export const CA_VARIABLES = ['NODE_EXTRA_CA_CERTS', 'SSL_CERT_FILE', 'SSL_CERT_DIR', 'REQUESTS_CA_BUNDLE', 'CURL_CA_BUNDLE', 'GIT_SSL_CAINFO'];
|
|
124
|
+
export const PASS_THROUGH_VARIABLES = [...PROXY_VARIABLES, ...CA_VARIABLES, 'LANG', 'LC_ALL', 'TZ'];
|
|
125
|
+
|
|
126
|
+
export function passThroughEnv(env = process.env, platform = process.platform) {
|
|
127
|
+
const passed = {};
|
|
128
|
+
for (const name of PASS_THROUGH_VARIABLES) if (env[name]) passed[name] = env[name];
|
|
129
|
+
if (!passed.LANG) passed.LANG = platform === 'darwin' ? 'en_US.UTF-8' : 'C.UTF-8';
|
|
130
|
+
return passed;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** CA files / directories named by the pass-through variables. */
|
|
134
|
+
export function caPaths(env = process.env) {
|
|
135
|
+
return CA_VARIABLES.map((name) => env[name]).filter(Boolean);
|
|
136
|
+
}
|
package/lib/service.mjs
ADDED
|
@@ -0,0 +1,220 @@
|
|
|
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
|
+
/** PATH, the pass-through variables that are set, NODE_USE_ENV_PROXY with a proxy, and the service marker. */
|
|
27
|
+
export function serviceEnvironment(env, kind) {
|
|
28
|
+
const out = { PATH: env.PATH || '/usr/local/bin:/usr/bin:/bin' };
|
|
29
|
+
for (const name of PASS_THROUGH_VARIABLES) if (env[name]) out[name] = env[name];
|
|
30
|
+
if (PROXY_VARIABLES.some((name) => env[name] && !/^no_proxy$/i.test(name))) out.NODE_USE_ENV_PROXY = '1';
|
|
31
|
+
out.GC_RUNNER_SERVICE = kind;
|
|
32
|
+
return out;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** "NAME=value" lines for the user to check, proxy credentials masked. */
|
|
36
|
+
export function describeEnvironment(environment) {
|
|
37
|
+
return Object.entries(environment).map(([name, value]) => `${name}=${PROXY_VARIABLES.includes(name) ? redactUrl(value) : value}`);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// systemd: one double-quoted word; % starts specifiers, \ and " are escaped.
|
|
41
|
+
function systemdWord(value) {
|
|
42
|
+
const text = String(value);
|
|
43
|
+
if (/[\n\r]/.test(text)) throw new Error('服务配置不能包含换行');
|
|
44
|
+
return `"${text.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/%/g, '%%')}"`;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function systemdExecWord(value) {
|
|
48
|
+
// ExecStart also expands $VAR.
|
|
49
|
+
return systemdWord(value).replace(/\$/g, '$$$$');
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function systemdUnit({ nodePath, entry, args = ['start'], environment }) {
|
|
53
|
+
const lines = [
|
|
54
|
+
'[Unit]',
|
|
55
|
+
'Description=work-agent-runner(GitCode 在线工具执行机器)',
|
|
56
|
+
'After=network-online.target',
|
|
57
|
+
'Wants=network-online.target',
|
|
58
|
+
'StartLimitIntervalSec=300',
|
|
59
|
+
'StartLimitBurst=10',
|
|
60
|
+
'',
|
|
61
|
+
'[Service]',
|
|
62
|
+
'Type=simple',
|
|
63
|
+
`ExecStart=${[nodePath, entry, ...args].map(systemdExecWord).join(' ')}`,
|
|
64
|
+
'Restart=on-failure',
|
|
65
|
+
'RestartSec=5',
|
|
66
|
+
`RestartPreventExitStatus=${EXIT_NEEDS_ATTENTION}`,
|
|
67
|
+
...Object.entries(environment).map(([name, value]) => `Environment=${systemdWord(`${name}=${value}`)}`),
|
|
68
|
+
'',
|
|
69
|
+
'[Install]',
|
|
70
|
+
'WantedBy=default.target',
|
|
71
|
+
'',
|
|
72
|
+
];
|
|
73
|
+
return lines.join('\n');
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function xml(value) {
|
|
77
|
+
return String(value).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export function launchdPlist({ nodePath, entry, args = ['start'], environment, logFile }) {
|
|
81
|
+
const strings = (items) => items.map((item) => ` <string>${xml(item)}</string>`).join('\n');
|
|
82
|
+
const variables = Object.entries(environment)
|
|
83
|
+
.map(([name, value]) => ` <key>${xml(name)}</key>\n <string>${xml(value)}</string>`)
|
|
84
|
+
.join('\n');
|
|
85
|
+
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
86
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
87
|
+
<plist version="1.0">
|
|
88
|
+
<dict>
|
|
89
|
+
<key>Label</key>
|
|
90
|
+
<string>${LAUNCHD_LABEL}</string>
|
|
91
|
+
<key>ProgramArguments</key>
|
|
92
|
+
<array>
|
|
93
|
+
${strings([nodePath, entry, ...args])}
|
|
94
|
+
</array>
|
|
95
|
+
<key>EnvironmentVariables</key>
|
|
96
|
+
<dict>
|
|
97
|
+
${variables}
|
|
98
|
+
</dict>
|
|
99
|
+
<key>RunAtLoad</key>
|
|
100
|
+
<true/>
|
|
101
|
+
<key>KeepAlive</key>
|
|
102
|
+
<dict>
|
|
103
|
+
<key>SuccessfulExit</key>
|
|
104
|
+
<false/>
|
|
105
|
+
</dict>
|
|
106
|
+
<key>StandardOutPath</key>
|
|
107
|
+
<string>${xml(logFile)}</string>
|
|
108
|
+
<key>StandardErrorPath</key>
|
|
109
|
+
<string>${xml(logFile)}</string>
|
|
110
|
+
</dict>
|
|
111
|
+
</plist>
|
|
112
|
+
`;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export function servicePaths({ platform = process.platform, home = os.homedir(), env = process.env } = {}) {
|
|
116
|
+
if (platform === 'darwin') {
|
|
117
|
+
const agents = path.join(home, 'Library', 'LaunchAgents');
|
|
118
|
+
return {
|
|
119
|
+
kind: 'launchd',
|
|
120
|
+
name: LAUNCHD_LABEL,
|
|
121
|
+
file: path.join(agents, `${LAUNCHD_LABEL}.plist`),
|
|
122
|
+
legacyName: LEGACY_LAUNCHD_LABEL,
|
|
123
|
+
legacyFile: path.join(agents, `${LEGACY_LAUNCHD_LABEL}.plist`),
|
|
124
|
+
logFile: path.join(home, 'Library', 'Logs', `${SERVICE_NAME}.log`),
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
const units = path.join(env.XDG_CONFIG_HOME || path.join(home, '.config'), 'systemd', 'user');
|
|
128
|
+
return {
|
|
129
|
+
kind: 'systemd',
|
|
130
|
+
name: SERVICE_NAME,
|
|
131
|
+
file: path.join(units, `${SERVICE_NAME}.service`),
|
|
132
|
+
legacyName: LEGACY_SERVICE_NAME,
|
|
133
|
+
legacyFile: path.join(units, `${LEGACY_SERVICE_NAME}.service`),
|
|
134
|
+
logFile: '',
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function run(command, args, { quiet = false } = {}) {
|
|
139
|
+
const result = spawnSync(command, args, { encoding: 'utf8', stdio: quiet ? ['ignore', 'pipe', 'pipe'] : 'inherit' });
|
|
140
|
+
return { ok: result.status === 0, status: result.status, stdout: result.stdout || '', stderr: result.stderr || '', error: result.error };
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** Writes the definition (0600), loads it and (re)starts the service. */
|
|
144
|
+
export function installService({ platform = process.platform, nodePath, entry, args, env = process.env, say }) {
|
|
145
|
+
const paths = servicePaths({ platform, env });
|
|
146
|
+
const environment = serviceEnvironment(env, paths.kind);
|
|
147
|
+
say('服务将使用以下环境变量(来自当前终端):');
|
|
148
|
+
for (const line of describeEnvironment(environment)) say(` ${line}`);
|
|
149
|
+
fs.mkdirSync(path.dirname(paths.file), { recursive: true, mode: 0o700 });
|
|
150
|
+
if (paths.kind === 'launchd') {
|
|
151
|
+
fs.mkdirSync(path.dirname(paths.logFile), { recursive: true });
|
|
152
|
+
fs.writeFileSync(paths.file, launchdPlist({ nodePath, entry, args, environment, logFile: paths.logFile }), { mode: 0o600 });
|
|
153
|
+
fs.chmodSync(paths.file, 0o600);
|
|
154
|
+
const domain = `gui/${process.getuid()}`;
|
|
155
|
+
run('launchctl', ['bootout', `${domain}/${LAUNCHD_LABEL}`], { quiet: true }); // an older definition, if loaded
|
|
156
|
+
const loaded = run('launchctl', ['bootstrap', domain, paths.file]);
|
|
157
|
+
if (!loaded.ok) throw new Error('launchctl bootstrap 失败');
|
|
158
|
+
say(`已安装并启动后台服务(launchd)。日志:${paths.logFile}`);
|
|
159
|
+
return paths;
|
|
160
|
+
}
|
|
161
|
+
fs.writeFileSync(paths.file, systemdUnit({ nodePath, entry, args, environment }), { mode: 0o600 });
|
|
162
|
+
fs.chmodSync(paths.file, 0o600);
|
|
163
|
+
for (const command of [['daemon-reload'], ['enable', SERVICE_NAME], ['restart', SERVICE_NAME]]) {
|
|
164
|
+
const result = run('systemctl', ['--user', ...command]);
|
|
165
|
+
if (!result.ok) throw new Error(`systemctl --user ${command.join(' ')} 失败`);
|
|
166
|
+
}
|
|
167
|
+
say('已安装并启动后台服务(systemd 用户服务)。');
|
|
168
|
+
say('退出登录后服务会停止;要让它一直运行,请让管理员执行一次:loginctl enable-linger $USER');
|
|
169
|
+
say(`查看日志:journalctl --user -u ${SERVICE_NAME} -f`);
|
|
170
|
+
return paths;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** Stops a service and deletes its definition; true when the definition existed. */
|
|
174
|
+
function removeService(kind, name, file) {
|
|
175
|
+
if (kind === 'launchd') run('launchctl', ['bootout', `gui/${process.getuid()}/${name}`], { quiet: true });
|
|
176
|
+
else run('systemctl', ['--user', 'disable', '--now', name], { quiet: true });
|
|
177
|
+
const existed = fs.existsSync(file);
|
|
178
|
+
fs.rmSync(file, { force: true });
|
|
179
|
+
if (kind === 'systemd') run('systemctl', ['--user', 'daemon-reload'], { quiet: true });
|
|
180
|
+
return existed;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** Whether the old name's service (gitcode-agent-runner) is still installed. */
|
|
184
|
+
export function legacyServiceInstalled({ platform = process.platform, env = process.env } = {}) {
|
|
185
|
+
return fs.existsSync(servicePaths({ platform, env }).legacyFile);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Stops and deletes the old name's service, if installed: otherwise it keeps
|
|
190
|
+
* running the old program, or fails over and over once that package is gone.
|
|
191
|
+
* True when there was one.
|
|
192
|
+
*/
|
|
193
|
+
export function removeLegacyService({ platform = process.platform, env = process.env, say }) {
|
|
194
|
+
const paths = servicePaths({ platform, env });
|
|
195
|
+
if (!fs.existsSync(paths.legacyFile)) return false;
|
|
196
|
+
removeService(paths.kind, paths.legacyName, paths.legacyFile);
|
|
197
|
+
say(`已停止并删除旧版程序的后台服务(${paths.legacyName})`);
|
|
198
|
+
return true;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
export function uninstallService({ platform = process.platform, env = process.env, say }) {
|
|
202
|
+
const paths = servicePaths({ platform, env });
|
|
203
|
+
const legacy = removeLegacyService({ platform, env, say });
|
|
204
|
+
if (removeService(paths.kind, paths.name, paths.file)) say('已停止并删除后台服务');
|
|
205
|
+
else if (!legacy) say('没有安装后台服务');
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** { installed, state, logHint } */
|
|
209
|
+
export function serviceStatus({ platform = process.platform, env = process.env } = {}) {
|
|
210
|
+
const paths = servicePaths({ platform, env });
|
|
211
|
+
const installed = fs.existsSync(paths.file);
|
|
212
|
+
if (paths.kind === 'launchd') {
|
|
213
|
+
const result = run('launchctl', ['print', `gui/${process.getuid()}/${LAUNCHD_LABEL}`], { quiet: true });
|
|
214
|
+
const state = result.ok ? /state = (\w+)/.exec(result.stdout)?.[1] || '已加载' : '未加载';
|
|
215
|
+
return { installed, state, logHint: `日志:${paths.logFile}` };
|
|
216
|
+
}
|
|
217
|
+
const active = run('systemctl', ['--user', 'is-active', SERVICE_NAME], { quiet: true });
|
|
218
|
+
const state = active.error ? '无法读取(systemctl 不可用)' : active.stdout.trim() || 'unknown';
|
|
219
|
+
return { installed, state, logHint: `日志:journalctl --user -u ${SERVICE_NAME} -f` };
|
|
220
|
+
}
|