@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
package/lib/doctor.mjs
ADDED
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
// What this machine can do: tools on PATH, claude and its version, the
|
|
2
|
+
// package manager, and whether a command really runs in the Claude Code
|
|
3
|
+
// sandbox. The result is reported to the website as `capabilities` (it
|
|
4
|
+
// decides which features run).
|
|
5
|
+
|
|
6
|
+
import { spawn, spawnSync } from 'node:child_process';
|
|
7
|
+
import fs from 'node:fs';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import readline from 'node:readline';
|
|
10
|
+
|
|
11
|
+
import { claudeArgs, claudeEnv } from './claude-cli.mjs';
|
|
12
|
+
import { SANDBOX_TOOLS, SKILL_TOOLS, detectPackageManager } from './packages.mjs';
|
|
13
|
+
import { PROBE_MARKER, PROBE_TOOL_ID, startProbeModel } from './probe-model.mjs';
|
|
14
|
+
import {
|
|
15
|
+
caPaths,
|
|
16
|
+
createRunLayout,
|
|
17
|
+
homeReadAllow,
|
|
18
|
+
newRunDir,
|
|
19
|
+
passThroughEnv,
|
|
20
|
+
socketPathProblem,
|
|
21
|
+
writeSandboxSettings,
|
|
22
|
+
} from './sandbox.mjs';
|
|
23
|
+
|
|
24
|
+
export const PROBE_TIMEOUT_MS = 60_000;
|
|
25
|
+
export const SANDBOX_DOCS = 'https://code.claude.com/docs/en/sandboxing';
|
|
26
|
+
|
|
27
|
+
function isExecutableFile(file) {
|
|
28
|
+
try {
|
|
29
|
+
fs.accessSync(file, fs.constants.X_OK);
|
|
30
|
+
return fs.statSync(file).isFile();
|
|
31
|
+
} catch {
|
|
32
|
+
return false;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Absolute path of `name` on PATH, or ''. */
|
|
37
|
+
export function which(name, pathEnv = process.env.PATH) {
|
|
38
|
+
for (const dir of String(pathEnv || '').split(path.delimiter)) {
|
|
39
|
+
if (!dir || !path.isAbsolute(dir)) continue;
|
|
40
|
+
const candidate = path.join(dir, name);
|
|
41
|
+
if (isExecutableFile(candidate)) return candidate;
|
|
42
|
+
}
|
|
43
|
+
return '';
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** First group of `pattern` in `file --version`; null when it does not run (exit ≠ 0). */
|
|
47
|
+
function versionOf(file, pattern, env) {
|
|
48
|
+
const result = spawnSync(file, ['--version'], {
|
|
49
|
+
encoding: 'utf8',
|
|
50
|
+
timeout: 10_000,
|
|
51
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
52
|
+
env,
|
|
53
|
+
});
|
|
54
|
+
if (result.error || result.status !== 0) return null;
|
|
55
|
+
return pattern.exec(`${result.stdout || ''}\n${result.stderr || ''}`)?.[1] || '';
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* { [tool]: { ok, path, version } } for the Skill tools (git and python3 must
|
|
60
|
+
* also run: on macOS they may be stubs that only offer to install the
|
|
61
|
+
* Command Line Tools) and, on Linux, the sandbox's bwrap and socat.
|
|
62
|
+
*/
|
|
63
|
+
export function checkTools({ platform = process.platform, pathEnv = process.env.PATH } = {}) {
|
|
64
|
+
const tools = {};
|
|
65
|
+
for (const name of SKILL_TOOLS) {
|
|
66
|
+
const file = which(name, pathEnv);
|
|
67
|
+
let ok = Boolean(file);
|
|
68
|
+
let version = '';
|
|
69
|
+
if (ok && (name === 'git' || name === 'python3')) {
|
|
70
|
+
const found = versionOf(file, name === 'git' ? /git version (\d+(?:\.\d+)*)/ : /Python (\d+(?:\.\d+)*)/);
|
|
71
|
+
ok = found !== null;
|
|
72
|
+
version = found || '';
|
|
73
|
+
}
|
|
74
|
+
tools[name] = { ok, path: file, version };
|
|
75
|
+
}
|
|
76
|
+
if (platform === 'linux') {
|
|
77
|
+
for (const name of SANDBOX_TOOLS) {
|
|
78
|
+
const file = which(name, pathEnv);
|
|
79
|
+
tools[name] = { ok: Boolean(file), path: file, version: '' };
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
return tools;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Where claude is: CLAUDE_BIN, the saved claudePath, PATH, then
|
|
87
|
+
* `$(npm prefix -g)/bin/claude` (viaNpmPrefix: tell the user to add it to PATH).
|
|
88
|
+
*/
|
|
89
|
+
export function resolveClaude({ env = process.env, configured = '', pathEnv = env.PATH } = {}) {
|
|
90
|
+
for (const candidate of [env.CLAUDE_BIN, configured]) {
|
|
91
|
+
if (candidate && isExecutableFile(candidate)) return { path: candidate, viaNpmPrefix: false };
|
|
92
|
+
}
|
|
93
|
+
const found = which('claude', pathEnv);
|
|
94
|
+
if (found) return { path: found, viaNpmPrefix: false };
|
|
95
|
+
const npm = which('npm', pathEnv);
|
|
96
|
+
if (npm) {
|
|
97
|
+
const result = spawnSync(npm, ['prefix', '-g'], { encoding: 'utf8', timeout: 20_000, stdio: ['ignore', 'pipe', 'ignore'] });
|
|
98
|
+
const prefix = result.status === 0 ? result.stdout.trim() : '';
|
|
99
|
+
const file = prefix ? path.join(prefix, 'bin', 'claude') : '';
|
|
100
|
+
if (file && isExecutableFile(file)) return { path: file, viaNpmPrefix: true };
|
|
101
|
+
}
|
|
102
|
+
return { path: '', viaNpmPrefix: false };
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** claude's version (x.y.z), '' when it does not run. */
|
|
106
|
+
export function claudeVersion(file, env = process.env) {
|
|
107
|
+
if (!file) return '';
|
|
108
|
+
return versionOf(file, /^(\d+\.\d+\.\d+)/m, { ...env, DISABLE_AUTOUPDATER: '1' }) || '';
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function killGroup(child, signal) {
|
|
112
|
+
try {
|
|
113
|
+
process.kill(-child.pid, signal);
|
|
114
|
+
} catch {
|
|
115
|
+
// Already gone.
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function failureReason(stderr, resultText, code) {
|
|
120
|
+
const line = stderr.find((item) => /sandbox/i.test(item)) || stderr[0] || resultText || `claude 退出码 ${code}`;
|
|
121
|
+
return [...line.replace(/\p{Cc}/gu, ' ').replace(/^error:\s*/i, '').trim()].slice(0, 300).join('');
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function blockText(content) {
|
|
125
|
+
if (typeof content === 'string') return content;
|
|
126
|
+
if (!Array.isArray(content)) return '';
|
|
127
|
+
return content.map((item) => (typeof item?.text === 'string' ? item.text : '')).join('\n');
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** What went wrong with the probe command, without Claude Code's boilerplate. */
|
|
131
|
+
export function sandboxFailure(text) {
|
|
132
|
+
const cleaned = String(text || '')
|
|
133
|
+
.replace(/^Exit code \d+\s*/i, '')
|
|
134
|
+
.replace(/^Sandbox is required but failed to initialize:\s*/i, '')
|
|
135
|
+
.replace(/\s*Restart to retry\.?/i, '')
|
|
136
|
+
.replace(/\s*Running it outside the sandbox[^.]*\.?/i, '')
|
|
137
|
+
.replace(/\p{Cc}/gu, ' ')
|
|
138
|
+
.replace(/\s+/g, ' ')
|
|
139
|
+
.trim();
|
|
140
|
+
return [...(cleaned || '沙箱里的命令没有正常执行')].slice(0, 300).join('');
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** NO_PROXY with the stand-in model's address added, so a proxy never sits between claude and it. */
|
|
144
|
+
function localNoProxy(env) {
|
|
145
|
+
const current = env.NO_PROXY || env.no_proxy || '';
|
|
146
|
+
const value = [current, '127.0.0.1', 'localhost'].filter(Boolean).join(',');
|
|
147
|
+
return { NO_PROXY: value, no_proxy: value };
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Runs claude exactly as for a job (same arguments, sandbox settings,
|
|
152
|
+
* environment and run directory shape) against a stand-in model on 127.0.0.1
|
|
153
|
+
* (probe-model.mjs) that asks for one Bash call: `echo <PROBE_MARKER>`. The
|
|
154
|
+
* sandbox only starts on a job's first command, so only the command's result
|
|
155
|
+
* tells whether jobs can run: its output means yes; an error is the reason
|
|
156
|
+
* (e.g. "Failed to create bridge sockets…"). claude exiting first gives its
|
|
157
|
+
* own reason (missing bubblewrap…). No request leaves the machine. The real
|
|
158
|
+
* guarantee remains failIfUnavailable in every job's settings.
|
|
159
|
+
*/
|
|
160
|
+
export async function probeSandbox({
|
|
161
|
+
claudePath,
|
|
162
|
+
workRoot,
|
|
163
|
+
realHome,
|
|
164
|
+
env = process.env,
|
|
165
|
+
platform = process.platform,
|
|
166
|
+
timeoutMs = PROBE_TIMEOUT_MS,
|
|
167
|
+
}) {
|
|
168
|
+
if (!claudePath) return { ok: false, reason: '未安装 claude' };
|
|
169
|
+
const pathEnv = env.PATH || '';
|
|
170
|
+
const layout = createRunLayout(newRunDir(path.join(workRoot, 'runs'), 'p'));
|
|
171
|
+
let model = null;
|
|
172
|
+
try {
|
|
173
|
+
const tooLong = socketPathProblem(layout.tmpDir, platform);
|
|
174
|
+
if (tooLong) return { ok: false, reason: tooLong };
|
|
175
|
+
writeSandboxSettings(layout.settingsFile, {
|
|
176
|
+
workDir: layout.workDir,
|
|
177
|
+
realHome,
|
|
178
|
+
readAllow: homeReadAllow({ realHome, pathEnv, caPaths: caPaths(env) }),
|
|
179
|
+
});
|
|
180
|
+
model = await startProbeModel();
|
|
181
|
+
const child = spawn(claudePath, claudeArgs({ settingsFile: layout.settingsFile }), {
|
|
182
|
+
cwd: layout.workDir,
|
|
183
|
+
detached: true,
|
|
184
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
185
|
+
env: claudeEnv({
|
|
186
|
+
path: pathEnv,
|
|
187
|
+
runDir: layout.runDir,
|
|
188
|
+
homeDir: layout.homeDir,
|
|
189
|
+
configDir: layout.configDir,
|
|
190
|
+
tmpDir: layout.tmpDir,
|
|
191
|
+
baseUrl: model.baseUrl,
|
|
192
|
+
apiKey: 'probe',
|
|
193
|
+
model: 'probe',
|
|
194
|
+
extra: { ...passThroughEnv(env, platform), ...localNoProxy(env) },
|
|
195
|
+
}),
|
|
196
|
+
});
|
|
197
|
+
const exited = new Promise((resolve) => child.once('close', resolve));
|
|
198
|
+
const verdict = new Promise((resolve) => {
|
|
199
|
+
const stderr = [];
|
|
200
|
+
let resultText = '';
|
|
201
|
+
let done = false;
|
|
202
|
+
const finish = (value) => {
|
|
203
|
+
if (done) return;
|
|
204
|
+
done = true;
|
|
205
|
+
clearTimeout(timer);
|
|
206
|
+
killGroup(child, 'SIGKILL');
|
|
207
|
+
resolve(value);
|
|
208
|
+
};
|
|
209
|
+
const timer = setTimeout(() => finish({ ok: false, reason: '沙箱检测超时' }), timeoutMs);
|
|
210
|
+
child.once('error', (error) => finish({ ok: false, reason: `无法启动 claude:${error.code || error.message}` }));
|
|
211
|
+
readline.createInterface({ input: child.stdout }).on('line', (line) => {
|
|
212
|
+
let event;
|
|
213
|
+
try {
|
|
214
|
+
event = JSON.parse(line);
|
|
215
|
+
} catch {
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
if (event?.type === 'result' && typeof event.result === 'string') resultText = event.result;
|
|
219
|
+
if (event?.type !== 'user' || !Array.isArray(event.message?.content)) return;
|
|
220
|
+
for (const block of event.message.content) {
|
|
221
|
+
if (block?.type !== 'tool_result' || block.tool_use_id !== PROBE_TOOL_ID) continue;
|
|
222
|
+
const text = blockText(block.content);
|
|
223
|
+
if (!block.is_error && text.includes(PROBE_MARKER)) finish({ ok: true, reason: '' });
|
|
224
|
+
else finish({ ok: false, reason: sandboxFailure(text) });
|
|
225
|
+
}
|
|
226
|
+
});
|
|
227
|
+
readline.createInterface({ input: child.stderr }).on('line', (line) => {
|
|
228
|
+
if (line.trim()) stderr.push(line.trim());
|
|
229
|
+
});
|
|
230
|
+
child.once('close', (code) => finish({ ok: false, reason: failureReason(stderr, resultText, code) }));
|
|
231
|
+
});
|
|
232
|
+
child.stdin.on('error', () => {});
|
|
233
|
+
child.stdin.end('probe');
|
|
234
|
+
const result = await verdict;
|
|
235
|
+
// The process group is gone (or going): give it a moment before deleting its directory.
|
|
236
|
+
await Promise.race([exited, new Promise((resolve) => setTimeout(resolve, 3000).unref())]);
|
|
237
|
+
return result;
|
|
238
|
+
} finally {
|
|
239
|
+
await model?.close();
|
|
240
|
+
fs.rmSync(layout.runDir, { recursive: true, force: true });
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* Full check. `probe: false` skips the sandbox probe (it then reads as not
|
|
246
|
+
* checked). Returns { capabilities, tools, claude, claudeVersion, packageManager }.
|
|
247
|
+
*/
|
|
248
|
+
export async function runDoctor({
|
|
249
|
+
env = process.env,
|
|
250
|
+
platform = process.platform,
|
|
251
|
+
arch = process.arch,
|
|
252
|
+
configuredClaude = '',
|
|
253
|
+
workRoot,
|
|
254
|
+
realHome,
|
|
255
|
+
probe = true,
|
|
256
|
+
probeTimeoutMs = PROBE_TIMEOUT_MS,
|
|
257
|
+
}) {
|
|
258
|
+
const pathEnv = env.PATH || '';
|
|
259
|
+
const tools = checkTools({ platform, pathEnv });
|
|
260
|
+
const claude = resolveClaude({ env, configured: configuredClaude, pathEnv });
|
|
261
|
+
const version = claudeVersion(claude.path, env);
|
|
262
|
+
const packageManager = detectPackageManager({ platform, which: (name) => which(name, pathEnv) });
|
|
263
|
+
let sandbox;
|
|
264
|
+
if (!claude.path) sandbox = { ok: false, reason: '未安装 claude' };
|
|
265
|
+
else if (!probe) sandbox = { ok: false, reason: '尚未检测沙箱' };
|
|
266
|
+
else {
|
|
267
|
+
sandbox = await probeSandbox({ claudePath: claude.path, workRoot, realHome, env, platform, timeoutMs: probeTimeoutMs });
|
|
268
|
+
if (!sandbox.ok && platform === 'linux') {
|
|
269
|
+
// The common case, in words the user can act on (setup installs them).
|
|
270
|
+
const missing = SANDBOX_TOOLS.filter((name) => !tools[name]?.ok).map((name) => (name === 'bwrap' ? 'bubblewrap' : name));
|
|
271
|
+
if (missing.length) sandbox = { ok: false, reason: `缺少 ${missing.join('、')}` };
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
return {
|
|
275
|
+
capabilities: {
|
|
276
|
+
os: platform,
|
|
277
|
+
arch,
|
|
278
|
+
node: process.versions.node,
|
|
279
|
+
claude: version,
|
|
280
|
+
tools: Object.fromEntries(SKILL_TOOLS.map((name) => [name, Boolean(tools[name]?.ok)])),
|
|
281
|
+
sandbox,
|
|
282
|
+
packageManager,
|
|
283
|
+
},
|
|
284
|
+
tools,
|
|
285
|
+
claude,
|
|
286
|
+
claudeVersion: version,
|
|
287
|
+
packageManager,
|
|
288
|
+
};
|
|
289
|
+
}
|
package/lib/http.mjs
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
// The website protocol (/api/machine/v1) over fetch: Bearer token + client id
|
|
2
|
+
// on every request, JSON bodies, the SSE control channel. Only https, except
|
|
3
|
+
// http://127.0.0.1 / http://localhost for development.
|
|
4
|
+
|
|
5
|
+
import http from 'node:http';
|
|
6
|
+
|
|
7
|
+
export const PROTOCOL_PATH = '/api/machine/v1';
|
|
8
|
+
|
|
9
|
+
export class ApiError extends Error {
|
|
10
|
+
constructor(status, body, retryAfterMs = 0) {
|
|
11
|
+
super(body?.message || `HTTP ${status}`);
|
|
12
|
+
this.name = 'ApiError';
|
|
13
|
+
this.status = status;
|
|
14
|
+
this.code = typeof body?.error === 'string' ? body.error : '';
|
|
15
|
+
this.body = body || null;
|
|
16
|
+
this.retryAfterMs = retryAfterMs;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export class IdleError extends Error {
|
|
21
|
+
constructor(ms) {
|
|
22
|
+
super(`控制通道 ${Math.round(ms / 1000)} 秒没有数据`);
|
|
23
|
+
this.name = 'IdleError';
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** The website origin; throws for anything but https (or http on 127.0.0.1 / localhost). */
|
|
28
|
+
export function normalizeServerUrl(raw) {
|
|
29
|
+
let url;
|
|
30
|
+
try {
|
|
31
|
+
url = new URL(String(raw ?? '').trim());
|
|
32
|
+
} catch {
|
|
33
|
+
throw new Error('网站地址不正确');
|
|
34
|
+
}
|
|
35
|
+
const local = ['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname);
|
|
36
|
+
if (url.protocol !== 'https:' && !(url.protocol === 'http:' && local)) {
|
|
37
|
+
throw new Error('网站地址必须是 https(只有 127.0.0.1 / localhost 可以用 http)');
|
|
38
|
+
}
|
|
39
|
+
if (url.username || url.password) throw new Error('网站地址不能包含账号');
|
|
40
|
+
return url.origin;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function userAgent(version) {
|
|
44
|
+
return `work-agent-runner/${version} (${process.platform}; ${process.arch}; node/${process.versions.node})`;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function retryAfterMs(response) {
|
|
48
|
+
const seconds = Number(response.headers.get('retry-after'));
|
|
49
|
+
return Number.isFinite(seconds) && seconds > 0 ? Math.min(seconds, 3600) * 1000 : 0;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function withTimeout(signal, ms) {
|
|
53
|
+
const timeout = AbortSignal.timeout(ms);
|
|
54
|
+
return signal ? AbortSignal.any([signal, timeout]) : timeout;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Splits SSE text into messages; returns the unfinished rest. */
|
|
58
|
+
function parseFrames(buffer, onEvent) {
|
|
59
|
+
let rest = buffer.replace(/\r\n?/g, '\n');
|
|
60
|
+
let index;
|
|
61
|
+
while ((index = rest.indexOf('\n\n')) >= 0) {
|
|
62
|
+
const frame = rest.slice(0, index);
|
|
63
|
+
rest = rest.slice(index + 2);
|
|
64
|
+
const data = frame
|
|
65
|
+
.split('\n')
|
|
66
|
+
.filter((line) => line.startsWith('data:'))
|
|
67
|
+
.map((line) => line.slice(5).replace(/^ /, ''))
|
|
68
|
+
.join('\n');
|
|
69
|
+
if (!data) continue; // comments (": ping") and empty frames
|
|
70
|
+
let event;
|
|
71
|
+
try {
|
|
72
|
+
event = JSON.parse(data);
|
|
73
|
+
} catch {
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
onEvent(event);
|
|
77
|
+
}
|
|
78
|
+
return rest;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function createClient({ server, token, clientId, version, timeoutMs = 30_000 }) {
|
|
82
|
+
const base = `${server}${PROTOCOL_PATH}`;
|
|
83
|
+
const headers = (extra = {}) => ({
|
|
84
|
+
Authorization: `Bearer ${token}`,
|
|
85
|
+
'X-Machine-Client': clientId,
|
|
86
|
+
'User-Agent': userAgent(version),
|
|
87
|
+
...extra,
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
async function request(method, url, body, { signal, timeout = timeoutMs } = {}) {
|
|
91
|
+
const response = await fetch(`${base}${url}`, {
|
|
92
|
+
method,
|
|
93
|
+
headers: headers(body === undefined ? {} : { 'Content-Type': 'application/json' }),
|
|
94
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
95
|
+
signal: withTimeout(signal, timeout),
|
|
96
|
+
});
|
|
97
|
+
const text = await response.text();
|
|
98
|
+
let json = null;
|
|
99
|
+
try {
|
|
100
|
+
json = text ? JSON.parse(text) : null;
|
|
101
|
+
} catch {
|
|
102
|
+
// Not JSON (e.g. a proxy error page).
|
|
103
|
+
}
|
|
104
|
+
if (!response.ok) throw new ApiError(response.status, json, retryAfterMs(response));
|
|
105
|
+
return json;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
async function download(url, { signal, timeout = 120_000 } = {}) {
|
|
109
|
+
const response = await fetch(`${base}${url}`, { headers: headers(), signal: withTimeout(signal, timeout) });
|
|
110
|
+
if (!response.ok) {
|
|
111
|
+
const text = await response.text().catch(() => '');
|
|
112
|
+
let json = null;
|
|
113
|
+
try {
|
|
114
|
+
json = JSON.parse(text);
|
|
115
|
+
} catch {
|
|
116
|
+
// Ignore.
|
|
117
|
+
}
|
|
118
|
+
throw new ApiError(response.status, json, retryAfterMs(response));
|
|
119
|
+
}
|
|
120
|
+
return Buffer.from(await response.arrayBuffer());
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* The control channel: calls onOpen() once connected and onEvent(event)
|
|
125
|
+
* for every message. Resolves when the server ends it, rejects with an
|
|
126
|
+
* ApiError (refused), an IdleError (no byte for idleMs) or a network error.
|
|
127
|
+
* Aborting `signal` resolves quietly.
|
|
128
|
+
*/
|
|
129
|
+
async function stream(url, { onEvent, onOpen, idleMs = 45_000, signal } = {}) {
|
|
130
|
+
const controller = new AbortController();
|
|
131
|
+
const stop = () => controller.abort();
|
|
132
|
+
signal?.addEventListener('abort', stop, { once: true });
|
|
133
|
+
let idle = false;
|
|
134
|
+
let timer = null;
|
|
135
|
+
const arm = () => {
|
|
136
|
+
clearTimeout(timer);
|
|
137
|
+
timer = setTimeout(() => {
|
|
138
|
+
idle = true;
|
|
139
|
+
controller.abort();
|
|
140
|
+
}, idleMs);
|
|
141
|
+
};
|
|
142
|
+
try {
|
|
143
|
+
arm();
|
|
144
|
+
const response = await fetch(`${base}${url}`, {
|
|
145
|
+
headers: headers({ Accept: 'text/event-stream', 'Accept-Encoding': 'identity', 'Cache-Control': 'no-cache' }),
|
|
146
|
+
signal: controller.signal,
|
|
147
|
+
});
|
|
148
|
+
if (!response.ok) {
|
|
149
|
+
const text = await response.text().catch(() => '');
|
|
150
|
+
let json = null;
|
|
151
|
+
try {
|
|
152
|
+
json = JSON.parse(text);
|
|
153
|
+
} catch {
|
|
154
|
+
// Ignore.
|
|
155
|
+
}
|
|
156
|
+
throw new ApiError(response.status, json, retryAfterMs(response));
|
|
157
|
+
}
|
|
158
|
+
onOpen?.();
|
|
159
|
+
const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
|
|
160
|
+
let buffer = '';
|
|
161
|
+
for (;;) {
|
|
162
|
+
const { value, done } = await reader.read();
|
|
163
|
+
if (done) break;
|
|
164
|
+
arm();
|
|
165
|
+
buffer = parseFrames(buffer + value, onEvent);
|
|
166
|
+
}
|
|
167
|
+
} catch (error) {
|
|
168
|
+
if (idle) throw new IdleError(idleMs);
|
|
169
|
+
if (signal?.aborted) return;
|
|
170
|
+
throw error;
|
|
171
|
+
} finally {
|
|
172
|
+
clearTimeout(timer);
|
|
173
|
+
signal?.removeEventListener('abort', stop);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
return { request, download, stream };
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** True when HTTPS_PROXY / HTTP_PROXY (either case) is set. */
|
|
181
|
+
export function hasProxy(env = process.env) {
|
|
182
|
+
return ['HTTPS_PROXY', 'HTTP_PROXY', 'https_proxy', 'http_proxy'].some((name) => Boolean(env[name]));
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* Makes this process's fetch use the proxy variables: 'enabled' (Node 24.14+
|
|
187
|
+
* / 25.4+ can do it at runtime), 'restart' (older Node only reads
|
|
188
|
+
* NODE_USE_ENV_PROXY at startup: run again with it set) or 'none'.
|
|
189
|
+
*/
|
|
190
|
+
export function proxyMode(env = process.env) {
|
|
191
|
+
if (!hasProxy(env)) return 'none';
|
|
192
|
+
if (typeof http.setGlobalProxyFromEnv === 'function') {
|
|
193
|
+
http.setGlobalProxyFromEnv();
|
|
194
|
+
return 'enabled';
|
|
195
|
+
}
|
|
196
|
+
if (env.NODE_USE_ENV_PROXY || env.GC_RUNNER_REEXEC) return 'none';
|
|
197
|
+
return 'restart';
|
|
198
|
+
}
|