@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.
- package/LICENSE +21 -0
- package/README.md +187 -2
- package/bin/main.mjs +990 -0
- package/bin/work-agent-runner.cjs +139 -0
- package/lib/claude-cli.mjs +85 -0
- package/lib/config.mjs +238 -0
- package/lib/connection.mjs +225 -0
- package/lib/doctor.mjs +316 -0
- package/lib/http.mjs +198 -0
- package/lib/jobs.mjs +527 -0
- package/lib/lock.mjs +70 -0
- package/lib/log.mjs +22 -0
- package/lib/node-runtime.cjs +595 -0
- package/lib/packages.mjs +78 -0
- package/lib/probe-model.mjs +129 -0
- package/lib/prompt.mjs +94 -0
- package/lib/sandbox.mjs +265 -0
- package/lib/service.mjs +226 -0
- package/lib/setup.mjs +155 -0
- package/lib/skill-text.mjs +29 -0
- package/lib/skill-tree.mjs +100 -0
- package/lib/system-info.mjs +132 -0
- package/lib/work-agent.mjs +486 -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,265 @@
|
|
|
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 (never writable: not in allowWrite)
|
|
5
|
+
// <runDir>/claude-home/ CLAUDE_CONFIG_DIR (claude's own state)
|
|
6
|
+
// <runDir>/work-agent/ cwd: a full copy of this machine's work-agent
|
|
7
|
+
// clone, so a job works inside a work-agent
|
|
8
|
+
// repository without being able to touch the real
|
|
9
|
+
// one. .claude/** stays Edit-denied.
|
|
10
|
+
// <runDir>/.home/ HOME of the job, with .work-agent -> the program's
|
|
11
|
+
// persistent WORK_AGENT_HOME, so the Skills' own
|
|
12
|
+
// `~/.work-agent/...` and $WORK_AGENT_HOME are the
|
|
13
|
+
// same directory (linkWorkAgentHome)
|
|
14
|
+
// <runDir>/.tmp/ TMPDIR (the sandbox's bridge sockets live here)
|
|
15
|
+
//
|
|
16
|
+
// Jobs now run inside the program's home (~/.work-agent-runner), so the
|
|
17
|
+
// sandbox is told exactly which subtrees to open instead of being kept out of
|
|
18
|
+
// the home directory wholesale: the four writable directories above, the
|
|
19
|
+
// persistent WORK_AGENT_HOME, and the knowledge pool read-only. Everything
|
|
20
|
+
// else in the home directory stays closed, and the paths that must never be
|
|
21
|
+
// read by a job (the real clone, config.json with the token) are named in
|
|
22
|
+
// permissions.deny as well.
|
|
23
|
+
//
|
|
24
|
+
// Paths are real paths: claude's HOME is the run's, so `~` cannot be used,
|
|
25
|
+
// and on macOS /var is a symlink to /private/var.
|
|
26
|
+
|
|
27
|
+
import fs from 'node:fs';
|
|
28
|
+
import path from 'node:path';
|
|
29
|
+
|
|
30
|
+
// The Skills only talk to GitCode; claude's own model requests do not go
|
|
31
|
+
// through the sandbox. Changing this list means publishing a new program.
|
|
32
|
+
export const ALLOWED_DOMAINS = ['gitcode.com', '*.gitcode.com'];
|
|
33
|
+
|
|
34
|
+
function fromRoot(absolute) {
|
|
35
|
+
return absolute.replace(/^\/+/, '');
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// Directories in the home that a job must never read, whatever else it may
|
|
39
|
+
// reach: credentials, keys and shell history. The operating system sandbox is
|
|
40
|
+
// the real boundary (nothing is readable unless it is in allowRead); this list
|
|
41
|
+
// is the second one, at the tool layer, where deny beats any allow.
|
|
42
|
+
export const SENSITIVE_HOME_PATHS = [
|
|
43
|
+
'.ssh',
|
|
44
|
+
'.gnupg',
|
|
45
|
+
'.aws',
|
|
46
|
+
'.azure',
|
|
47
|
+
'.gcloud',
|
|
48
|
+
'.kube',
|
|
49
|
+
'.docker',
|
|
50
|
+
'.config',
|
|
51
|
+
'.netrc',
|
|
52
|
+
'.npmrc',
|
|
53
|
+
'.pypirc',
|
|
54
|
+
'.git-credentials',
|
|
55
|
+
'.gitconfig',
|
|
56
|
+
'.bash_history',
|
|
57
|
+
'.zsh_history',
|
|
58
|
+
];
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* The settings object. `readAllow` / `writeAllow` are real paths (see
|
|
62
|
+
* runAllowances); `deny` keeps the Read and Edit tools away from credentials,
|
|
63
|
+
* from the program's own files (the token, the real clone) and from the Skill
|
|
64
|
+
* copy of this run.
|
|
65
|
+
*/
|
|
66
|
+
export function sandboxSettings({ workDir, realHome, readAllow = [], writeAllow = [], deny = [] }) {
|
|
67
|
+
return {
|
|
68
|
+
sandbox: {
|
|
69
|
+
enabled: true,
|
|
70
|
+
// Without it claude would warn and run commands unsandboxed.
|
|
71
|
+
failIfUnavailable: true,
|
|
72
|
+
// Ignore the model's dangerouslyDisableSandbox (project settings cannot override this).
|
|
73
|
+
allowUnsandboxedCommands: false,
|
|
74
|
+
network: { allowedDomains: [...ALLOWED_DOMAINS], strictAllowlist: true },
|
|
75
|
+
filesystem: { allowRead: [...readAllow], allowWrite: [...writeAllow] },
|
|
76
|
+
credentials: { envVars: [{ name: 'ANTHROPIC_AUTH_TOKEN', mode: 'deny' }] },
|
|
77
|
+
},
|
|
78
|
+
permissions: {
|
|
79
|
+
deny: [
|
|
80
|
+
...SENSITIVE_HOME_PATHS.flatMap((name) => [
|
|
81
|
+
`Read(//${fromRoot(realHome)}/${name})`,
|
|
82
|
+
`Read(//${fromRoot(realHome)}/${name}/**)`,
|
|
83
|
+
`Edit(//${fromRoot(realHome)}/${name})`,
|
|
84
|
+
`Edit(//${fromRoot(realHome)}/${name}/**)`,
|
|
85
|
+
]),
|
|
86
|
+
...deny,
|
|
87
|
+
`Edit(//${fromRoot(workDir)}/.claude/**)`,
|
|
88
|
+
],
|
|
89
|
+
},
|
|
90
|
+
// Hooks run outside the sandbox.
|
|
91
|
+
disableAllHooks: true,
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* What one job may read and write: the four directories of its run, the
|
|
97
|
+
* program's persistent WORK_AGENT_HOME (the Skills' logs, scratch and
|
|
98
|
+
* deliverables), the knowledge pool read-only, and — inside the home directory
|
|
99
|
+
* — the PATH entries and CA bundles a command needs to run at all. Also the
|
|
100
|
+
* `deny` entries for the program's own files. All as real paths.
|
|
101
|
+
*/
|
|
102
|
+
export function runAllowances(layout, { realHome, pathEnv = '', caPaths = [], pool = '', paths = null }) {
|
|
103
|
+
const runDirs = [layout.workDir, layout.homeDir, layout.tmpDir, layout.configDir].map((dir) => realpathOr(dir));
|
|
104
|
+
const workAgentHome = layout.workAgentHome ? realpathOr(layout.workAgentHome) : '';
|
|
105
|
+
const writeAllow = [...runDirs, ...(workAgentHome ? [workAgentHome] : [])];
|
|
106
|
+
const readAllow = [
|
|
107
|
+
...writeAllow,
|
|
108
|
+
...(pool ? [realpathOr(pool)] : []),
|
|
109
|
+
...homeReadAllow({ realHome, pathEnv, caPaths }),
|
|
110
|
+
];
|
|
111
|
+
const deny = [];
|
|
112
|
+
if (paths) {
|
|
113
|
+
// The access token, and the clone every job copies from.
|
|
114
|
+
for (const file of [paths.configFile, paths.repoDir]) {
|
|
115
|
+
deny.push(`Read(//${fromRoot(path.resolve(file))}/**)`, `Read(//${fromRoot(path.resolve(file))})`);
|
|
116
|
+
deny.push(`Edit(//${fromRoot(path.resolve(file))}/**)`, `Edit(//${fromRoot(path.resolve(file))})`);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
// The pool is shared with the user's own work-agent: read it, never write it.
|
|
120
|
+
if (pool) deny.push(`Edit(//${fromRoot(realpathOr(pool))}/**)`);
|
|
121
|
+
return { readAllow: [...new Set(readAllow)], writeAllow: [...new Set(writeAllow)], deny };
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function realpathOr(value) {
|
|
125
|
+
try {
|
|
126
|
+
return fs.realpathSync(value);
|
|
127
|
+
} catch {
|
|
128
|
+
return path.resolve(value);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export function writeSandboxSettings(file, input) {
|
|
133
|
+
fs.writeFileSync(file, `${JSON.stringify(sandboxSettings(input), null, 2)}\n`, { mode: 0o600 });
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Directories / files inside HOME that sandboxed commands still need to read:
|
|
138
|
+
* PATH entries (e.g. ~/.local/bin, nvm), CA bundles passed through, and
|
|
139
|
+
* `extra` (the knowledge pool, which lives in ~/.work-agent by default).
|
|
140
|
+
* Returns their real paths. Entries outside HOME are dropped — they need no
|
|
141
|
+
* exception, since the sandbox only closes HOME.
|
|
142
|
+
*/
|
|
143
|
+
export function homeReadAllow({ realHome, pathEnv = '', caPaths = [], extra = [] }) {
|
|
144
|
+
const allowed = new Set();
|
|
145
|
+
for (const entry of [...String(pathEnv).split(path.delimiter), ...caPaths, ...extra]) {
|
|
146
|
+
if (!entry || !path.isAbsolute(entry)) continue;
|
|
147
|
+
let real;
|
|
148
|
+
try {
|
|
149
|
+
real = fs.realpathSync(entry);
|
|
150
|
+
} catch {
|
|
151
|
+
continue;
|
|
152
|
+
}
|
|
153
|
+
if (real === realHome || real.startsWith(`${realHome}/`)) allowed.add(real);
|
|
154
|
+
}
|
|
155
|
+
return [...allowed];
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
// Claude Code's Linux sandbox bridges its network proxies into the sandbox
|
|
159
|
+
// through Unix sockets named $TMPDIR/claude-http-<16 hex>.sock and
|
|
160
|
+
// claude-socks-<16 hex>.sock, and a Unix socket path holds at most 107 bytes.
|
|
161
|
+
// With a longer TMPDIR every sandboxed command fails ("Failed to create bridge
|
|
162
|
+
// sockets"), so run directories are kept short: <work root>/runs/<7 characters>,
|
|
163
|
+
// TMPDIR <run>/work/.tmp. Jobs and the sandbox check use the same shape, so the
|
|
164
|
+
// check sees the same path lengths a job does.
|
|
165
|
+
const UNIX_SOCKET_PATH_MAX = 107;
|
|
166
|
+
const BRIDGE_SOCKET_NAME = '/claude-socks-0123456789abcdef.sock';
|
|
167
|
+
const RUN_TMP_SUFFIX = '/runs/r123456/.tmp';
|
|
168
|
+
export const WORK_ROOT_MAX_BYTES = UNIX_SOCKET_PATH_MAX - BRIDGE_SOCKET_NAME.length - RUN_TMP_SUFFIX.length;
|
|
169
|
+
|
|
170
|
+
/** Why the sandbox cannot start with this TMPDIR ('' = it can). Linux only: macOS bridges over TCP. */
|
|
171
|
+
export function socketPathProblem(tmpDir, platform = process.platform) {
|
|
172
|
+
if (platform !== 'linux') return '';
|
|
173
|
+
const bytes = Buffer.byteLength(String(tmpDir)) + BRIDGE_SOCKET_NAME.length;
|
|
174
|
+
if (bytes <= UNIX_SOCKET_PATH_MAX) return '';
|
|
175
|
+
return `工作目录的路径太长:沙箱的通信 socket 路径要 ${bytes} 字节,超过 Linux 的上限 ${UNIX_SOCKET_PATH_MAX};请用 --work-dir 换一个不超过 ${WORK_ROOT_MAX_BYTES} 字节的目录`;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** A new, empty run directory <runsDir>/<prefix + 6 random characters> (0700); `prefix` is one character. */
|
|
179
|
+
export function newRunDir(runsDir, prefix) {
|
|
180
|
+
fs.mkdirSync(runsDir, { recursive: true, mode: 0o700 });
|
|
181
|
+
return fs.mkdtempSync(path.join(runsDir, prefix));
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* Creates the run directory tree (0700) and returns its paths. `workAgentHome`
|
|
186
|
+
* is the program's persistent WORK_AGENT_HOME; the job's HOME gets a
|
|
187
|
+
* `.work-agent` symlink to it, so a Skill's `~/.work-agent/...` and
|
|
188
|
+
* `$WORK_AGENT_HOME` are one directory.
|
|
189
|
+
*/
|
|
190
|
+
export function createRunLayout(runDir, { workAgentHome = '' } = {}) {
|
|
191
|
+
fs.mkdirSync(runDir, { recursive: true, mode: 0o700 });
|
|
192
|
+
const layout = {
|
|
193
|
+
runDir,
|
|
194
|
+
settingsFile: path.join(runDir, 'settings.json'),
|
|
195
|
+
configDir: path.join(runDir, 'claude-home'),
|
|
196
|
+
// cwd: a copy of the work-agent repository, Skills included.
|
|
197
|
+
workDir: path.join(runDir, 'work-agent'),
|
|
198
|
+
homeDir: path.join(runDir, '.home'),
|
|
199
|
+
tmpDir: path.join(runDir, '.tmp'),
|
|
200
|
+
workAgentHome,
|
|
201
|
+
};
|
|
202
|
+
layout.skillsDir = path.join(layout.workDir, '.claude', 'skills');
|
|
203
|
+
for (const dir of [layout.configDir, layout.workDir, layout.homeDir, layout.tmpDir]) {
|
|
204
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
205
|
+
}
|
|
206
|
+
if (workAgentHome) {
|
|
207
|
+
fs.symlinkSync(path.resolve(workAgentHome), path.join(layout.homeDir, '.work-agent'));
|
|
208
|
+
}
|
|
209
|
+
return layout;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* Creates the program's persistent WORK_AGENT_HOME: `logs/ tmp/ docs/` for the
|
|
214
|
+
* Skills to write, and `ascend-repos` pointing at the shared knowledge pool
|
|
215
|
+
* (work-agent's own documented way of putting the pool on another disk). The
|
|
216
|
+
* pool stays outside this directory, so a job cannot delete it.
|
|
217
|
+
*/
|
|
218
|
+
export function prepareWorkAgentHome(workAgentHome, poolDir = '') {
|
|
219
|
+
for (const name of ['logs', 'tmp', 'docs']) {
|
|
220
|
+
fs.mkdirSync(path.join(workAgentHome, name), { recursive: true, mode: 0o700 });
|
|
221
|
+
}
|
|
222
|
+
const link = path.join(workAgentHome, 'ascend-repos');
|
|
223
|
+
if (!poolDir) return '';
|
|
224
|
+
let real;
|
|
225
|
+
try {
|
|
226
|
+
real = fs.realpathSync(poolDir);
|
|
227
|
+
} catch {
|
|
228
|
+
return '';
|
|
229
|
+
}
|
|
230
|
+
let current = '';
|
|
231
|
+
try {
|
|
232
|
+
current = fs.readlinkSync(link);
|
|
233
|
+
} catch {
|
|
234
|
+
// Not a symlink, or missing.
|
|
235
|
+
}
|
|
236
|
+
if (current !== real) {
|
|
237
|
+
if (current) fs.rmSync(link, { force: true });
|
|
238
|
+
try {
|
|
239
|
+
fs.symlinkSync(real, link);
|
|
240
|
+
} catch (error) {
|
|
241
|
+
// A real directory there (someone cloned into it): leave it alone.
|
|
242
|
+
if (error.code !== 'EEXIST') throw error;
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
return real;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// Variables passed through to claude (and written into the background
|
|
249
|
+
// service): proxies, CA bundles, language and time zone. Nothing else from
|
|
250
|
+
// this machine's environment reaches a job.
|
|
251
|
+
export const PROXY_VARIABLES = ['HTTPS_PROXY', 'HTTP_PROXY', 'NO_PROXY', 'ALL_PROXY', 'https_proxy', 'http_proxy', 'no_proxy', 'all_proxy'];
|
|
252
|
+
export const CA_VARIABLES = ['NODE_EXTRA_CA_CERTS', 'SSL_CERT_FILE', 'SSL_CERT_DIR', 'REQUESTS_CA_BUNDLE', 'CURL_CA_BUNDLE', 'GIT_SSL_CAINFO'];
|
|
253
|
+
export const PASS_THROUGH_VARIABLES = [...PROXY_VARIABLES, ...CA_VARIABLES, 'LANG', 'LC_ALL', 'TZ'];
|
|
254
|
+
|
|
255
|
+
export function passThroughEnv(env = process.env, platform = process.platform) {
|
|
256
|
+
const passed = {};
|
|
257
|
+
for (const name of PASS_THROUGH_VARIABLES) if (env[name]) passed[name] = env[name];
|
|
258
|
+
if (!passed.LANG) passed.LANG = platform === 'darwin' ? 'en_US.UTF-8' : 'C.UTF-8';
|
|
259
|
+
return passed;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/** CA files / directories named by the pass-through variables. */
|
|
263
|
+
export function caPaths(env = process.env) {
|
|
264
|
+
return CA_VARIABLES.map((name) => env[name]).filter(Boolean);
|
|
265
|
+
}
|