shoplazza-ai-dev-cli 0.1.21 → 0.1.22-snapshot.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,910 @@
1
+ import { i as loadConfig, n as runLogin, r as getConfigFile } from "../cli.mjs";
2
+ import { chmodSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
3
+ import { dirname, join } from "node:path";
4
+ import { execFile, execFileSync } from "node:child_process";
5
+ import { cpus, homedir, hostname, release, totalmem } from "node:os";
6
+ import { randomUUID } from "node:crypto";
7
+ const AUTOFLOW_API_PREFIX = "/api/v1/autoflow";
8
+ const RUNNER_INSTANCE_HEADER = "X-Runner-Instance";
9
+ const CODE_OK = "ok";
10
+ const ERR_RUNNER_SUPERSEDED = "runner_superseded";
11
+ const HTTP_UNAUTHORIZED = 401;
12
+ const BEARER_PREFIX = "Bearer ";
13
+ const DEFAULT_TIMEOUT_MS = 3e4;
14
+ const AUTHORIZATION = "authorization";
15
+ const JSON_TYPE = "application/json";
16
+ const DEFAULT_SCHEME = "https://";
17
+ const HTTP_SCHEMES = new Set(["http:", "https:"]);
18
+ var RunnerApiError = class extends Error {
19
+ hint;
20
+ constructor(status, code, detail) {
21
+ super(`autoflow api failed: status=${status} code=${code || "-"} message=${detail}`);
22
+ this.status = status;
23
+ this.code = code;
24
+ this.detail = detail;
25
+ this.name = "RunnerApiError";
26
+ }
27
+ };
28
+ var RunnerTokenInvalidError = class extends RunnerApiError {
29
+ hint = "runner 令牌已失效(这台电脑可能已在页面解绑或重新绑定),请在页面重新绑定后再启动";
30
+ constructor(status, code, message) {
31
+ super(status, code, message);
32
+ this.name = "RunnerTokenInvalidError";
33
+ }
34
+ };
35
+ var RunnerSupersededError = class extends RunnerApiError {
36
+ hint = "这台电脑已在别处启动了 runner,本进程退出";
37
+ constructor(status, code, message) {
38
+ super(status, code, message);
39
+ this.name = "RunnerSupersededError";
40
+ }
41
+ };
42
+ var RunnerBadResponseError = class extends RunnerApiError {
43
+ hint = "平台返回了无法识别的响应(可能被重定向到了登录页),请检查门户地址是否正确";
44
+ constructor(status, message) {
45
+ super(status, "", message);
46
+ this.name = "RunnerBadResponseError";
47
+ }
48
+ };
49
+ var PlatformHttp = class {
50
+ base;
51
+ token;
52
+ instanceId;
53
+ timeoutMs;
54
+ constructor(opts) {
55
+ this.base = normalizePortalURL(opts.portal) + AUTOFLOW_API_PREFIX;
56
+ this.token = opts.token;
57
+ this.instanceId = opts.instanceId;
58
+ this.timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
59
+ }
60
+ async request(method, path, opts = {}) {
61
+ const headers = new Headers({ accept: JSON_TYPE });
62
+ const bearer = opts.leaseToken ?? this.token;
63
+ if (bearer) headers.set(AUTHORIZATION, BEARER_PREFIX + bearer);
64
+ if (this.instanceId) headers.set(RUNNER_INSTANCE_HEADER, this.instanceId);
65
+ if (opts.body !== void 0) headers.set("content-type", JSON_TYPE);
66
+ for (const [k, v] of Object.entries(opts.headers ?? {})) headers.set(k, v);
67
+ const res = await fetch(this.base + path, {
68
+ method,
69
+ headers,
70
+ body: opts.body === void 0 ? void 0 : JSON.stringify(opts.body),
71
+ signal: AbortSignal.timeout(this.timeoutMs)
72
+ });
73
+ const text = await res.text();
74
+ return {
75
+ status: res.status,
76
+ body: parseBody(text)
77
+ };
78
+ }
79
+ async call(method, path, opts = {}) {
80
+ const res = await this.request(method, path, opts);
81
+ const env = asEnvelope(res.body);
82
+ const ok = res.status >= 200 && res.status < 300;
83
+ if (ok && res.body === void 0) return;
84
+ if (ok && env === void 0) throw new RunnerBadResponseError(res.status, "response is not an autoflow envelope");
85
+ if (ok && env?.code === CODE_OK) return env.data;
86
+ const code = env?.code ?? "";
87
+ const message = env?.message ?? `http ${res.status}`;
88
+ if (code === ERR_RUNNER_SUPERSEDED) throw new RunnerSupersededError(res.status, code, message);
89
+ if (res.status === HTTP_UNAUTHORIZED && this.usesRunnerToken(opts)) throw new RunnerTokenInvalidError(res.status, code, message);
90
+ throw new RunnerApiError(res.status, code, message);
91
+ }
92
+ usesRunnerToken(opts) {
93
+ const overridden = Object.keys(opts.headers ?? {}).some((k) => k.toLowerCase() === AUTHORIZATION);
94
+ return Boolean(this.token) && opts.leaseToken === void 0 && !overridden;
95
+ }
96
+ };
97
+ function normalizePortalURL(portal) {
98
+ const url = parsePortal(portal);
99
+ return (url.origin + url.pathname).replace(/\/+$/, "");
100
+ }
101
+ function portalHostOf(portal) {
102
+ return parsePortal(portal).host;
103
+ }
104
+ function parsePortal(portal) {
105
+ const trimmed = portal.trim();
106
+ const withScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed) ? trimmed : DEFAULT_SCHEME + trimmed;
107
+ let url;
108
+ try {
109
+ url = new URL(withScheme);
110
+ } catch (e) {
111
+ throw new Error(`invalid portal url: ${JSON.stringify(portal)}`, { cause: e });
112
+ }
113
+ if (!HTTP_SCHEMES.has(url.protocol) || url.host === "") throw new Error(`invalid portal url: ${JSON.stringify(portal)}`);
114
+ return url;
115
+ }
116
+ function parseBody(text) {
117
+ if (text === "") return;
118
+ try {
119
+ return JSON.parse(text);
120
+ } catch {
121
+ return text;
122
+ }
123
+ }
124
+ function asEnvelope(body) {
125
+ if (body === null || typeof body !== "object" || Array.isArray(body)) return;
126
+ const code = body.code;
127
+ if (typeof code !== "string") return;
128
+ const message = body.message;
129
+ return {
130
+ code,
131
+ message: typeof message === "string" ? message : void 0,
132
+ data: body.data
133
+ };
134
+ }
135
+ const ROOT_DIR = ".forge-runner";
136
+ const PKG_DIR = "pkg";
137
+ const BIN_DIR = "bin";
138
+ const NODE_DIR = "node";
139
+ const RUNNER_BIN_NAME = "forge-runner";
140
+ const CREDENTIALS_FILE = "credentials.json";
141
+ const DEFAULT_WS_PATH = `${AUTOFLOW_API_PREFIX}/runner/ws`;
142
+ const LEGACY_PORTAL_SCHEME = "https://";
143
+ const AGENTS_FILE = "agents.json";
144
+ const SETTINGS_FILE = "settings.json";
145
+ const DOCTOR_TARGETS_FILE = "doctor_targets.json";
146
+ const PORT_FILE = "runner.port";
147
+ const INSTANCE_FILE = "instance_id";
148
+ const LOCK_FILE = "runner.lock";
149
+ const LOGS_DIR = "logs";
150
+ const DIR_MODE = 448;
151
+ const FILE_MODE = 384;
152
+ const MAX_PORT = 65535;
153
+ const HEALTH_PORT_BASE = 19600;
154
+ const HEALTH_PORT_SPAN = 400;
155
+ const FNV_OFFSET = 2166136261;
156
+ const FNV_PRIME = 16777619;
157
+ const PORTAL_HOST_RE = /^[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)*(:\d{1,5})?$/;
158
+ var RunnerProfile = class {
159
+ root;
160
+ lockPath;
161
+ portPath;
162
+ logsDir;
163
+ constructor(home = homedir()) {
164
+ this.root = join(home, ROOT_DIR);
165
+ this.lockPath = join(this.root, LOCK_FILE);
166
+ this.portPath = join(this.root, PORT_FILE);
167
+ this.logsDir = join(this.root, LOGS_DIR);
168
+ }
169
+ portalDir(portalHost) {
170
+ if (!PORTAL_HOST_RE.test(portalHost)) throw new Error(`invalid portal host: ${JSON.stringify(portalHost)}`);
171
+ return join(this.root, portalHost);
172
+ }
173
+ readCredentials(portalHost) {
174
+ const path = join(this.portalDir(portalHost), CREDENTIALS_FILE);
175
+ const data = readJSON(path);
176
+ if (data === void 0) return;
177
+ if (typeof data?.portal_host !== "string" || typeof data.runner_id !== "string" || data.runner_id === "" || typeof data.runner_token !== "string" || data.runner_token === "" || !optionalNonEmpty(data.portal) || !optionalNonEmpty(data.ws_path)) throw new Error(`invalid credentials file: ${path}`);
178
+ return {
179
+ portalHost: data.portal_host,
180
+ runnerId: data.runner_id,
181
+ runnerToken: data.runner_token,
182
+ portal: data.portal ?? LEGACY_PORTAL_SCHEME + data.portal_host,
183
+ wsPath: data.ws_path ?? DEFAULT_WS_PATH
184
+ };
185
+ }
186
+ writeCredentials(creds) {
187
+ const data = {
188
+ portal_host: creds.portalHost,
189
+ runner_id: creds.runnerId,
190
+ runner_token: creds.runnerToken,
191
+ portal: creds.portal,
192
+ ws_path: creds.wsPath
193
+ };
194
+ this.writeFile(join(this.portalDir(creds.portalHost), CREDENTIALS_FILE), jsonText(data));
195
+ }
196
+ removeCredentialsIfToken(portalHost, runnerToken) {
197
+ let stored;
198
+ try {
199
+ stored = this.readCredentials(portalHost);
200
+ } catch {
201
+ return false;
202
+ }
203
+ if (stored?.runnerToken !== runnerToken) return false;
204
+ rmSync(join(this.portalDir(portalHost), CREDENTIALS_FILE), { force: true });
205
+ return true;
206
+ }
207
+ listCredentials() {
208
+ if (!existsSync(this.root)) return [];
209
+ const found = [];
210
+ for (const entry of readdirSync(this.root, { withFileTypes: true })) {
211
+ if (!entry.isDirectory() || !existsSync(join(this.root, entry.name, CREDENTIALS_FILE))) continue;
212
+ try {
213
+ const creds = this.readCredentials(entry.name);
214
+ if (creds) found.push(creds);
215
+ } catch {}
216
+ }
217
+ return found;
218
+ }
219
+ readAgents(portalHost) {
220
+ const path = join(this.portalDir(portalHost), AGENTS_FILE);
221
+ const data = readJSON(path);
222
+ if (data === void 0) return [];
223
+ if (!Array.isArray(data)) throw new Error(`invalid agents cache, want array: ${path}`);
224
+ return data;
225
+ }
226
+ writeAgents(portalHost, agents) {
227
+ this.writeFile(join(this.portalDir(portalHost), AGENTS_FILE), jsonText(agents));
228
+ }
229
+ readSettings(portalHost) {
230
+ const path = join(this.portalDir(portalHost), SETTINGS_FILE);
231
+ const data = readJSON(path);
232
+ if (data === void 0) return;
233
+ if (data === null || typeof data !== "object" || Array.isArray(data)) throw new Error(`invalid settings cache, want object: ${path}`);
234
+ return data;
235
+ }
236
+ writeSettings(portalHost, settings) {
237
+ this.writeFile(join(this.portalDir(portalHost), SETTINGS_FILE), jsonText(settings));
238
+ }
239
+ readDoctorTargets(portalHost) {
240
+ const data = readJSON(join(this.portalDir(portalHost), DOCTOR_TARGETS_FILE));
241
+ if (data === void 0 || data === null || typeof data !== "object") return;
242
+ return normalizeDoctorTargets(data);
243
+ }
244
+ writeDoctorTargets(portalHost, targets) {
245
+ this.writeFile(join(this.portalDir(portalHost), DOCTOR_TARGETS_FILE), jsonText(targets));
246
+ }
247
+ ensureLogsDir() {
248
+ this.ensureDir(this.logsDir);
249
+ return this.logsDir;
250
+ }
251
+ readPort() {
252
+ let raw;
253
+ try {
254
+ raw = readFileSync(this.portPath, "utf8").trim();
255
+ } catch (e) {
256
+ if (errCode(e) === "ENOENT") return;
257
+ throw e;
258
+ }
259
+ const port = /^\d+$/.test(raw) ? Number(raw) : NaN;
260
+ if (!isValidPort(port)) throw new Error(`invalid port file ${JSON.stringify(raw)}: ${this.portPath}`);
261
+ return port;
262
+ }
263
+ instanceId(host = hostname()) {
264
+ const path = join(this.root, INSTANCE_FILE);
265
+ let saved;
266
+ try {
267
+ saved = readJSON(path);
268
+ } catch {
269
+ saved = void 0;
270
+ }
271
+ if (typeof saved?.instance_id === "string" && saved.instance_id !== "" && saved.host === host) return saved.instance_id;
272
+ const fresh = {
273
+ instance_id: randomUUID(),
274
+ host
275
+ };
276
+ this.writeFile(path, jsonText(fresh));
277
+ return fresh.instance_id;
278
+ }
279
+ writePort(port) {
280
+ if (!isValidPort(port)) throw new Error(`invalid port: ${port}`);
281
+ this.writeFile(this.portPath, `${port}\n`);
282
+ }
283
+ ensureDir(dir) {
284
+ mkdirSync(dir, {
285
+ recursive: true,
286
+ mode: DIR_MODE
287
+ });
288
+ chmodSync(this.root, DIR_MODE);
289
+ if (dir !== this.root) chmodSync(dir, DIR_MODE);
290
+ }
291
+ writeFile(path, content) {
292
+ this.ensureDir(dirname(path));
293
+ const tmp = `${path}.${randomUUID()}.tmp`;
294
+ try {
295
+ writeFileSync(tmp, content, {
296
+ mode: FILE_MODE,
297
+ flag: "wx"
298
+ });
299
+ renameSync(tmp, path);
300
+ } catch (e) {
301
+ rmSync(tmp, { force: true });
302
+ throw e;
303
+ }
304
+ }
305
+ };
306
+ function healthPort(host = hostname()) {
307
+ let hash = FNV_OFFSET;
308
+ for (const byte of Buffer.from(host, "utf8")) hash = Math.imul(hash ^ byte, FNV_PRIME) >>> 0;
309
+ return HEALTH_PORT_BASE + hash % HEALTH_PORT_SPAN;
310
+ }
311
+ function normalizeDoctorTargets(raw) {
312
+ const data = raw ?? {};
313
+ return {
314
+ gitlab_url: typeof data.gitlab_url === "string" ? data.gitlab_url : "",
315
+ repos: Array.isArray(data.repos) ? data.repos.filter((r) => typeof r === "string") : [],
316
+ publish_url: typeof data.publish_url === "string" ? data.publish_url : ""
317
+ };
318
+ }
319
+ function readJSON(path) {
320
+ let raw;
321
+ try {
322
+ raw = readFileSync(path, "utf8");
323
+ } catch (e) {
324
+ if (errCode(e) === "ENOENT") return;
325
+ throw e;
326
+ }
327
+ try {
328
+ return JSON.parse(raw);
329
+ } catch (e) {
330
+ throw new Error(`parse ${path}: ${e.message}`, { cause: e });
331
+ }
332
+ }
333
+ function optionalNonEmpty(v) {
334
+ return v === void 0 || typeof v === "string" && v !== "";
335
+ }
336
+ function jsonText(data) {
337
+ return `${JSON.stringify(data, null, 2)}\n`;
338
+ }
339
+ function isValidPort(port) {
340
+ return Number.isInteger(port) && port > 0 && port <= MAX_PORT;
341
+ }
342
+ function errCode(e) {
343
+ return e?.code;
344
+ }
345
+ const CLI_PACKAGE = "shoplazza-ai-dev-cli";
346
+ const NPM_TIMEOUT_MS$1 = 10 * 6e4;
347
+ const NPM_MAX_BUFFER$1 = 4 * 1024 * 1024;
348
+ const ENTRY_MODE = 493;
349
+ var InstallError = class extends Error {
350
+ hint;
351
+ constructor(message) {
352
+ super(message);
353
+ this.name = "InstallError";
354
+ this.hint = `安装 runner 到 ~/.forge-runner 失败:${message}`;
355
+ }
356
+ };
357
+ function bundledNpm(profile) {
358
+ const p = join(profile.root, NODE_DIR, "bin", "npm");
359
+ return existsSync(p) ? p : "npm";
360
+ }
361
+ function runnerEntryPath(profile) {
362
+ return join(profile.root, BIN_DIR, RUNNER_BIN_NAME);
363
+ }
364
+ async function installRunnerPackage(opts) {
365
+ const { profile, version } = opts;
366
+ const run = opts.run ?? defaultRun$1;
367
+ const prefix = join(profile.root, PKG_DIR);
368
+ mkdirSync(prefix, {
369
+ recursive: true,
370
+ mode: DIR_MODE
371
+ });
372
+ const res = await run(bundledNpm(profile), [
373
+ "i",
374
+ "--prefix",
375
+ prefix,
376
+ `${CLI_PACKAGE}@${version}`
377
+ ]);
378
+ if (res.code !== 0) throw new InstallError(`npm exited ${res.code}: ${res.output.trim().slice(-300)}`);
379
+ const pkgDir = join(prefix, "node_modules", CLI_PACKAGE);
380
+ const binRel = readBinPath(pkgDir);
381
+ const entry = runnerEntryPath(profile);
382
+ mkdirSync(join(profile.root, BIN_DIR), {
383
+ recursive: true,
384
+ mode: DIR_MODE
385
+ });
386
+ writeFileSync(entry, `#!/bin/sh\nexec ${shQuote(opts.nodePath ?? process.execPath)} ${shQuote(join(pkgDir, binRel))} "$@"\n`);
387
+ chmodSync(entry, ENTRY_MODE);
388
+ return entry;
389
+ }
390
+ function readBinPath(pkgDir) {
391
+ let bin;
392
+ try {
393
+ bin = JSON.parse(readFileSync(join(pkgDir, "package.json"), "utf8")).bin;
394
+ } catch (e) {
395
+ throw new InstallError(`read package.json of installed package: ${e.message}`);
396
+ }
397
+ const rel = typeof bin === "string" ? bin : bin?.[CLI_PACKAGE];
398
+ if (typeof rel !== "string" || rel === "") throw new InstallError("installed package has no bin entry");
399
+ return rel;
400
+ }
401
+ function shQuote(s) {
402
+ return `'${s.replace(/'/g, "'\\''")}'`;
403
+ }
404
+ function defaultRun$1(cmd, args) {
405
+ return new Promise((resolve, reject) => {
406
+ execFile(cmd, args, {
407
+ timeout: NPM_TIMEOUT_MS$1,
408
+ maxBuffer: NPM_MAX_BUFFER$1
409
+ }, (err, stdout, stderr) => {
410
+ const output = `${stdout}${stderr}`;
411
+ if (!err) {
412
+ resolve({
413
+ code: 0,
414
+ output
415
+ });
416
+ return;
417
+ }
418
+ const code = err.code;
419
+ if (typeof code === "number") {
420
+ resolve({
421
+ code,
422
+ output: output || err.message
423
+ });
424
+ return;
425
+ }
426
+ reject(err);
427
+ });
428
+ });
429
+ }
430
+ const REGISTER_PATH = "/runner/register";
431
+ const ERR_BIND_CODE_INVALID = "bind_code_invalid";
432
+ const GIB = 1024 ** 3;
433
+ const SW_VERS_TIMEOUT_MS = 5e3;
434
+ var BindCodeInvalidError = class extends RunnerApiError {
435
+ hint = "绑定码无效、已过期或已被使用,请回到页面重新生成绑定码后再试";
436
+ constructor(status, code, detail) {
437
+ super(status, code, detail);
438
+ this.name = "BindCodeInvalidError";
439
+ }
440
+ };
441
+ var CliTokenRejectedError = class extends RunnerApiError {
442
+ hint = "CLI 登录令牌被平台拒绝,请确认浏览器里登录的是同一个门户,然后重新运行 runner setup";
443
+ constructor(status, code, detail) {
444
+ super(status, code, detail);
445
+ this.name = "CliTokenRejectedError";
446
+ }
447
+ };
448
+ var LoginRequiredError = class extends Error {
449
+ hint = "浏览器登录未完成,请重新运行 runner setup 并在浏览器里完成登录";
450
+ constructor() {
451
+ super("cli login did not produce a token");
452
+ this.name = "LoginRequiredError";
453
+ }
454
+ };
455
+ const defaultCliLogin = {
456
+ token: (portal) => samePortal(portal, loadConfig().portal) ? loadConfig().token : void 0,
457
+ login: async (portal) => {
458
+ if (!samePortal(portal, loadConfig().portal)) return runLogin({
459
+ force: true,
460
+ portal,
461
+ save: false
462
+ });
463
+ await runLogin({
464
+ force: true,
465
+ portal
466
+ });
467
+ return readSavedCliToken();
468
+ }
469
+ };
470
+ function samePortal(a, b) {
471
+ try {
472
+ return normalizePortalURL(a) === normalizePortalURL(b);
473
+ } catch {
474
+ return false;
475
+ }
476
+ }
477
+ function readSavedCliToken(file = getConfigFile()) {
478
+ let data;
479
+ try {
480
+ data = JSON.parse(readFileSync(file, "utf8"));
481
+ } catch {
482
+ return;
483
+ }
484
+ const token = data?.token;
485
+ return typeof token === "string" && token !== "" ? token : void 0;
486
+ }
487
+ async function registerWithBindCode(code, opts) {
488
+ const bindCode = code.trim();
489
+ if (bindCode === "") throw new Error("bind code is empty");
490
+ const http = new PlatformHttp({ portal: opts.portal });
491
+ let data;
492
+ try {
493
+ data = await http.call("POST", REGISTER_PATH, { body: {
494
+ bind_code: bindCode,
495
+ ...registerBody(opts)
496
+ } });
497
+ } catch (e) {
498
+ if (e instanceof RunnerApiError && e.code === ERR_BIND_CODE_INVALID) throw new BindCodeInvalidError(e.status, e.code, e.detail);
499
+ throw e;
500
+ }
501
+ return saveCredentials(opts, data);
502
+ }
503
+ async function registerWithLogin(opts) {
504
+ const login = opts.login ?? defaultCliLogin;
505
+ const portal = normalizePortalURL(opts.portal);
506
+ const body = registerBody(opts);
507
+ const http = new PlatformHttp({ portal });
508
+ const registerOnce = async (token) => {
509
+ try {
510
+ return await http.call("POST", REGISTER_PATH, {
511
+ body,
512
+ headers: { Authorization: BEARER_PREFIX + token }
513
+ });
514
+ } catch (e) {
515
+ if (e instanceof RunnerApiError && e.status === HTTP_UNAUTHORIZED) throw new CliTokenRejectedError(e.status, e.code, e.detail);
516
+ throw e;
517
+ }
518
+ };
519
+ let token = login.token(portal);
520
+ let freshLogin = false;
521
+ if (!token) {
522
+ token = await loginForToken(login, portal);
523
+ freshLogin = true;
524
+ }
525
+ let data;
526
+ try {
527
+ data = await registerOnce(token);
528
+ } catch (e) {
529
+ if (!(e instanceof CliTokenRejectedError) || freshLogin) throw e;
530
+ data = await registerOnce(await loginForToken(login, portal));
531
+ }
532
+ return saveCredentials(opts, data);
533
+ }
534
+ function collectHostFacts() {
535
+ return {
536
+ host: hostname(),
537
+ os: process.platform,
538
+ arch: process.arch,
539
+ os_version: osVersion(),
540
+ hw: hostHardware()
541
+ };
542
+ }
543
+ function hostHardware() {
544
+ return {
545
+ cores: cpus().length,
546
+ mem_gb: Math.round(totalmem() / GIB)
547
+ };
548
+ }
549
+ async function loginForToken(login, portal) {
550
+ const token = await login.login(portal);
551
+ if (!token) throw new LoginRequiredError();
552
+ return token;
553
+ }
554
+ function registerBody(opts) {
555
+ const facts = opts.facts ?? collectHostFacts();
556
+ return {
557
+ host: facts.host,
558
+ os: facts.os,
559
+ arch: facts.arch,
560
+ os_version: facts.os_version,
561
+ cli_version: opts.cliVersion,
562
+ instance_id: opts.instanceId ?? opts.profile.instanceId(),
563
+ runtimes: opts.runtimes,
564
+ hw: facts.hw
565
+ };
566
+ }
567
+ function saveCredentials(opts, data) {
568
+ const runnerId = data?.runner_id;
569
+ const runnerToken = data?.runner_token;
570
+ if (typeof runnerId !== "string" || runnerId === "") throw new Error(`invalid register response: runner_id=${JSON.stringify(runnerId)}`);
571
+ if (typeof runnerToken !== "string" || runnerToken === "") throw new Error("invalid register response: empty runner_token");
572
+ const serverHost = data.portal_host;
573
+ const wsPath = data.ws_path;
574
+ const creds = {
575
+ portalHost: typeof serverHost === "string" && serverHost !== "" ? serverHost : portalHostOf(opts.portal),
576
+ runnerId,
577
+ runnerToken,
578
+ portal: normalizePortalURL(opts.portal),
579
+ wsPath: typeof wsPath === "string" && wsPath !== "" ? wsPath : DEFAULT_WS_PATH
580
+ };
581
+ opts.profile.writeCredentials(creds);
582
+ return creds;
583
+ }
584
+ function osVersion() {
585
+ if (process.platform !== "darwin") return release();
586
+ try {
587
+ const out = execFileSync("sw_vers", ["-productVersion"], {
588
+ encoding: "utf8",
589
+ timeout: SW_VERS_TIMEOUT_MS,
590
+ stdio: [
591
+ "ignore",
592
+ "pipe",
593
+ "ignore"
594
+ ]
595
+ }).trim();
596
+ return out === "" ? release() : out;
597
+ } catch {
598
+ return release();
599
+ }
600
+ }
601
+ const UPDATE_ERROR_FILE = "update_error.json";
602
+ const UPDATE_LOCK_FILE = "update.lock";
603
+ const RETRY_BACKOFF_MS = 36e5;
604
+ const NPM_TIMEOUT_MS = 10 * 6e4;
605
+ const MESSAGE_MAX_CHARS = 500;
606
+ const NPM_MAX_BUFFER = 4 * 1024 * 1024;
607
+ const VERSION_RE = /^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/;
608
+ function readUpdateError(profile) {
609
+ let data;
610
+ try {
611
+ data = JSON.parse(readFileSync(join(profile.root, UPDATE_ERROR_FILE), "utf8"));
612
+ } catch {
613
+ return;
614
+ }
615
+ const rec = data;
616
+ if (typeof rec?.version !== "string" || typeof rec.message !== "string") return;
617
+ return {
618
+ version: rec.version,
619
+ message: rec.message,
620
+ ...typeof rec.at === "string" ? { at: rec.at } : {}
621
+ };
622
+ }
623
+ function writeUpdateError(profile, err) {
624
+ mkdirSync(profile.root, {
625
+ recursive: true,
626
+ mode: DIR_MODE
627
+ });
628
+ writeFileSync(join(profile.root, UPDATE_ERROR_FILE), `${JSON.stringify(err, null, 2)}\n`, { mode: FILE_MODE });
629
+ }
630
+ function clearUpdateError(profile) {
631
+ rmSync(join(profile.root, UPDATE_ERROR_FILE), { force: true });
632
+ }
633
+ let updating = false;
634
+ async function performUpdate(opts) {
635
+ const { version, profile } = opts;
636
+ const run = opts.run ?? ((cmd, args) => defaultRun(cmd, args));
637
+ const exit = opts.exit ?? (() => process.exit(0));
638
+ const now = opts.now ?? Date.now;
639
+ if (!VERSION_RE.test(version)) {
640
+ writeUpdateError(profile, {
641
+ version,
642
+ message: `invalid version: ${JSON.stringify(version)}`
643
+ });
644
+ return {
645
+ ok: false,
646
+ version
647
+ };
648
+ }
649
+ const last = readUpdateError(profile);
650
+ if (last?.version === version && last.at !== void 0 && now() - Date.parse(last.at) < RETRY_BACKOFF_MS) return {
651
+ ok: false,
652
+ version,
653
+ skipped: "recent_failure"
654
+ };
655
+ if (updating || !takeLock(profile)) return {
656
+ ok: false,
657
+ version,
658
+ skipped: "busy"
659
+ };
660
+ updating = true;
661
+ try {
662
+ const prefix = join(profile.root, PKG_DIR);
663
+ let outcome;
664
+ try {
665
+ outcome = await run(bundledNpm(profile), [
666
+ "i",
667
+ "--prefix",
668
+ prefix,
669
+ `${CLI_PACKAGE}@${version}`
670
+ ]);
671
+ } catch (e) {
672
+ outcome = {
673
+ code: -1,
674
+ output: e instanceof Error ? e.message : String(e)
675
+ };
676
+ }
677
+ if (outcome.code !== 0) {
678
+ writeUpdateError(profile, {
679
+ version,
680
+ message: tail(outcome.output),
681
+ at: new Date(now()).toISOString()
682
+ });
683
+ return {
684
+ ok: false,
685
+ version
686
+ };
687
+ }
688
+ clearUpdateError(profile);
689
+ } finally {
690
+ updating = false;
691
+ rmSync(join(profile.root, UPDATE_LOCK_FILE), { force: true });
692
+ }
693
+ exit();
694
+ return {
695
+ ok: true,
696
+ version
697
+ };
698
+ }
699
+ function takeLock(profile) {
700
+ const path = join(profile.root, UPDATE_LOCK_FILE);
701
+ mkdirSync(profile.root, {
702
+ recursive: true,
703
+ mode: DIR_MODE
704
+ });
705
+ for (let i = 0; i < 2; i++) {
706
+ try {
707
+ writeFileSync(path, String(process.pid), {
708
+ mode: FILE_MODE,
709
+ flag: "wx"
710
+ });
711
+ return true;
712
+ } catch (e) {
713
+ if (e.code !== "EEXIST") throw e;
714
+ }
715
+ const pid = Number(readLockPid(path));
716
+ if (Number.isInteger(pid) && pid > 0 && pidAlive(pid)) return false;
717
+ rmSync(path, { force: true });
718
+ }
719
+ return false;
720
+ }
721
+ function readLockPid(path) {
722
+ try {
723
+ return readFileSync(path, "utf8").trim();
724
+ } catch {
725
+ return "";
726
+ }
727
+ }
728
+ function pidAlive(pid) {
729
+ try {
730
+ process.kill(pid, 0);
731
+ return true;
732
+ } catch (e) {
733
+ return e.code === "EPERM";
734
+ }
735
+ }
736
+ function tail(text) {
737
+ const t = text.trim();
738
+ return t.length <= MESSAGE_MAX_CHARS ? t : t.slice(t.length - MESSAGE_MAX_CHARS);
739
+ }
740
+ function defaultRun(cmd, args) {
741
+ return new Promise((resolve, reject) => {
742
+ execFile(cmd, args, {
743
+ timeout: NPM_TIMEOUT_MS,
744
+ maxBuffer: NPM_MAX_BUFFER
745
+ }, (err, stdout, stderr) => {
746
+ const output = `${stdout}${stderr}`;
747
+ if (!err) {
748
+ resolve({
749
+ code: 0,
750
+ output
751
+ });
752
+ return;
753
+ }
754
+ const code = err.code;
755
+ if (typeof code === "number") {
756
+ resolve({
757
+ code,
758
+ output: output || err.message
759
+ });
760
+ return;
761
+ }
762
+ reject(err);
763
+ });
764
+ });
765
+ }
766
+ const HEARTBEAT_PATH = "/runner/heartbeat";
767
+ const HEARTBEAT_INTERVAL_MS = 15e3;
768
+ const BACKOFF_BASE_MS = 1e3;
769
+ const BACKOFF_MAX_MS = 6e4;
770
+ const ACTION_PROBE = "probe";
771
+ const ACTION_DOCTOR = "doctor";
772
+ const ACTION_UPDATE = "update";
773
+ const ACTION_CONFIG = "config";
774
+ var Heartbeat = class {
775
+ failures = 0;
776
+ halted = false;
777
+ inflight = /* @__PURE__ */ new Set();
778
+ intervalMs;
779
+ hw;
780
+ constructor(opts) {
781
+ this.opts = opts;
782
+ this.intervalMs = opts.intervalMs ?? HEARTBEAT_INTERVAL_MS;
783
+ this.hw = opts.hw ?? hostHardware;
784
+ }
785
+ async send(req) {
786
+ if (this.halted) return;
787
+ let data;
788
+ try {
789
+ data = await this.opts.host.api().call("POST", HEARTBEAT_PATH, { body: this.body(req) });
790
+ } catch (e) {
791
+ this.onFailure(e);
792
+ throw e;
793
+ }
794
+ this.failures = 0;
795
+ this.apply(data ?? {});
796
+ }
797
+ nextDelayMs() {
798
+ if (this.halted || this.failures === 0) return this.intervalMs;
799
+ return Math.min(BACKOFF_BASE_MS * 2 ** (this.failures - 1), BACKOFF_MAX_MS);
800
+ }
801
+ async settled() {
802
+ while (this.inflight.size > 0) await Promise.allSettled([...this.inflight]);
803
+ }
804
+ body(req) {
805
+ const body = {
806
+ ...req,
807
+ hw: this.hw()
808
+ };
809
+ const err = readUpdateError(this.opts.profile);
810
+ if (err && versionAtLeast(req.cli_version, err.version)) clearUpdateError(this.opts.profile);
811
+ else if (err) body.update_error = {
812
+ version: err.version,
813
+ message: err.message
814
+ };
815
+ return body;
816
+ }
817
+ onFailure(e) {
818
+ if (e instanceof RunnerTokenInvalidError) {
819
+ this.halted = true;
820
+ this.opts.host.onTokenInvalid(e);
821
+ return;
822
+ }
823
+ if (e instanceof RunnerSupersededError) {
824
+ this.opts.host.onSuperseded(e);
825
+ return;
826
+ }
827
+ this.failures++;
828
+ }
829
+ apply(data) {
830
+ const { host } = this.opts;
831
+ let configReady = Promise.resolve();
832
+ const version = data.config_version;
833
+ if (typeof version === "number" && version !== host.configVersion()) {
834
+ configReady = host.refreshConfig().catch((e) => {
835
+ host.log("warn", "refresh runner config failed", {
836
+ error: errText(e),
837
+ config_version: version
838
+ });
839
+ });
840
+ this.track(ACTION_CONFIG, configReady);
841
+ }
842
+ const minVersion = typeof data.min_version === "string" ? data.min_version : "";
843
+ const actions = Array.isArray(data.actions) ? data.actions : [];
844
+ for (const action of actions) this.trigger(String(action), minVersion, configReady);
845
+ }
846
+ trigger(action, minVersion, configReady) {
847
+ const { host } = this.opts;
848
+ switch (action) {
849
+ case ACTION_PROBE:
850
+ this.track(action, host.probe());
851
+ break;
852
+ case ACTION_DOCTOR:
853
+ this.track(action, configReady.then(() => host.doctor()));
854
+ break;
855
+ case ACTION_CONFIG:
856
+ this.track(action, host.refreshConfig());
857
+ break;
858
+ case ACTION_UPDATE:
859
+ if (minVersion === "") {
860
+ host.log("warn", "heartbeat update action without min_version", { action });
861
+ break;
862
+ }
863
+ this.track(action, host.update(minVersion));
864
+ break;
865
+ default: host.log("warn", "unknown heartbeat action", { action });
866
+ }
867
+ }
868
+ track(action, task) {
869
+ const p = task.catch((e) => {
870
+ this.opts.host.log("warn", "heartbeat action failed", {
871
+ action,
872
+ error: errText(e)
873
+ });
874
+ }).finally(() => {
875
+ this.inflight.delete(p);
876
+ });
877
+ this.inflight.add(p);
878
+ }
879
+ };
880
+ const SEMVER_RE = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;
881
+ function versionAtLeast(current, target) {
882
+ const a = SEMVER_RE.exec(current.trim());
883
+ const b = SEMVER_RE.exec(target.trim());
884
+ if (!a || !b) return false;
885
+ for (let i = 1; i <= 3; i++) {
886
+ const diff = Number(a[i]) - Number(b[i]);
887
+ if (diff !== 0) return diff > 0;
888
+ }
889
+ return comparePrerelease(a[4], b[4]) >= 0;
890
+ }
891
+ function comparePrerelease(a, b) {
892
+ if (a === void 0 || b === void 0) return a === b ? 0 : a === void 0 ? 1 : -1;
893
+ const pa = a.split(".");
894
+ const pb = b.split(".");
895
+ for (let i = 0; i < Math.min(pa.length, pb.length); i++) {
896
+ const x = pa[i];
897
+ const y = pb[i];
898
+ if (x === y) continue;
899
+ const nx = /^\d+$/.test(x);
900
+ const ny = /^\d+$/.test(y);
901
+ if (nx && ny) return Number(x) - Number(y);
902
+ if (nx !== ny) return nx ? -1 : 1;
903
+ return x < y ? -1 : 1;
904
+ }
905
+ return pa.length - pb.length;
906
+ }
907
+ function errText(e) {
908
+ return e instanceof Error ? e.message : String(e);
909
+ }
910
+ export { healthPort as C, normalizePortalURL as D, RunnerApiError as E, portalHostOf as O, RunnerProfile as S, PlatformHttp as T, DIR_MODE as _, HEARTBEAT_INTERVAL_MS as a, ROOT_DIR as b, clearUpdateError as c, LoginRequiredError as d, registerWithBindCode as f, BIN_DIR as g, installRunnerPackage as h, BACKOFF_MAX_MS as i, performUpdate as l, InstallError as m, ACTION_PROBE as n, HEARTBEAT_PATH as o, registerWithLogin as p, BACKOFF_BASE_MS as r, Heartbeat as s, ACTION_DOCTOR as t, readUpdateError as u, FILE_MODE as v, normalizeDoctorTargets as w, RUNNER_BIN_NAME as x, NODE_DIR as y };