shoplazza-ai-dev-cli 0.1.21 → 0.1.22-snapshot.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.
@@ -0,0 +1,2265 @@
1
+ import "./rolldown-runtime.mjs";
2
+ import "./libs/@clack/core.mjs";
3
+ import "./libs/@clack/prompts.mjs";
4
+ import { i as loadConfig, t as LoginFailedError } from "../cli.mjs";
5
+ import { C as healthPort, D as normalizePortalURL, E as RunnerApiError, O as portalHostOf, S as RunnerProfile, T as PlatformHttp, _ as DIR_MODE, b as ROOT_DIR, c as clearUpdateError, d as LoginRequiredError, f as registerWithBindCode, g as BIN_DIR, h as installRunnerPackage, i as BACKOFF_MAX_MS, l as performUpdate, m as InstallError, n as ACTION_PROBE, p as registerWithLogin, r as BACKOFF_BASE_MS, s as Heartbeat, t as ACTION_DOCTOR, u as readUpdateError, v as FILE_MODE, w as normalizeDoctorTargets, x as RUNNER_BIN_NAME, y as NODE_DIR } from "./heartbeat.mjs";
6
+ import { i as sessionTokenOf, n as isSessionPath, r as missingTokenReply, t as forwardSession } from "./session-forward.mjs";
7
+ import { createInterface } from "node:readline";
8
+ import { accessSync, chmodSync, constants, existsSync, linkSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
9
+ import { delimiter, dirname, isAbsolute, join } from "node:path";
10
+ import { execFile, execFileSync, spawn } from "node:child_process";
11
+ import { homedir, tmpdir, uptime } from "node:os";
12
+ import { randomUUID } from "node:crypto";
13
+ import { createServer } from "node:http";
14
+ const DOCTOR_REPORT_PATH = "/runner/doctor-report";
15
+ const DOCTOR_LABELS = {
16
+ claude: "Claude Code",
17
+ codex: "Codex",
18
+ git: "本机 git 凭据",
19
+ gitlab: "GitLab 连通",
20
+ publish: "发布平台连通"
21
+ };
22
+ const DEFAULT_GIT_TIMEOUT_MS = 15e3;
23
+ const DEFAULT_NET_TIMEOUT_MS = 8e3;
24
+ const SSH_CONNECT_TIMEOUT_S = 8;
25
+ const HTTP_SERVER_ERROR = 500;
26
+ const REASON_MAX_CHARS = 200;
27
+ const MAX_REPOS = 3;
28
+ const NOT_CONFIGURED = "平台未配置";
29
+ const PROBE_BRANCH = "refs/heads/forge-runner-doctor-probe";
30
+ const SSH_KEYS = [
31
+ "id_ed25519",
32
+ "id_ecdsa",
33
+ "id_rsa"
34
+ ];
35
+ const FEISHU_NOTE = "飞书连通由服务端检查,不在本机自检里。";
36
+ async function runDoctor(opts) {
37
+ const { gitlab_url: gitlabURL, publish_url: publishURL } = opts.targets;
38
+ const netTimeoutMs = opts.netTimeoutMs ?? DEFAULT_NET_TIMEOUT_MS;
39
+ const [runtimes, git, gitlab, publish] = await Promise.all([
40
+ detectRuntimes(opts.detector),
41
+ guard("git", () => checkGit(opts)),
42
+ guard("gitlab", () => gitlabURL === "" ? Promise.resolve({
43
+ key: "gitlab",
44
+ ok: false,
45
+ detail: NOT_CONFIGURED
46
+ }) : checkReach(gitlabURL, netTimeoutMs, true)),
47
+ guard("publish", () => publishURL === "" ? Promise.resolve({
48
+ key: "publish",
49
+ ok: false,
50
+ detail: NOT_CONFIGURED
51
+ }) : checkReach(publishURL, netTimeoutMs, false))
52
+ ]);
53
+ return {
54
+ items: [
55
+ runtimeItem("claude", runtimes),
56
+ runtimeItem("codex", runtimes),
57
+ git,
58
+ gitlab,
59
+ publish
60
+ ],
61
+ at: (/* @__PURE__ */ new Date()).toISOString()
62
+ };
63
+ }
64
+ async function reportDoctor(http, report) {
65
+ await http.call("POST", DOCTOR_REPORT_PATH, { body: report });
66
+ }
67
+ function formatDoctorReport(report) {
68
+ const lines = report.items.map((item) => {
69
+ return `${DOCTOR_LABELS[item.key].padEnd(12, " ")}${item.ok ? "正常 " : "有问题"} ${item.detail}`;
70
+ });
71
+ lines.push(FEISHU_NOTE);
72
+ return lines;
73
+ }
74
+ async function guard(key, fn) {
75
+ try {
76
+ return await fn();
77
+ } catch (e) {
78
+ return {
79
+ key,
80
+ ok: false,
81
+ detail: `检查出错:${shorten(e instanceof Error ? e.message : String(e))}`
82
+ };
83
+ }
84
+ }
85
+ async function detectRuntimes(detector) {
86
+ try {
87
+ return await detector.detect({ force: true });
88
+ } catch (e) {
89
+ return e instanceof Error ? e : new Error(String(e));
90
+ }
91
+ }
92
+ function runtimeItem(kind, runtimes) {
93
+ const key = kind;
94
+ if (runtimes instanceof Error) return {
95
+ key,
96
+ ok: false,
97
+ detail: `检测出错:${shorten(runtimes.message)}`
98
+ };
99
+ const info = runtimes.find((r) => r.kind === kind);
100
+ const ignorable = kind === "codex" ? "(不用 Codex 可忽略)" : "";
101
+ if (!info) return {
102
+ key,
103
+ ok: false,
104
+ detail: `未安装${ignorable}`
105
+ };
106
+ if (info.logged_in === true) return {
107
+ key,
108
+ ok: true,
109
+ detail: `${info.version} · 已登录`
110
+ };
111
+ if (info.logged_in === false) {
112
+ const hint = kind === "codex" ? `未登录,执行 codex login${ignorable}` : "未登录,按运行时清单的指引登录";
113
+ return {
114
+ key,
115
+ ok: false,
116
+ detail: `${info.version} · ${hint}`
117
+ };
118
+ }
119
+ return {
120
+ key,
121
+ ok: false,
122
+ detail: `${info.version} · 登录状态无法确认,请在终端执行 ${kind} 确认`
123
+ };
124
+ }
125
+ async function checkGit(opts) {
126
+ const { gitlab_url: gitlabURL, repos } = opts.targets;
127
+ const host = gitlabURL !== "" ? new URL(gitlabURL).hostname : repoHost(repos[0]);
128
+ if (host === void 0) return {
129
+ key: "git",
130
+ ok: false,
131
+ detail: NOT_CONFIGURED
132
+ };
133
+ const timeoutMs = opts.gitTimeoutMs ?? DEFAULT_GIT_TIMEOUT_MS;
134
+ const baseEnv = opts.env ?? process.env;
135
+ const env = {
136
+ ...baseEnv,
137
+ GIT_TERMINAL_PROMPT: "0",
138
+ GIT_SSH_COMMAND: baseEnv.GIT_SSH_COMMAND ?? `ssh -o BatchMode=yes -o ConnectTimeout=${SSH_CONNECT_TIMEOUT_S}`
139
+ };
140
+ const probeRepos = repos.slice(0, MAX_REPOS);
141
+ const label = credentialLabel(opts.home ?? homedir(), probeRepos[0]);
142
+ if (probeRepos.length === 0) {
143
+ const res = await runCommand$1("ssh", [
144
+ "-T",
145
+ "-o",
146
+ "BatchMode=yes",
147
+ "-o",
148
+ `ConnectTimeout=${SSH_CONNECT_TIMEOUT_S}`,
149
+ `git@${host}`
150
+ ], {
151
+ env,
152
+ timeoutMs
153
+ });
154
+ if (res.ok) return {
155
+ key: "git",
156
+ ok: true,
157
+ detail: `${label} · 已通过 ${host} 的 SSH 认证(平台没给探测仓库,未验证推送权限)`
158
+ };
159
+ return {
160
+ key: "git",
161
+ ok: false,
162
+ detail: `SSH 认证失败:${reasonOf(res)}`
163
+ };
164
+ }
165
+ const results = await Promise.all(probeRepos.map((repo) => probeRepo(repo, env, timeoutMs)));
166
+ if (results.some((r) => r.ok)) return {
167
+ key: "git",
168
+ ok: true,
169
+ detail: `${label} · 能推 ${host};推送被拒时节点转阻塞,不另填令牌`
170
+ };
171
+ return {
172
+ key: "git",
173
+ ok: false,
174
+ detail: results.map((r) => `${r.stage === "read" ? "无法读取" : "能读取但无法推送"} ${r.repo}:${r.reason}`).join(";")
175
+ };
176
+ }
177
+ function repoHost(repo) {
178
+ if (repo === void 0 || repo === "") return;
179
+ const scp = /^[^@/\s]+@([^:/\s]+):/.exec(repo);
180
+ if (scp) return scp[1];
181
+ try {
182
+ return new URL(repo).hostname || void 0;
183
+ } catch {
184
+ return;
185
+ }
186
+ }
187
+ async function probeRepo(repo, env, timeoutMs) {
188
+ const read = await runCommand$1("git", [
189
+ "ls-remote",
190
+ "--heads",
191
+ repo
192
+ ], {
193
+ env,
194
+ timeoutMs
195
+ });
196
+ if (!read.ok) return {
197
+ repo,
198
+ ok: false,
199
+ stage: "read",
200
+ reason: reasonOf(read)
201
+ };
202
+ const push = await dryRunPush(repo, env, timeoutMs);
203
+ return {
204
+ repo,
205
+ ok: push.ok,
206
+ stage: "push",
207
+ reason: push.ok ? "" : reasonOf(push)
208
+ };
209
+ }
210
+ async function dryRunPush(repo, env, timeoutMs) {
211
+ const work = mkdtempSync(join(tmpdir(), "forge-doctor-"));
212
+ try {
213
+ const noHooks = [
214
+ "-c",
215
+ "commit.gpgsign=false",
216
+ "-c",
217
+ "core.hooksPath=/dev/null"
218
+ ];
219
+ const steps = [
220
+ ["init", "-q"],
221
+ [
222
+ ...noHooks,
223
+ "-c",
224
+ "user.name=forge-doctor",
225
+ "-c",
226
+ "user.email=forge-doctor@localhost",
227
+ "commit",
228
+ "-q",
229
+ "--no-verify",
230
+ "--allow-empty",
231
+ "-m",
232
+ "probe"
233
+ ],
234
+ [
235
+ ...noHooks,
236
+ "push",
237
+ "--dry-run",
238
+ "--no-verify",
239
+ repo,
240
+ `HEAD:${PROBE_BRANCH}`
241
+ ]
242
+ ];
243
+ let last = {
244
+ ok: true,
245
+ ended: "exit",
246
+ stderr: ""
247
+ };
248
+ for (const args of steps) {
249
+ last = await runCommand$1("git", args, {
250
+ env,
251
+ timeoutMs,
252
+ cwd: work
253
+ });
254
+ if (!last.ok) break;
255
+ }
256
+ return last;
257
+ } finally {
258
+ rmSync(work, {
259
+ recursive: true,
260
+ force: true
261
+ });
262
+ }
263
+ }
264
+ function credentialLabel(home, repo) {
265
+ const key = SSH_KEYS.find((k) => existsSync(join(home, ".ssh", k)));
266
+ if (key !== void 0 && !(repo ?? "").startsWith("http")) return `SSH 密钥 ~/.ssh/${key}`;
267
+ return repo?.startsWith("http") ? "git 凭据" : "SSH 密钥";
268
+ }
269
+ async function checkReach(url, timeoutMs, withLatency) {
270
+ const key = withLatency ? "gitlab" : "publish";
271
+ const host = new URL(url.includes("://") ? url : `https://${url}`).host;
272
+ const started = performance.now();
273
+ let status;
274
+ try {
275
+ const res = await fetch(url, {
276
+ redirect: "manual",
277
+ signal: AbortSignal.timeout(timeoutMs)
278
+ });
279
+ status = res.status;
280
+ await res.body?.cancel();
281
+ } catch (e) {
282
+ return {
283
+ key,
284
+ ok: false,
285
+ detail: `${host} · 连不上:${netReason(e)}`
286
+ };
287
+ }
288
+ if (status >= HTTP_SERVER_ERROR) return {
289
+ key,
290
+ ok: false,
291
+ detail: `${host} · HTTP ${status}`
292
+ };
293
+ const ms = Math.round(performance.now() - started);
294
+ return {
295
+ key,
296
+ ok: true,
297
+ detail: withLatency ? `${host} · ${ms} ms` : `${host} · 正常`
298
+ };
299
+ }
300
+ function netReason(e) {
301
+ const err = e;
302
+ if (err?.name === "TimeoutError") return "超时";
303
+ return shorten(err?.cause?.code ?? err?.cause?.message ?? err?.message ?? String(e));
304
+ }
305
+ function reasonOf(res) {
306
+ if (res.ended === "timeout") return "命令超时";
307
+ return shorten(res.stderr) || "命令失败";
308
+ }
309
+ function runCommand$1(cmd, args, o) {
310
+ return new Promise((resolve) => {
311
+ let settled = false;
312
+ let stderr = "";
313
+ const done = (r) => {
314
+ if (settled) return;
315
+ settled = true;
316
+ clearTimeout(timer);
317
+ resolve(r);
318
+ };
319
+ const child = spawn(cmd, args, {
320
+ env: o.env,
321
+ cwd: o.cwd,
322
+ stdio: [
323
+ "ignore",
324
+ "ignore",
325
+ "pipe"
326
+ ],
327
+ detached: process.platform !== "win32"
328
+ });
329
+ child.stderr.on("data", (c) => {
330
+ if (stderr.length < REASON_MAX_CHARS * 20) stderr += c.toString("utf8");
331
+ });
332
+ const timer = setTimeout(() => {
333
+ try {
334
+ if (child.pid !== void 0 && process.platform !== "win32") process.kill(-child.pid, "SIGKILL");
335
+ else child.kill("SIGKILL");
336
+ } catch {}
337
+ done({
338
+ ok: false,
339
+ ended: "timeout",
340
+ stderr: ""
341
+ });
342
+ }, o.timeoutMs);
343
+ child.on("error", (e) => done({
344
+ ok: false,
345
+ ended: "error",
346
+ stderr: e.message
347
+ }));
348
+ child.on("close", (code) => done({
349
+ ok: code === 0,
350
+ ended: "exit",
351
+ stderr
352
+ }));
353
+ });
354
+ }
355
+ function shorten(text) {
356
+ const flat = text.replace(/\s+/g, " ").trim();
357
+ return flat.length <= REASON_MAX_CHARS ? flat : flat.slice(0, REASON_MAX_CHARS);
358
+ }
359
+ var RunnerLockedError = class extends Error {
360
+ constructor(holderPid, lockPath) {
361
+ super(`runner lock is held by pid ${holderPid}: ${lockPath}`);
362
+ this.holderPid = holderPid;
363
+ this.lockPath = lockPath;
364
+ this.name = "RunnerLockedError";
365
+ }
366
+ };
367
+ const BOOT_SKEW_MS = 6e4;
368
+ const START_SKEW_MS = 2e3;
369
+ const MAX_ATTEMPTS = 5;
370
+ let bootIdCache;
371
+ function currentBootId() {
372
+ bootIdCache ??= readBootId();
373
+ return bootIdCache;
374
+ }
375
+ function readBootId() {
376
+ try {
377
+ if (process.platform === "linux") return readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim();
378
+ if (process.platform === "darwin") return execFileSync("sysctl", ["-n", "kern.bootsessionuuid"], {
379
+ encoding: "utf8",
380
+ stdio: [
381
+ "ignore",
382
+ "pipe",
383
+ "ignore"
384
+ ]
385
+ }).trim();
386
+ } catch {}
387
+ return "";
388
+ }
389
+ function currentBootAt() {
390
+ return Date.now() - uptime() * 1e3;
391
+ }
392
+ function acquireRunnerLock(lockPath) {
393
+ mkdirSync(dirname(lockPath), {
394
+ recursive: true,
395
+ mode: DIR_MODE
396
+ });
397
+ const record = {
398
+ pid: process.pid,
399
+ boot_id: currentBootId(),
400
+ boot_at: currentBootAt(),
401
+ token: randomUUID(),
402
+ acquired_at: (/* @__PURE__ */ new Date()).toISOString()
403
+ };
404
+ const content = JSON.stringify(record);
405
+ const tmp = `${lockPath}.${record.token}.tmp`;
406
+ try {
407
+ writeFileSync(tmp, content, {
408
+ mode: FILE_MODE,
409
+ flag: "wx"
410
+ });
411
+ for (let i = 0; i < MAX_ATTEMPTS; i++) {
412
+ if (tryLink(tmp, lockPath)) return newHandle(lockPath, content);
413
+ const seen = readRaw(lockPath);
414
+ if (seen === void 0) continue;
415
+ const holder = parseRecord(seen);
416
+ if (holder && isAlive(holder)) throw new RunnerLockedError(holder.pid, lockPath);
417
+ reclaim(lockPath, seen, record.token);
418
+ }
419
+ } finally {
420
+ rmSync(tmp, { force: true });
421
+ }
422
+ throw new Error(`acquire runner lock: gave up after ${MAX_ATTEMPTS} attempts: ${lockPath}`);
423
+ }
424
+ function inspectRunnerLock(lockPath) {
425
+ const raw = readRaw(lockPath);
426
+ const holder = raw === void 0 ? void 0 : parseRecord(raw);
427
+ return holder && isAlive(holder) ? holder : void 0;
428
+ }
429
+ function tryLink(from, to) {
430
+ try {
431
+ linkSync(from, to);
432
+ } catch (e) {
433
+ if (errCode$1(e) === "EEXIST") return false;
434
+ throw e;
435
+ }
436
+ return true;
437
+ }
438
+ function reclaim(lockPath, staleContent, token) {
439
+ const aside = `${lockPath}.${token}.stale`;
440
+ try {
441
+ renameSync(lockPath, aside);
442
+ } catch (e) {
443
+ if (errCode$1(e) === "ENOENT") return;
444
+ throw e;
445
+ }
446
+ try {
447
+ if (readRaw(aside) !== staleContent) tryLink(aside, lockPath);
448
+ } finally {
449
+ rmSync(aside, { force: true });
450
+ }
451
+ }
452
+ function newHandle(lockPath, content) {
453
+ let released = false;
454
+ return {
455
+ path: lockPath,
456
+ release() {
457
+ if (released) return;
458
+ released = true;
459
+ if (readRaw(lockPath) === content) rmSync(lockPath, { force: true });
460
+ }
461
+ };
462
+ }
463
+ function isAlive(holder) {
464
+ if (!sameBoot(holder)) return false;
465
+ try {
466
+ process.kill(holder.pid, 0);
467
+ } catch (e) {
468
+ if (errCode$1(e) !== "EPERM") return false;
469
+ }
470
+ const startedAt = processStartedAt(holder.pid);
471
+ const acquiredAt = Date.parse(holder.acquired_at);
472
+ if (startedAt === void 0 || Number.isNaN(acquiredAt)) return true;
473
+ return startedAt <= acquiredAt + START_SKEW_MS;
474
+ }
475
+ function sameBoot(holder) {
476
+ const bootId = currentBootId();
477
+ if (bootId && holder.boot_id) return holder.boot_id === bootId;
478
+ return Math.abs(holder.boot_at - currentBootAt()) <= BOOT_SKEW_MS;
479
+ }
480
+ function processStartedAt(pid) {
481
+ if (process.platform === "win32") return;
482
+ let out;
483
+ try {
484
+ out = execFileSync("ps", [
485
+ "-o",
486
+ "lstart=",
487
+ "-p",
488
+ String(pid)
489
+ ], {
490
+ encoding: "utf8",
491
+ env: {
492
+ ...process.env,
493
+ LC_ALL: "C"
494
+ },
495
+ stdio: [
496
+ "ignore",
497
+ "pipe",
498
+ "ignore"
499
+ ]
500
+ });
501
+ } catch {
502
+ return;
503
+ }
504
+ const at = Date.parse(out.trim());
505
+ return Number.isNaN(at) ? void 0 : at;
506
+ }
507
+ function parseRecord(raw) {
508
+ let data;
509
+ try {
510
+ data = JSON.parse(raw);
511
+ } catch {
512
+ return;
513
+ }
514
+ const pid = data?.pid;
515
+ const bootAt = data?.boot_at;
516
+ if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0) return;
517
+ if (typeof bootAt !== "number" || !Number.isFinite(bootAt)) return;
518
+ return data;
519
+ }
520
+ function readRaw(path) {
521
+ try {
522
+ return readFileSync(path, "utf8");
523
+ } catch (e) {
524
+ if (errCode$1(e) === "ENOENT") return;
525
+ throw e;
526
+ }
527
+ }
528
+ function errCode$1(e) {
529
+ return e?.code;
530
+ }
531
+ const CLAIM_SWEEP_CONNECTED_MS = 18e4;
532
+ const CLAIM_SWEEP_DISCONNECTED_MS = 3e4;
533
+ const CLAIM_SWEEP_JITTER_MIN = 1 / 12;
534
+ const CLAIM_SWEEP_JITTER_MAX = 1 / 6;
535
+ var ClaimSweeper = class {
536
+ connected = false;
537
+ running = false;
538
+ timer;
539
+ random;
540
+ constructor(opts) {
541
+ this.opts = opts;
542
+ this.random = opts.random ?? Math.random;
543
+ }
544
+ start() {
545
+ if (this.running) return;
546
+ this.running = true;
547
+ this.schedule();
548
+ }
549
+ stop() {
550
+ this.running = false;
551
+ clearTimeout(this.timer);
552
+ this.timer = void 0;
553
+ }
554
+ setConnected(connected) {
555
+ if (connected === this.connected) return;
556
+ this.connected = connected;
557
+ if (!this.running) return;
558
+ if (connected) this.opts.nudge();
559
+ this.schedule();
560
+ }
561
+ schedule() {
562
+ clearTimeout(this.timer);
563
+ this.timer = setTimeout(() => {
564
+ this.timer = void 0;
565
+ this.opts.nudge();
566
+ this.schedule();
567
+ }, this.nextDelayMs());
568
+ this.timer.unref?.();
569
+ }
570
+ nextDelayMs() {
571
+ if (!this.connected) return CLAIM_SWEEP_DISCONNECTED_MS;
572
+ const jitter = CLAIM_SWEEP_JITTER_MIN + this.random() * (CLAIM_SWEEP_JITTER_MAX - CLAIM_SWEEP_JITTER_MIN);
573
+ return Math.round(CLAIM_SWEEP_CONNECTED_MS * (1 - jitter));
574
+ }
575
+ };
576
+ const PROBE_REPORT_PATH = "/runner/probe-report";
577
+ const LOGIN_CACHE_TTL_MS = 6 * 36e5;
578
+ const UNKNOWN_CACHE_TTL_MS = 5 * 6e4;
579
+ const OUTPUT_LIMIT_BYTES = 256 * 1024;
580
+ const LOGIN_UNKNOWN = "unknown";
581
+ const CLAUDE = "claude";
582
+ const CODEX = "codex";
583
+ const CACHE_FILE = "runtimes.json";
584
+ const VERSION_ARGS = ["--version"];
585
+ const CLAUDE_PING_ARGS = [
586
+ "-p",
587
+ "ping",
588
+ "--max-turns",
589
+ "1",
590
+ "--output-format",
591
+ "json"
592
+ ];
593
+ const CODEX_STATUS_ARGS = ["login", "status"];
594
+ const DEFAULT_VERSION_TIMEOUT_MS = 1e4;
595
+ const DEFAULT_PING_TIMEOUT_MS = 6e4;
596
+ const DEFAULT_STATUS_TIMEOUT_MS = 1e4;
597
+ const VERSION_RE = /\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?/;
598
+ const CLAUDE_LOGGED_OUT_RE = /not logged in|run \/login|invalid api key|oauth token|authentication_error/i;
599
+ const CLAUDE_RESULT_TYPE = "result";
600
+ const CODEX_LOGGED_OUT_RE = /not logged in/i;
601
+ const CODEX_LOGGED_IN_RE = /logged in/i;
602
+ const IS_WINDOWS = process.platform === "win32";
603
+ var RuntimeDetector = class {
604
+ last = [];
605
+ inflight;
606
+ home;
607
+ pathEnv;
608
+ now;
609
+ cachePath;
610
+ constructor(opts) {
611
+ this.opts = opts;
612
+ this.home = opts.home ?? homedir();
613
+ this.pathEnv = opts.pathEnv ?? process.env.PATH ?? "";
614
+ this.now = opts.now ?? Date.now;
615
+ this.cachePath = join(opts.profile.root, CACHE_FILE);
616
+ }
617
+ detect(opts = {}) {
618
+ const force = opts.force === true;
619
+ const running = this.inflight;
620
+ if (running && (running.force || !force)) return running.promise;
621
+ const promise = (async () => {
622
+ await running?.promise.catch(() => void 0);
623
+ return this.runDetect(force);
624
+ })().finally(() => {
625
+ if (this.inflight?.promise === promise) this.inflight = void 0;
626
+ });
627
+ this.inflight = {
628
+ promise,
629
+ force
630
+ };
631
+ return promise;
632
+ }
633
+ latest() {
634
+ return this.last;
635
+ }
636
+ async reprobe(http) {
637
+ const runtimes = await this.detect({ force: true });
638
+ await http.call("POST", PROBE_REPORT_PATH, { body: { runtimes } });
639
+ return runtimes;
640
+ }
641
+ async runDetect(force) {
642
+ const [claude, codex] = await Promise.all([this.detectClaude(force), this.detectCodex()]);
643
+ this.last = [claude, codex].filter((r) => r !== void 0);
644
+ return this.last;
645
+ }
646
+ async detectClaude(force) {
647
+ const path = firstExecutable([
648
+ ...pathCandidates(CLAUDE, this.pathEnv),
649
+ join(this.home, ".local", "bin", CLAUDE),
650
+ join(this.home, ".claude", "local", CLAUDE)
651
+ ]);
652
+ if (path === void 0) return;
653
+ const version = await this.version(path);
654
+ const cached = force ? void 0 : this.cachedLogin(path, version);
655
+ if (cached) return {
656
+ kind: CLAUDE,
657
+ path,
658
+ version,
659
+ logged_in: cached.logged_in,
660
+ checked_at: cached.checked_at
661
+ };
662
+ const loggedIn = judgeClaudePing(await runCommand(path, CLAUDE_PING_ARGS, this.opts.pingTimeoutMs ?? DEFAULT_PING_TIMEOUT_MS));
663
+ const checkedAt = new Date(this.now()).toISOString();
664
+ this.saveLogin({
665
+ path,
666
+ version,
667
+ logged_in: loggedIn,
668
+ checked_at: checkedAt
669
+ });
670
+ return {
671
+ kind: CLAUDE,
672
+ path,
673
+ version,
674
+ logged_in: loggedIn,
675
+ checked_at: checkedAt
676
+ };
677
+ }
678
+ async detectCodex() {
679
+ const path = firstExecutable(pathCandidates(CODEX, this.pathEnv));
680
+ if (path === void 0) return;
681
+ const [version, status] = await Promise.all([this.version(path), runCommand(path, CODEX_STATUS_ARGS, this.opts.statusTimeoutMs ?? DEFAULT_STATUS_TIMEOUT_MS)]);
682
+ return {
683
+ kind: CODEX,
684
+ path,
685
+ version,
686
+ logged_in: judgeCodexStatus(status),
687
+ checked_at: new Date(this.now()).toISOString()
688
+ };
689
+ }
690
+ async version(path) {
691
+ const res = await runCommand(path, VERSION_ARGS, this.opts.versionTimeoutMs ?? DEFAULT_VERSION_TIMEOUT_MS);
692
+ if (res.ended !== "exit" || res.code !== 0) return "";
693
+ return VERSION_RE.exec(res.stdout)?.[0] ?? "";
694
+ }
695
+ cachedLogin(path, version) {
696
+ const entry = this.readCache().claude;
697
+ if (!entry || entry.path !== path || entry.version !== version) return;
698
+ const ttl = entry.logged_in === LOGIN_UNKNOWN ? UNKNOWN_CACHE_TTL_MS : LOGIN_CACHE_TTL_MS;
699
+ const age = this.now() - Date.parse(entry.checked_at);
700
+ if (!(age >= 0 && age < ttl)) return;
701
+ return entry;
702
+ }
703
+ readCache() {
704
+ let data;
705
+ try {
706
+ data = JSON.parse(readFileSync(this.cachePath, "utf8"));
707
+ } catch {
708
+ return {};
709
+ }
710
+ const entry = data?.claude;
711
+ if (typeof entry?.path !== "string" || typeof entry.version !== "string" || typeof entry.logged_in !== "boolean" && entry.logged_in !== LOGIN_UNKNOWN || typeof entry.checked_at !== "string") return {};
712
+ return { claude: entry };
713
+ }
714
+ saveLogin(entry) {
715
+ try {
716
+ const root = this.opts.profile.root;
717
+ mkdirSync(root, {
718
+ recursive: true,
719
+ mode: DIR_MODE
720
+ });
721
+ chmodSync(root, DIR_MODE);
722
+ const data = { claude: entry };
723
+ const tmp = `${this.cachePath}.${randomUUID()}.tmp`;
724
+ writeFileSync(tmp, `${JSON.stringify(data, null, 2)}\n`, {
725
+ mode: FILE_MODE,
726
+ flag: "wx"
727
+ });
728
+ try {
729
+ renameSync(tmp, this.cachePath);
730
+ } catch (e) {
731
+ rmSync(tmp, { force: true });
732
+ throw e;
733
+ }
734
+ } catch (e) {
735
+ this.opts.log?.("warn", "write runtime login cache failed", {
736
+ path: this.cachePath,
737
+ error: e instanceof Error ? e.message : String(e)
738
+ });
739
+ }
740
+ }
741
+ };
742
+ function judgeClaudePing(res) {
743
+ if (res.ended !== "exit") return LOGIN_UNKNOWN;
744
+ const out = lastJSONObject(res.stdout);
745
+ if (out?.type === CLAUDE_RESULT_TYPE) {
746
+ if (out.is_error === false) return true;
747
+ return CLAUDE_LOGGED_OUT_RE.test(String(out.result ?? "")) ? false : LOGIN_UNKNOWN;
748
+ }
749
+ return CLAUDE_LOGGED_OUT_RE.test(`${res.stdout}\n${res.stderr}`) ? false : LOGIN_UNKNOWN;
750
+ }
751
+ function judgeCodexStatus(res) {
752
+ if (res.ended !== "exit") return LOGIN_UNKNOWN;
753
+ const text = `${res.stdout}\n${res.stderr}`;
754
+ if (CODEX_LOGGED_OUT_RE.test(text)) return false;
755
+ return res.code === 0 && CODEX_LOGGED_IN_RE.test(text) ? true : LOGIN_UNKNOWN;
756
+ }
757
+ function pathCandidates(name, pathEnv) {
758
+ return pathEnv.split(delimiter).filter((dir) => dir !== "" && isAbsolute(dir)).map((dir) => join(dir, name));
759
+ }
760
+ function firstExecutable(candidates) {
761
+ return candidates.find(isExecutableFile);
762
+ }
763
+ function isExecutableFile(path) {
764
+ try {
765
+ if (!statSync(path).isFile()) return false;
766
+ accessSync(path, constants.X_OK);
767
+ return true;
768
+ } catch {
769
+ return false;
770
+ }
771
+ }
772
+ function lastJSONObject(text) {
773
+ const lines = [text.trim(), ...text.split("\n").reverse()];
774
+ for (const line of lines) {
775
+ const s = line.trim();
776
+ if (!s.startsWith("{")) continue;
777
+ try {
778
+ const v = JSON.parse(s);
779
+ if (v !== null && typeof v === "object" && !Array.isArray(v)) return v;
780
+ } catch {}
781
+ }
782
+ }
783
+ function runCommand(cmd, args, timeoutMs) {
784
+ return new Promise((resolve) => {
785
+ let settled = false;
786
+ let timer;
787
+ const out = capped();
788
+ const errOut = capped();
789
+ const finish = (ended, code) => {
790
+ if (settled) return;
791
+ settled = true;
792
+ clearTimeout(timer);
793
+ resolve({
794
+ ended,
795
+ code,
796
+ stdout: out.text(),
797
+ stderr: errOut.text()
798
+ });
799
+ };
800
+ let child;
801
+ try {
802
+ child = spawn(cmd, args, {
803
+ cwd: tmpdir(),
804
+ stdio: [
805
+ "ignore",
806
+ "pipe",
807
+ "pipe"
808
+ ],
809
+ detached: !IS_WINDOWS
810
+ });
811
+ } catch {
812
+ finish("error", null);
813
+ return;
814
+ }
815
+ child.stdout?.on("data", (b) => out.push(b));
816
+ child.stderr?.on("data", (b) => errOut.push(b));
817
+ child.on("error", () => finish("error", null));
818
+ child.on("close", (code) => finish("exit", code));
819
+ timer = setTimeout(() => {
820
+ killTree(child);
821
+ finish("timeout", null);
822
+ }, timeoutMs);
823
+ });
824
+ }
825
+ function capped() {
826
+ const chunks = [];
827
+ let size = 0;
828
+ return {
829
+ push(b) {
830
+ const room = OUTPUT_LIMIT_BYTES - size;
831
+ if (room <= 0) return;
832
+ const kept = b.length > room ? b.subarray(0, room) : b;
833
+ chunks.push(kept);
834
+ size += kept.length;
835
+ },
836
+ text: () => Buffer.concat(chunks).toString("utf8")
837
+ };
838
+ }
839
+ function killTree(child) {
840
+ if (child.pid !== void 0) try {
841
+ process.kill(IS_WINDOWS ? child.pid : -child.pid, "SIGKILL");
842
+ } catch {}
843
+ child.stdout?.destroy();
844
+ child.stderr?.destroy();
845
+ }
846
+ const WS_PING_INTERVAL_MS = 25e3;
847
+ const WS_HANDSHAKE_TIMEOUT_MS = 15e3;
848
+ const WS_MAX_SILENT_PINGS = 2;
849
+ const WS_TYPE_WAKE = "wake";
850
+ const WS_TYPE_CANCEL = "cancel";
851
+ const WS_TYPE_CONFIG = "config";
852
+ const WS_TYPE_PROBE = "probe";
853
+ const WS_TYPE_DOCTOR = "doctor";
854
+ const WS_TYPE_UPDATE = "update";
855
+ const WS_TYPE_UNBOUND = "unbound";
856
+ const WS_TYPE_PING = "ping";
857
+ const WS_TYPE_PONG = "pong";
858
+ const WS_HEADER_INSTANCE = "X-Runner-Instance";
859
+ const WS_CLOSE_NORMAL = 1e3;
860
+ function runnerWsURL(portal, wsPath) {
861
+ const path = wsPath.startsWith("/") ? wsPath : `/${wsPath}`;
862
+ const u = new URL(normalizePortalURL(portal) + path);
863
+ u.protocol = u.protocol === "https:" ? "wss:" : "ws:";
864
+ return u.toString();
865
+ }
866
+ var RunnerWs = class {
867
+ socket;
868
+ failures = 0;
869
+ silentPings = 0;
870
+ stopped = false;
871
+ started = false;
872
+ opened = false;
873
+ reconnectTimer;
874
+ handshakeTimer;
875
+ pingTimer;
876
+ configReady = Promise.resolve();
877
+ inflight = /* @__PURE__ */ new Set();
878
+ factory;
879
+ pingIntervalMs;
880
+ constructor(opts) {
881
+ this.opts = opts;
882
+ this.factory = opts.factory ?? globalWebSocket;
883
+ this.pingIntervalMs = opts.pingIntervalMs ?? WS_PING_INTERVAL_MS;
884
+ }
885
+ start() {
886
+ if (this.started || this.stopped) return;
887
+ this.started = true;
888
+ this.connect();
889
+ }
890
+ stop() {
891
+ if (this.stopped) return;
892
+ this.stopped = true;
893
+ clearTimeout(this.reconnectTimer);
894
+ this.reconnectTimer = void 0;
895
+ this.closeSocket();
896
+ }
897
+ nextDelayMs() {
898
+ return Math.min(BACKOFF_BASE_MS * 2 ** this.failures, BACKOFF_MAX_MS);
899
+ }
900
+ async settled() {
901
+ while (this.inflight.size > 0) await Promise.allSettled([...this.inflight]);
902
+ }
903
+ connect() {
904
+ if (this.stopped) return;
905
+ let socket;
906
+ try {
907
+ socket = this.factory(this.opts.url, {
908
+ Authorization: `Bearer ${this.opts.token}`,
909
+ [WS_HEADER_INSTANCE]: this.opts.instanceId
910
+ });
911
+ } catch (e) {
912
+ this.opts.host.log("warn", "runner websocket connect failed", { error: errText$1(e) });
913
+ this.scheduleReconnect();
914
+ return;
915
+ }
916
+ this.socket = socket;
917
+ socket.onopen = () => this.onOpen(socket);
918
+ socket.onmessage = (ev) => this.onMessage(socket, ev.data);
919
+ socket.onerror = () => this.onLost(socket);
920
+ socket.onclose = () => this.onLost(socket);
921
+ this.handshakeTimer = setTimeout(() => {
922
+ if (socket !== this.socket) return;
923
+ this.opts.host.log("warn", "runner websocket handshake timeout, reconnecting", { timeout_ms: WS_HANDSHAKE_TIMEOUT_MS });
924
+ this.dropSocket();
925
+ }, WS_HANDSHAKE_TIMEOUT_MS);
926
+ this.handshakeTimer.unref?.();
927
+ }
928
+ onOpen(socket) {
929
+ if (socket !== this.socket) return;
930
+ clearTimeout(this.handshakeTimer);
931
+ this.handshakeTimer = void 0;
932
+ this.failures = 0;
933
+ this.silentPings = 0;
934
+ this.opts.host.log("info", "runner websocket connected");
935
+ this.opened = true;
936
+ this.opts.onConnectionChange?.(true);
937
+ clearInterval(this.pingTimer);
938
+ this.pingTimer = setInterval(() => this.ping(socket), this.pingIntervalMs);
939
+ this.pingTimer.unref?.();
940
+ }
941
+ ping(socket) {
942
+ if (socket !== this.socket) return;
943
+ if (this.silentPings >= WS_MAX_SILENT_PINGS) {
944
+ this.opts.host.log("warn", "runner websocket silent, reconnecting", { silent_pings: this.silentPings });
945
+ this.dropSocket();
946
+ return;
947
+ }
948
+ this.silentPings++;
949
+ try {
950
+ socket.send(JSON.stringify({ type: WS_TYPE_PING }));
951
+ } catch (e) {
952
+ this.opts.host.log("warn", "runner websocket ping failed", { error: errText$1(e) });
953
+ }
954
+ }
955
+ onLost(socket) {
956
+ if (socket !== this.socket) return;
957
+ this.dropSocket();
958
+ }
959
+ scheduleReconnect() {
960
+ if (this.stopped) return;
961
+ const delay = this.nextDelayMs();
962
+ this.failures++;
963
+ this.opts.host.log("debug", "runner websocket closed, reconnecting", { delay_ms: delay });
964
+ this.reconnectTimer = setTimeout(() => {
965
+ this.reconnectTimer = void 0;
966
+ this.connect();
967
+ }, delay);
968
+ this.reconnectTimer.unref?.();
969
+ }
970
+ dropSocket() {
971
+ const socket = this.socket;
972
+ this.closeSocket();
973
+ if (socket) this.scheduleReconnect();
974
+ }
975
+ closeSocket() {
976
+ clearInterval(this.pingTimer);
977
+ this.pingTimer = void 0;
978
+ clearTimeout(this.handshakeTimer);
979
+ this.handshakeTimer = void 0;
980
+ if (this.opened) {
981
+ this.opened = false;
982
+ this.opts.onConnectionChange?.(false);
983
+ }
984
+ const socket = this.socket;
985
+ this.socket = void 0;
986
+ if (!socket) return;
987
+ socket.onopen = null;
988
+ socket.onmessage = null;
989
+ socket.onerror = null;
990
+ socket.onclose = null;
991
+ try {
992
+ socket.close(WS_CLOSE_NORMAL);
993
+ } catch {}
994
+ }
995
+ onMessage(socket, data) {
996
+ if (socket !== this.socket) return;
997
+ this.silentPings = 0;
998
+ let msg;
999
+ try {
1000
+ msg = JSON.parse(String(data));
1001
+ } catch {
1002
+ this.opts.host.log("warn", "runner websocket message is not json");
1003
+ return;
1004
+ }
1005
+ if (msg === null || typeof msg !== "object") return;
1006
+ this.handle(msg);
1007
+ }
1008
+ handle(msg) {
1009
+ const { host } = this.opts;
1010
+ const type = String(msg.type);
1011
+ switch (type) {
1012
+ case WS_TYPE_WAKE:
1013
+ this.track(type, host.dispatch({ kind: "wake" }));
1014
+ break;
1015
+ case WS_TYPE_CANCEL:
1016
+ if (typeof msg.attempt_id !== "string" || msg.attempt_id === "") {
1017
+ host.log("warn", "runner websocket cancel without attempt_id");
1018
+ break;
1019
+ }
1020
+ this.track(type, host.dispatch({
1021
+ kind: "cancel",
1022
+ attempt_id: msg.attempt_id
1023
+ }));
1024
+ break;
1025
+ case WS_TYPE_CONFIG:
1026
+ this.onConfig(msg.config_version);
1027
+ break;
1028
+ case WS_TYPE_PROBE:
1029
+ this.track(type, host.probe());
1030
+ break;
1031
+ case WS_TYPE_DOCTOR:
1032
+ this.track(type, this.configReady.then(() => host.doctor()));
1033
+ break;
1034
+ case WS_TYPE_UPDATE:
1035
+ if (typeof msg.version !== "string" || msg.version === "") {
1036
+ host.log("warn", "runner websocket update without version");
1037
+ break;
1038
+ }
1039
+ this.track(type, host.update(msg.version));
1040
+ break;
1041
+ case WS_TYPE_UNBOUND:
1042
+ host.log("warn", "runner websocket received unbound, stop reconnecting");
1043
+ this.stop();
1044
+ this.track(type, host.selfUninstall());
1045
+ break;
1046
+ case WS_TYPE_PONG: break;
1047
+ default: host.log("debug", "unknown runner websocket message", { type });
1048
+ }
1049
+ }
1050
+ onConfig(version) {
1051
+ const { host } = this.opts;
1052
+ if (typeof version === "number" && version === host.configVersion()) return;
1053
+ this.configReady = host.refreshConfig().catch((e) => {
1054
+ host.log("warn", "refresh runner config failed", {
1055
+ error: errText$1(e),
1056
+ config_version: version
1057
+ });
1058
+ });
1059
+ this.track(WS_TYPE_CONFIG, this.configReady);
1060
+ }
1061
+ track(type, task) {
1062
+ const p = task.catch((e) => {
1063
+ this.opts.host.log("warn", "runner websocket action failed", {
1064
+ type,
1065
+ error: errText$1(e)
1066
+ });
1067
+ }).finally(() => {
1068
+ this.inflight.delete(p);
1069
+ });
1070
+ this.inflight.add(p);
1071
+ }
1072
+ };
1073
+ function globalWebSocket(url, headers) {
1074
+ const Ctor = globalThis.WebSocket;
1075
+ if (!Ctor) throw new Error("websocket is not available in this node version");
1076
+ return new Ctor(url, { headers });
1077
+ }
1078
+ function errText$1(e) {
1079
+ return e instanceof Error ? e.message : String(e);
1080
+ }
1081
+ const RUNNER_CONFIG_PATH = "/runner/config";
1082
+ const EXIT_OK = 0;
1083
+ const EXIT_FAILED = 1;
1084
+ const NOTIFY_TITLE = "Forge Runner";
1085
+ const DEFAULT_MACHINE_SETTINGS = {
1086
+ work_hours_minus_one: false,
1087
+ prevent_sleep: "plugged",
1088
+ work_dir: "~/forge-runner/workspaces",
1089
+ disk_limit_gb: 20,
1090
+ cleanup_days: 7,
1091
+ offline_remind_hours: 2,
1092
+ auto_update: true
1093
+ };
1094
+ const LOCAL_RESTART_PATH = "/host/restart";
1095
+ const FORCE_EXIT_GRACE_MS = 1e4;
1096
+ const LOCAL_HOST = "127.0.0.1";
1097
+ const LOCAL_HOST_NAMES = [LOCAL_HOST, "localhost"];
1098
+ const LOCAL_BODY_LIMIT_BYTES = 16 * 1024 * 1024;
1099
+ const JSON_TYPE = "application/json";
1100
+ const HTTP_OK = 200;
1101
+ const HTTP_BAD_REQUEST = 400;
1102
+ const HTTP_FORBIDDEN = 403;
1103
+ const HTTP_NOT_FOUND = 404;
1104
+ const HTTP_TOO_LARGE = 413;
1105
+ const HTTP_INTERNAL_ERROR = 500;
1106
+ const LOCAL_OK = "ok";
1107
+ const LOCAL_ERR_FORBIDDEN = "forbidden";
1108
+ const LOCAL_ERR_NOT_FOUND = "not_found";
1109
+ const LOCAL_ERR_BAD_JSON = "bad_json";
1110
+ const LOCAL_ERR_TOO_LARGE = "body_too_large";
1111
+ const LOCAL_ERR_INTERNAL = "internal_error";
1112
+ const DISK_REFRESH_MS = 10 * 6e4;
1113
+ const DU_TIMEOUT_MS = 6e4;
1114
+ const KB_PER_GB = 1024 * 1024;
1115
+ const NOTIFY_TIMEOUT_MS = 1e4;
1116
+ var RealHost = class {
1117
+ creds;
1118
+ profile;
1119
+ home;
1120
+ client;
1121
+ detector;
1122
+ sink;
1123
+ err;
1124
+ notify;
1125
+ now;
1126
+ ws;
1127
+ sweeper;
1128
+ localSettings;
1129
+ agents = [];
1130
+ version;
1131
+ configLoad;
1132
+ actions = /* @__PURE__ */ new Map();
1133
+ handlers = /* @__PURE__ */ new Map();
1134
+ routes = /* @__PURE__ */ new Map();
1135
+ server;
1136
+ port = 0;
1137
+ shutdownRequested = false;
1138
+ restartRequested = false;
1139
+ latched = /* @__PURE__ */ new Set();
1140
+ code = EXIT_OK;
1141
+ tokenInvalid = false;
1142
+ diskGb = 0;
1143
+ diskCheckedAt;
1144
+ diskLoad;
1145
+ constructor(opts) {
1146
+ this.opts = opts;
1147
+ this.creds = opts.creds;
1148
+ this.profile = opts.profile;
1149
+ this.home = opts.home ?? homedir();
1150
+ const instanceId = opts.instanceId ?? opts.profile.instanceId();
1151
+ this.client = new PlatformHttp({
1152
+ portal: opts.creds.portal,
1153
+ token: opts.creds.runnerToken,
1154
+ instanceId
1155
+ });
1156
+ this.sweeper = new ClaimSweeper({ nudge: () => void this.dispatch({ kind: "wake" }) });
1157
+ this.ws = new RunnerWs({
1158
+ host: this,
1159
+ url: runnerWsURL(opts.creds.portal, opts.creds.wsPath),
1160
+ token: opts.creds.runnerToken,
1161
+ instanceId,
1162
+ factory: opts.wsFactory,
1163
+ onConnectionChange: (connected) => this.sweeper.setConnected(connected)
1164
+ });
1165
+ this.sink = opts.sink ?? ((line) => void process.stdout.write(`${line}\n`));
1166
+ this.err = opts.err ?? ((line) => console.error(line));
1167
+ this.notify = opts.notify ?? desktopNotify;
1168
+ this.now = opts.now ?? Date.now;
1169
+ this.detector = opts.detector ?? new RuntimeDetector({
1170
+ profile: opts.profile,
1171
+ log: (l, m, f) => this.log(l, m, f)
1172
+ });
1173
+ this.localSettings = this.expand(DEFAULT_MACHINE_SETTINGS);
1174
+ this.localRoute("POST", LOCAL_RESTART_PATH, async () => {
1175
+ this.requestRestart();
1176
+ return {
1177
+ status: HTTP_OK,
1178
+ body: { code: LOCAL_OK }
1179
+ };
1180
+ });
1181
+ }
1182
+ async start() {
1183
+ await this.listen();
1184
+ this.loadCache();
1185
+ try {
1186
+ await this.loadConfig(false);
1187
+ } catch (e) {
1188
+ this.log("warn", "load runner config failed, using local cache", { error: errText(e) });
1189
+ }
1190
+ try {
1191
+ await this.detector.detect();
1192
+ } catch (e) {
1193
+ this.log("warn", "detect runtimes failed", { error: errText(e) });
1194
+ }
1195
+ this.sweeper.start();
1196
+ this.ws.start();
1197
+ }
1198
+ async stop() {
1199
+ this.sweeper.stop();
1200
+ this.ws.stop();
1201
+ const server = this.server;
1202
+ this.server = void 0;
1203
+ if (!server) return;
1204
+ server.closeAllConnections();
1205
+ await new Promise((resolve) => server.close(() => resolve()));
1206
+ }
1207
+ credentials() {
1208
+ return {
1209
+ portalHost: this.creds.portalHost,
1210
+ runnerId: this.creds.runnerId,
1211
+ runnerToken: this.creds.runnerToken
1212
+ };
1213
+ }
1214
+ http() {
1215
+ return this.client;
1216
+ }
1217
+ api() {
1218
+ return this.client;
1219
+ }
1220
+ agentConfig(agentId) {
1221
+ return this.agents.find((a) => a.agent_id === agentId);
1222
+ }
1223
+ machineSettings() {
1224
+ return this.localSettings;
1225
+ }
1226
+ runtimes() {
1227
+ return this.detector.latest();
1228
+ }
1229
+ onEvent(kind, handler) {
1230
+ let set = this.handlers.get(kind);
1231
+ if (!set) {
1232
+ set = /* @__PURE__ */ new Set();
1233
+ this.handlers.set(kind, set);
1234
+ }
1235
+ const h = handler;
1236
+ set.add(h);
1237
+ if (this.latched.has(kind)) queueMicrotask(() => void this.invoke(h, { kind }));
1238
+ return () => {
1239
+ set.delete(h);
1240
+ };
1241
+ }
1242
+ async dispatch(event) {
1243
+ const set = this.handlers.get(event.kind);
1244
+ if (!set) return;
1245
+ await Promise.all([...set].map((h) => this.invoke(h, event)));
1246
+ }
1247
+ localRoute(method, path, handler) {
1248
+ this.routes.set(routeKey(method, path), handler);
1249
+ }
1250
+ localBaseUrl() {
1251
+ return `http://${LOCAL_HOST}:${this.port}`;
1252
+ }
1253
+ log(level, msg, fields) {
1254
+ let line;
1255
+ try {
1256
+ line = JSON.stringify({
1257
+ time: new Date(this.now()).toISOString(),
1258
+ level,
1259
+ msg,
1260
+ ...fields
1261
+ });
1262
+ } catch {
1263
+ line = JSON.stringify({
1264
+ time: new Date(this.now()).toISOString(),
1265
+ level,
1266
+ msg
1267
+ });
1268
+ }
1269
+ this.sink(line);
1270
+ }
1271
+ configVersion() {
1272
+ return this.version;
1273
+ }
1274
+ refreshConfig() {
1275
+ this.configLoad ??= this.loadConfig(true).finally(() => {
1276
+ this.configLoad = void 0;
1277
+ });
1278
+ return this.configLoad;
1279
+ }
1280
+ probe() {
1281
+ return this.once(ACTION_PROBE, async () => {
1282
+ await this.detector.reprobe(this.client);
1283
+ });
1284
+ }
1285
+ doctor() {
1286
+ return this.once(ACTION_DOCTOR, async () => {
1287
+ const targets = this.profile.readDoctorTargets(this.creds.portalHost) ?? normalizeDoctorTargets(void 0);
1288
+ const report = await runDoctor({
1289
+ detector: this.detector,
1290
+ targets,
1291
+ ...this.opts.doctorOptions
1292
+ });
1293
+ await reportDoctor(this.client, report);
1294
+ });
1295
+ }
1296
+ async update(version) {
1297
+ if (this.restartRequested) {
1298
+ this.log("debug", "update skipped, new version installed and waiting for restart", { version });
1299
+ return;
1300
+ }
1301
+ const res = await performUpdate({
1302
+ version,
1303
+ profile: this.profile,
1304
+ run: this.opts.updateRun,
1305
+ exit: () => this.requestRestart(),
1306
+ now: this.now
1307
+ });
1308
+ const level = res.ok ? "info" : res.skipped ? "debug" : "warn";
1309
+ this.log(level, "runner update finished", {
1310
+ version: res.version,
1311
+ ok: res.ok,
1312
+ skipped: res.skipped
1313
+ });
1314
+ }
1315
+ requestRestart() {
1316
+ if (this.restartRequested) return;
1317
+ this.restartRequested = true;
1318
+ this.latched.add("restart");
1319
+ this.dispatch({ kind: "restart" });
1320
+ }
1321
+ onTokenInvalid(err) {
1322
+ if (this.tokenInvalid) return;
1323
+ this.tokenInvalid = true;
1324
+ this.sweeper.stop();
1325
+ this.ws.stop();
1326
+ const revoked = this.removeRevokedCredentials();
1327
+ this.log("error", "runner token rejected, stop retrying", { error: err.message });
1328
+ this.err(err.hint);
1329
+ this.notify(NOTIFY_TITLE, err.hint).catch((e) => {
1330
+ this.log("warn", "desktop notification failed", { error: errText(e) });
1331
+ });
1332
+ if (revoked) this.selfUninstall().catch((e) => {
1333
+ this.log("warn", "self uninstall after token revoked failed", { error: errText(e) });
1334
+ });
1335
+ }
1336
+ removeRevokedCredentials() {
1337
+ try {
1338
+ if (this.profile.removeCredentialsIfToken(this.creds.portalHost, this.creds.runnerToken)) {
1339
+ this.log("info", "removed revoked runner credentials", { portal_host: this.creds.portalHost });
1340
+ return true;
1341
+ }
1342
+ } catch (e) {
1343
+ this.log("warn", "remove revoked credentials failed", { error: errText(e) });
1344
+ }
1345
+ return false;
1346
+ }
1347
+ onSuperseded(err) {
1348
+ this.log("error", "runner superseded by another instance, exiting", { error: err.message });
1349
+ this.err(err.hint);
1350
+ this.requestShutdown(EXIT_FAILED);
1351
+ }
1352
+ requestShutdown(exitCode) {
1353
+ if (this.shutdownRequested) return;
1354
+ this.shutdownRequested = true;
1355
+ this.latched.add("shutdown");
1356
+ this.code = exitCode;
1357
+ this.dispatch({ kind: "shutdown" });
1358
+ }
1359
+ get exitCode() {
1360
+ return this.code;
1361
+ }
1362
+ async selfUninstall() {
1363
+ this.log("warn", "runner unbound, removing autostart service");
1364
+ this.removeRevokedCredentials();
1365
+ await this.stop();
1366
+ this.opts.lock?.release();
1367
+ await this.opts.service?.uninstall();
1368
+ this.requestShutdown(EXIT_OK);
1369
+ }
1370
+ diskUsedGb() {
1371
+ const at = this.diskCheckedAt;
1372
+ if (at === void 0 || this.now() - at >= DISK_REFRESH_MS) this.refreshDiskUsage();
1373
+ return this.diskGb;
1374
+ }
1375
+ refreshDiskUsage() {
1376
+ this.diskLoad ??= (async () => {
1377
+ const kb = await duKb(this.localSettings.work_dir);
1378
+ if (kb !== void 0) this.diskGb = Math.round(kb / KB_PER_GB * 1e3) / 1e3;
1379
+ this.diskCheckedAt = this.now();
1380
+ })().finally(() => {
1381
+ this.diskLoad = void 0;
1382
+ });
1383
+ return this.diskLoad;
1384
+ }
1385
+ async invoke(h, event) {
1386
+ try {
1387
+ await h(event);
1388
+ } catch (e) {
1389
+ this.log("error", "runner event handler failed", {
1390
+ kind: event.kind,
1391
+ error: errText(e)
1392
+ });
1393
+ }
1394
+ }
1395
+ once(key, fn) {
1396
+ let p = this.actions.get(key);
1397
+ if (!p) {
1398
+ p = fn().finally(() => {
1399
+ this.actions.delete(key);
1400
+ });
1401
+ this.actions.set(key, p);
1402
+ }
1403
+ return p;
1404
+ }
1405
+ loadCache() {
1406
+ const portalHost = this.creds.portalHost;
1407
+ try {
1408
+ this.setSettings(this.profile.readSettings(portalHost) ?? DEFAULT_MACHINE_SETTINGS);
1409
+ this.agents = this.profile.readAgents(portalHost);
1410
+ } catch (e) {
1411
+ this.log("warn", "read runner config cache failed", { error: errText(e) });
1412
+ }
1413
+ }
1414
+ async loadConfig(notify) {
1415
+ const cfg = parseConfig(await this.client.call("GET", RUNNER_CONFIG_PATH));
1416
+ const portalHost = this.creds.portalHost;
1417
+ this.profile.writeSettings(portalHost, cfg.settings);
1418
+ this.profile.writeAgents(portalHost, cfg.agents);
1419
+ this.profile.writeDoctorTargets(portalHost, normalizeDoctorTargets(cfg.doctorTargets));
1420
+ this.setSettings(cfg.settings);
1421
+ this.agents = cfg.agents;
1422
+ this.version = cfg.version;
1423
+ if (notify) await this.dispatch({ kind: "config" });
1424
+ }
1425
+ setSettings(settings) {
1426
+ this.localSettings = this.expand(settings);
1427
+ }
1428
+ expand(settings) {
1429
+ return {
1430
+ ...settings,
1431
+ work_dir: expandHome(settings.work_dir, this.home)
1432
+ };
1433
+ }
1434
+ async listen() {
1435
+ const preferred = this.opts.preferredPort ?? healthPort();
1436
+ let server;
1437
+ try {
1438
+ server = await this.listenOn(preferred);
1439
+ } catch (e) {
1440
+ if (errCode(e) !== "EADDRINUSE" || preferred === 0) throw e;
1441
+ this.log("warn", "preferred local port in use, using a random port", { port: preferred });
1442
+ server = await this.listenOn(0);
1443
+ }
1444
+ this.server = server;
1445
+ this.port = server.address().port;
1446
+ this.profile.writePort(this.port);
1447
+ }
1448
+ listenOn(port) {
1449
+ const server = createServer((req, res) => this.serve(req, res));
1450
+ return new Promise((resolve, reject) => {
1451
+ server.once("error", reject);
1452
+ server.listen(port, LOCAL_HOST, () => {
1453
+ server.off("error", reject);
1454
+ resolve(server);
1455
+ });
1456
+ });
1457
+ }
1458
+ serve(req, res) {
1459
+ this.handle(req, res).catch((e) => {
1460
+ this.log("error", "local request failed", {
1461
+ path: req.url,
1462
+ error: errText(e)
1463
+ });
1464
+ if (!res.headersSent) reply(res, HTTP_INTERNAL_ERROR, {
1465
+ code: LOCAL_ERR_INTERNAL,
1466
+ message: "internal error"
1467
+ });
1468
+ });
1469
+ }
1470
+ async handle(req, res) {
1471
+ if (!this.allowedHost(req.headers.host)) {
1472
+ reply(res, HTTP_FORBIDDEN, {
1473
+ code: LOCAL_ERR_FORBIDDEN,
1474
+ message: "host not allowed"
1475
+ });
1476
+ return;
1477
+ }
1478
+ if (req.headers.origin !== void 0) {
1479
+ reply(res, HTTP_FORBIDDEN, {
1480
+ code: LOCAL_ERR_FORBIDDEN,
1481
+ message: "browser origin not allowed"
1482
+ });
1483
+ return;
1484
+ }
1485
+ const method = req.method ?? "";
1486
+ const url = new URL(req.url ?? "/", this.localBaseUrl());
1487
+ const path = url.pathname;
1488
+ const handler = this.routes.get(routeKey(method, path));
1489
+ if (!handler && isSessionPath(path) && !this.hasRoutePath(path)) {
1490
+ await this.serveSessionForward(req, res, method, url);
1491
+ return;
1492
+ }
1493
+ if (!handler) {
1494
+ reply(res, HTTP_NOT_FOUND, {
1495
+ code: LOCAL_ERR_NOT_FOUND,
1496
+ message: "no such route"
1497
+ });
1498
+ return;
1499
+ }
1500
+ const raw = await readBody(req, LOCAL_BODY_LIMIT_BYTES);
1501
+ if (raw === void 0) {
1502
+ reply(res, HTTP_TOO_LARGE, {
1503
+ code: LOCAL_ERR_TOO_LARGE,
1504
+ message: "request body too large"
1505
+ });
1506
+ return;
1507
+ }
1508
+ let body;
1509
+ try {
1510
+ body = raw === "" ? void 0 : JSON.parse(raw);
1511
+ } catch {
1512
+ reply(res, HTTP_BAD_REQUEST, {
1513
+ code: LOCAL_ERR_BAD_JSON,
1514
+ message: "request body is not json"
1515
+ });
1516
+ return;
1517
+ }
1518
+ const out = await handler({
1519
+ method,
1520
+ path,
1521
+ body,
1522
+ headers: flatHeaders(req)
1523
+ });
1524
+ reply(res, out.status, out.body);
1525
+ }
1526
+ hasRoutePath(path) {
1527
+ return [...this.routes.keys()].some((key) => key.endsWith(` ${path}`));
1528
+ }
1529
+ async serveSessionForward(req, res, method, url) {
1530
+ const headers = flatHeaders(req);
1531
+ if (sessionTokenOf(headers) === void 0) {
1532
+ const out = missingTokenReply();
1533
+ res.writeHead(out.status, { "content-type": JSON_TYPE }).end(out.body);
1534
+ return;
1535
+ }
1536
+ const body = await readBodyBytes(req, LOCAL_BODY_LIMIT_BYTES);
1537
+ if (body === void 0) {
1538
+ reply(res, HTTP_TOO_LARGE, {
1539
+ code: LOCAL_ERR_TOO_LARGE,
1540
+ message: "request body too large"
1541
+ });
1542
+ return;
1543
+ }
1544
+ const out = await forwardSession(this.client.base, {
1545
+ method,
1546
+ pathname: url.pathname,
1547
+ search: url.search,
1548
+ headers,
1549
+ body
1550
+ }, this.opts.sessionForwardTimeoutMs);
1551
+ res.writeHead(out.status, { "content-type": out.contentType ?? JSON_TYPE }).end(out.body);
1552
+ }
1553
+ allowedHost(host) {
1554
+ return LOCAL_HOST_NAMES.some((name) => host === `${name}:${this.port}`);
1555
+ }
1556
+ };
1557
+ async function startRealDaemon(opts) {
1558
+ const creds = pickCredentials(opts.profile.listCredentials(), opts.defaultPortal);
1559
+ if (typeof creds === "string") {
1560
+ opts.err(creds);
1561
+ return EXIT_FAILED;
1562
+ }
1563
+ const forceExit = opts.forceExit ?? ((code) => process.exit(code));
1564
+ const host = new RealHost({
1565
+ creds,
1566
+ profile: opts.profile,
1567
+ lock: opts.lock,
1568
+ service: opts.service,
1569
+ err: opts.err,
1570
+ ...opts.hostOptions
1571
+ });
1572
+ const heartbeat = new Heartbeat({
1573
+ host,
1574
+ profile: opts.profile
1575
+ });
1576
+ let signals = 0;
1577
+ const offSignal = (opts.onSignal ?? onStopSignals)(() => {
1578
+ signals++;
1579
+ if (signals === 1) {
1580
+ host.requestShutdown(EXIT_OK);
1581
+ return;
1582
+ }
1583
+ forceExit(EXIT_FAILED);
1584
+ });
1585
+ try {
1586
+ await opts.run(host, {
1587
+ cliVersion: opts.cliVersion,
1588
+ diskUsedGb: () => host.diskUsedGb(),
1589
+ heartbeat
1590
+ });
1591
+ } finally {
1592
+ offSignal();
1593
+ }
1594
+ const code = host.exitCode;
1595
+ setTimeout(() => forceExit(code), FORCE_EXIT_GRACE_MS).unref();
1596
+ return code;
1597
+ }
1598
+ function pickCredentials(registered, defaultPortal) {
1599
+ if (registered.length === 0) return "这台电脑还没注册(先执行 runner setup 或 runner bind)";
1600
+ if (registered.length === 1) return registered[0];
1601
+ let wanted = "";
1602
+ try {
1603
+ wanted = portalHostOf(defaultPortal());
1604
+ } catch {}
1605
+ return registered.find((c) => c.portalHost === wanted) ?? `这台电脑注册在多个门户(${registered.map((c) => c.portalHost).join("、")}),都不是 CLI 配置的门户,无法确定连哪个`;
1606
+ }
1607
+ function onStopSignals(handler) {
1608
+ process.on("SIGTERM", handler);
1609
+ process.on("SIGINT", handler);
1610
+ return () => {
1611
+ process.off("SIGTERM", handler);
1612
+ process.off("SIGINT", handler);
1613
+ };
1614
+ }
1615
+ function desktopNotify(title, body, platform = process.platform) {
1616
+ let cmd;
1617
+ let args;
1618
+ if (platform === "darwin") {
1619
+ cmd = "osascript";
1620
+ args = [
1621
+ "-e",
1622
+ "on run argv",
1623
+ "-e",
1624
+ "display notification (item 2 of argv) with title (item 1 of argv)",
1625
+ "-e",
1626
+ "end run",
1627
+ title,
1628
+ body
1629
+ ];
1630
+ } else if (platform === "linux") {
1631
+ cmd = "notify-send";
1632
+ args = [title, body];
1633
+ } else return Promise.resolve();
1634
+ return new Promise((resolve, reject) => {
1635
+ execFile(cmd, args, { timeout: NOTIFY_TIMEOUT_MS }, (err) => err ? reject(err) : resolve());
1636
+ });
1637
+ }
1638
+ function expandHome(path, home) {
1639
+ if (path === "~") return home;
1640
+ if (path.startsWith("~/")) return join(home, path.slice(2));
1641
+ return path;
1642
+ }
1643
+ function parseConfig(data) {
1644
+ const d = data ?? {};
1645
+ const settings = d.settings;
1646
+ const agents = d.agents ?? [];
1647
+ if (typeof d.config_version !== "number" || settings === null || typeof settings !== "object" || Array.isArray(settings) || !Array.isArray(agents)) throw new Error("invalid runner config response");
1648
+ return {
1649
+ version: d.config_version,
1650
+ settings,
1651
+ agents,
1652
+ doctorTargets: d.doctor_targets
1653
+ };
1654
+ }
1655
+ function readBodyBytes(req, limit) {
1656
+ return new Promise((resolve, reject) => {
1657
+ const chunks = [];
1658
+ let size = 0;
1659
+ let over = false;
1660
+ req.on("data", (c) => {
1661
+ size += c.length;
1662
+ if (size > limit) {
1663
+ over = true;
1664
+ chunks.length = 0;
1665
+ return;
1666
+ }
1667
+ if (!over) chunks.push(c);
1668
+ });
1669
+ req.on("end", () => resolve(over ? void 0 : Buffer.concat(chunks)));
1670
+ req.on("error", reject);
1671
+ });
1672
+ }
1673
+ async function readBody(req, limit) {
1674
+ return (await readBodyBytes(req, limit))?.toString("utf8");
1675
+ }
1676
+ function flatHeaders(req) {
1677
+ const out = {};
1678
+ for (const [k, v] of Object.entries(req.headers)) if (v !== void 0) out[k] = Array.isArray(v) ? v.join(", ") : v;
1679
+ return out;
1680
+ }
1681
+ function reply(res, status, body) {
1682
+ res.writeHead(status, { "content-type": JSON_TYPE }).end(JSON.stringify(body ?? {}));
1683
+ }
1684
+ function routeKey(method, path) {
1685
+ return `${method} ${path}`;
1686
+ }
1687
+ function duKb(dir) {
1688
+ return new Promise((resolve) => {
1689
+ execFile("du", ["-sk", dir], { timeout: DU_TIMEOUT_MS }, (_err, stdout) => {
1690
+ const m = /^(\d+)/.exec(String(stdout ?? "").trim());
1691
+ resolve(m ? Number(m[1]) : void 0);
1692
+ });
1693
+ });
1694
+ }
1695
+ function errText(e) {
1696
+ return e instanceof Error ? e.message : String(e);
1697
+ }
1698
+ function errCode(e) {
1699
+ return e?.code;
1700
+ }
1701
+ const LAUNCHD_LABEL = "com.shoplazza.forge-runner";
1702
+ const SYSTEMD_UNIT = "forge-runner.service";
1703
+ const RUNNER_ARGS = ["runner", "start"];
1704
+ const OUT_LOG = "runner.out.log";
1705
+ const ERR_LOG = "runner.err.log";
1706
+ const EXEC_TIMEOUT_MS = 3e4;
1707
+ const STOP_TIMEOUT_S = 40;
1708
+ const BOOTSTRAP_RETRIES = 3;
1709
+ const BOOTSTRAP_RETRY_DELAY_MS = 500;
1710
+ const IO_ERROR_RE = /Input\/output error/i;
1711
+ const PATH_DIRS = [
1712
+ "/opt/homebrew/bin",
1713
+ "/usr/local/bin",
1714
+ "/usr/bin",
1715
+ "/bin",
1716
+ "/usr/sbin",
1717
+ "/sbin"
1718
+ ];
1719
+ var ServiceCommandError = class extends Error {
1720
+ hint;
1721
+ constructor(command, stderr) {
1722
+ super(`service command failed: ${command}: ${stderr.trim()}`);
1723
+ this.command = command;
1724
+ this.stderr = stderr;
1725
+ this.name = "ServiceCommandError";
1726
+ this.hint = `开机自启命令执行失败:${command}\n${stderr.trim()}`;
1727
+ }
1728
+ };
1729
+ var UnsupportedPlatformError = class extends Error {
1730
+ hint = "开机自启目前只支持 macOS 和 Linux";
1731
+ constructor(platform) {
1732
+ super(`unsupported platform for service: ${platform}`);
1733
+ this.name = "UnsupportedPlatformError";
1734
+ }
1735
+ };
1736
+ var RunnerService = class {
1737
+ unitPath;
1738
+ binPath;
1739
+ home;
1740
+ platform;
1741
+ uid;
1742
+ exec;
1743
+ sleep;
1744
+ logsDir;
1745
+ constructor(opts = {}) {
1746
+ this.home = opts.home ?? homedir();
1747
+ this.platform = opts.platform ?? process.platform;
1748
+ this.uid = opts.uid ?? process.getuid?.() ?? 0;
1749
+ this.exec = opts.exec ?? defaultExec;
1750
+ this.sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
1751
+ this.binPath = join(this.home, ROOT_DIR, BIN_DIR, RUNNER_BIN_NAME);
1752
+ this.logsDir = join(this.home, ROOT_DIR, "logs");
1753
+ this.unitPath = this.platform === "darwin" ? join(this.home, "Library", "LaunchAgents", `${LAUNCHD_LABEL}.plist`) : this.platform === "linux" ? join(this.home, ".config", "systemd", "user", SYSTEMD_UNIT) : "";
1754
+ }
1755
+ isInstalled() {
1756
+ return this.unitPath !== "" && existsSync(this.unitPath);
1757
+ }
1758
+ async install() {
1759
+ this.requireSupported();
1760
+ mkdirSync(this.logsDir, {
1761
+ recursive: true,
1762
+ mode: DIR_MODE
1763
+ });
1764
+ mkdirSync(dirname(this.unitPath), { recursive: true });
1765
+ writeFileSync(this.unitPath, this.render());
1766
+ if (this.platform === "linux") {
1767
+ await this.must("systemctl", ["--user", "daemon-reload"]);
1768
+ await this.must("systemctl", [
1769
+ "--user",
1770
+ "enable",
1771
+ SYSTEMD_UNIT
1772
+ ]);
1773
+ }
1774
+ }
1775
+ async start() {
1776
+ this.requireSupported();
1777
+ if (this.platform === "darwin") {
1778
+ await this.exec("launchctl", ["bootout", this.launchdTarget()]);
1779
+ await this.bootstrapWithRetry();
1780
+ return;
1781
+ }
1782
+ await this.must("systemctl", [
1783
+ "--user",
1784
+ "restart",
1785
+ SYSTEMD_UNIT
1786
+ ]);
1787
+ }
1788
+ async stop() {
1789
+ this.requireSupported();
1790
+ if (this.platform === "darwin") {
1791
+ await this.exec("launchctl", ["bootout", this.launchdTarget()]);
1792
+ return;
1793
+ }
1794
+ await this.exec("systemctl", [
1795
+ "--user",
1796
+ "stop",
1797
+ SYSTEMD_UNIT
1798
+ ]);
1799
+ }
1800
+ async uninstall() {
1801
+ this.requireSupported();
1802
+ if (this.platform === "darwin") {
1803
+ rmSync(this.unitPath, { force: true });
1804
+ await this.exec("launchctl", ["bootout", this.launchdTarget()]);
1805
+ return;
1806
+ }
1807
+ await this.exec("systemctl", [
1808
+ "--user",
1809
+ "disable",
1810
+ SYSTEMD_UNIT
1811
+ ]);
1812
+ rmSync(this.unitPath, { force: true });
1813
+ await this.exec("systemctl", ["--user", "daemon-reload"]);
1814
+ await this.exec("systemctl", [
1815
+ "--user",
1816
+ "stop",
1817
+ SYSTEMD_UNIT
1818
+ ]);
1819
+ }
1820
+ render() {
1821
+ const opts = {
1822
+ binPath: this.binPath,
1823
+ pathEnv: [
1824
+ join(this.home, ROOT_DIR, NODE_DIR, "bin"),
1825
+ join(this.home, ".local", "bin"),
1826
+ ...PATH_DIRS
1827
+ ].join(":"),
1828
+ outLog: join(this.logsDir, OUT_LOG),
1829
+ errLog: join(this.logsDir, ERR_LOG)
1830
+ };
1831
+ return this.platform === "darwin" ? renderLaunchdPlist(opts) : renderSystemdUnit(opts);
1832
+ }
1833
+ launchdDomain() {
1834
+ return `gui/${this.uid}`;
1835
+ }
1836
+ launchdTarget() {
1837
+ return `${this.launchdDomain()}/${LAUNCHD_LABEL}`;
1838
+ }
1839
+ requireSupported() {
1840
+ if (this.unitPath === "") throw new UnsupportedPlatformError(this.platform);
1841
+ }
1842
+ async bootstrapWithRetry() {
1843
+ const args = [
1844
+ "bootstrap",
1845
+ this.launchdDomain(),
1846
+ this.unitPath
1847
+ ];
1848
+ for (let attempt = 0;; attempt++) {
1849
+ const res = await this.exec("launchctl", args);
1850
+ if (res.code === 0) return;
1851
+ if (attempt >= BOOTSTRAP_RETRIES || !IO_ERROR_RE.test(res.stderr)) throw new ServiceCommandError(["launchctl", ...args].join(" "), res.stderr);
1852
+ await this.sleep(BOOTSTRAP_RETRY_DELAY_MS);
1853
+ }
1854
+ }
1855
+ async must(cmd, args) {
1856
+ const res = await this.exec(cmd, args);
1857
+ if (res.code !== 0) throw new ServiceCommandError([cmd, ...args].join(" "), res.stderr);
1858
+ }
1859
+ };
1860
+ function renderLaunchdPlist(c) {
1861
+ return `<?xml version="1.0" encoding="UTF-8"?>
1862
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
1863
+ <plist version="1.0">
1864
+ <dict>
1865
+ <key>Label</key>
1866
+ <string>${LAUNCHD_LABEL}</string>
1867
+ <key>ProgramArguments</key>
1868
+ <array>
1869
+ ${[c.binPath, ...RUNNER_ARGS].map((a) => ` <string>${xmlEscape(a)}</string>`).join("\n")}
1870
+ </array>
1871
+ <key>RunAtLoad</key>
1872
+ <true/>
1873
+ <key>KeepAlive</key>
1874
+ <true/>
1875
+ <key>ExitTimeOut</key>
1876
+ <integer>${STOP_TIMEOUT_S}</integer>
1877
+ <key>EnvironmentVariables</key>
1878
+ <dict>
1879
+ <key>PATH</key>
1880
+ <string>${xmlEscape(c.pathEnv)}</string>
1881
+ </dict>
1882
+ <key>StandardOutPath</key>
1883
+ <string>${xmlEscape(c.outLog)}</string>
1884
+ <key>StandardErrorPath</key>
1885
+ <string>${xmlEscape(c.errLog)}</string>
1886
+ </dict>
1887
+ </plist>
1888
+ `;
1889
+ }
1890
+ function renderSystemdUnit(c) {
1891
+ return `[Unit]
1892
+ Description=Forge Runner
1893
+ After=network-online.target
1894
+ Wants=network-online.target
1895
+
1896
+ [Service]
1897
+ ExecStart=${unitQuote(c.binPath)} ${RUNNER_ARGS.join(" ")}
1898
+ Restart=always
1899
+ RestartSec=5
1900
+ TimeoutStopSec=${STOP_TIMEOUT_S}
1901
+ Environment=${unitQuote(`PATH=${c.pathEnv}`)}
1902
+ StandardOutput=append:${specifierEscape(c.outLog)}
1903
+ StandardError=append:${specifierEscape(c.errLog)}
1904
+
1905
+ [Install]
1906
+ WantedBy=default.target
1907
+ `;
1908
+ }
1909
+ function specifierEscape(s) {
1910
+ return s.replace(/%/g, "%%");
1911
+ }
1912
+ function unitQuote(s) {
1913
+ return `"${specifierEscape(s).replace(/\\/g, "\\\\").replace(/"/g, "\\\"")}"`;
1914
+ }
1915
+ function xmlEscape(s) {
1916
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
1917
+ }
1918
+ const defaultExec = (cmd, args) => new Promise((resolve) => {
1919
+ execFile(cmd, args, { timeout: EXEC_TIMEOUT_MS }, (err, _stdout, stderr) => {
1920
+ if (!err) {
1921
+ resolve({
1922
+ code: 0,
1923
+ stderr
1924
+ });
1925
+ return;
1926
+ }
1927
+ resolve({
1928
+ code: typeof err.code === "number" ? err.code : -1,
1929
+ stderr: stderr || err.message
1930
+ });
1931
+ });
1932
+ });
1933
+ const EXIT_USAGE = 2;
1934
+ const CMD_BIND = "bind";
1935
+ const CMD_SETUP = "setup";
1936
+ const CMD_START = "start";
1937
+ const CMD_STOP = "stop";
1938
+ const CMD_STATUS = "status";
1939
+ const CMD_DOCTOR = "doctor";
1940
+ const CMD_UPDATE = "update";
1941
+ const CMD_UNINSTALL = "uninstall";
1942
+ const FLAG_CODE = "code";
1943
+ const FLAG_PORTAL = "portal";
1944
+ const FLAG_PURGE = "purge";
1945
+ const FLAG_YES = "yes";
1946
+ const FLAG_NO_AUTOSTART = "no-autostart";
1947
+ const FLAG_VERSION = "version";
1948
+ const RESTART_NOTIFY_TIMEOUT_MS = 5e3;
1949
+ const USAGE = `用法:shoplazza-ai-dev-cli runner <子命令>
1950
+ bind --code <绑定码> --portal <门户地址> [--no-autostart] 用页面生成的绑定码注册这台电脑,并装开机自启
1951
+ setup [--portal <门户地址>] [--no-autostart] 浏览器登录后注册这台电脑,并装开机自启
1952
+ --no-autostart:只注册、写本机配置,不装开机自启(本地开发用,之后手动 runner start)
1953
+ start 前台运行 runner(开机自启调用的就是它)
1954
+ stop 停止 runner(不删开机自启)
1955
+ status 查看是否在运行、电脑 id
1956
+ doctor [--portal <门户地址>] 自检并上报结果
1957
+ update [--version <版本>] 手动升级(不给版本用自动更新失败时的目标版本);runner 在跑时等当前任务结束后重启
1958
+ uninstall [--purge] [--yes] 停止并移除开机自启;--purge 同时清空 ~/.forge-runner`;
1959
+ function defaultRunnerDeps(cliVersion) {
1960
+ const profile = new RunnerProfile();
1961
+ const service = new RunnerService();
1962
+ const defaultPortal = () => loadConfig().portal;
1963
+ const err = (l) => console.error(l);
1964
+ return {
1965
+ cliVersion,
1966
+ profile,
1967
+ service,
1968
+ detector: new RuntimeDetector({ profile }),
1969
+ installPackage: async (version) => void await installRunnerPackage({
1970
+ profile,
1971
+ version
1972
+ }),
1973
+ defaultPortal,
1974
+ confirm: askYesNo,
1975
+ startDaemon: (ctx) => startRealDaemon({
1976
+ ...ctx,
1977
+ cliVersion,
1978
+ defaultPortal,
1979
+ service,
1980
+ err,
1981
+ run: async (host, opts) => (await import("./main.mjs")).runRealDaemon(host, opts)
1982
+ }),
1983
+ log: (l) => console.log(l),
1984
+ err
1985
+ };
1986
+ }
1987
+ async function runRunnerCommand(args, deps) {
1988
+ const [sub, ...rest] = args;
1989
+ const handler = sub === void 0 ? void 0 : {
1990
+ [CMD_BIND]: cmdBind,
1991
+ [CMD_SETUP]: cmdSetup,
1992
+ [CMD_START]: cmdStart,
1993
+ [CMD_STOP]: cmdStop,
1994
+ [CMD_STATUS]: cmdStatus,
1995
+ [CMD_DOCTOR]: cmdDoctor,
1996
+ [CMD_UPDATE]: cmdUpdate,
1997
+ [CMD_UNINSTALL]: cmdUninstall
1998
+ }[sub];
1999
+ if (!handler) {
2000
+ deps.err(sub === void 0 ? USAGE : `未知子命令:${sub}\n${USAGE}`);
2001
+ return EXIT_USAGE;
2002
+ }
2003
+ try {
2004
+ return await handler(rest, deps);
2005
+ } catch (e) {
2006
+ if (e instanceof UsageError) {
2007
+ deps.err(`${e.message}\n${USAGE}`);
2008
+ return EXIT_USAGE;
2009
+ }
2010
+ deps.err(describeRunnerError(e));
2011
+ return EXIT_FAILED;
2012
+ }
2013
+ }
2014
+ function describeRunnerError(e) {
2015
+ if (e instanceof RunnerLockedError) return `已有 runner 在运行(pid ${e.holderPid}),本进程退出`;
2016
+ if (e instanceof LoginFailedError) return `登录失败:${e.reason}`;
2017
+ if (e instanceof RunnerApiError || e instanceof LoginRequiredError || e instanceof ServiceCommandError || e instanceof InstallError || e instanceof UnsupportedPlatformError) {
2018
+ const hint = e.hint;
2019
+ return hint ? `${hint}\n(${e.message})` : e.message;
2020
+ }
2021
+ return `失败:${e instanceof Error ? e.message : String(e)}`;
2022
+ }
2023
+ var UsageError = class extends Error {};
2024
+ function parseFlags(args, valueFlags, boolFlags = []) {
2025
+ const out = {};
2026
+ for (let i = 0; i < args.length; i++) {
2027
+ const arg = args[i];
2028
+ const m = /^--([a-z-]+)(?:=(.*))?$/.exec(arg);
2029
+ const name = m?.[1];
2030
+ if (!m || name === void 0) throw new UsageError(`无法识别的参数:${arg}`);
2031
+ if (boolFlags.includes(name)) out[name] = true;
2032
+ else if (valueFlags.includes(name)) {
2033
+ const value = m[2] ?? args[++i];
2034
+ if (value === void 0 || value.startsWith("--")) throw new UsageError(`参数 --${name} 缺少值`);
2035
+ out[name] = value;
2036
+ } else throw new UsageError(`无法识别的参数:${arg}`);
2037
+ }
2038
+ return out;
2039
+ }
2040
+ function portalFrom(flags, fallback) {
2041
+ const raw = typeof flags[FLAG_PORTAL] === "string" ? flags[FLAG_PORTAL] : fallback();
2042
+ try {
2043
+ return normalizePortalURL(raw);
2044
+ } catch {
2045
+ throw new UsageError(`门户地址格式不对:${raw}(示例:https://forge.shoplazza.com)`);
2046
+ }
2047
+ }
2048
+ async function cmdBind(args, d) {
2049
+ const flags = parseFlags(args, [FLAG_CODE, FLAG_PORTAL], [FLAG_NO_AUTOSTART]);
2050
+ const code = flags[FLAG_CODE];
2051
+ if (typeof code !== "string" || code.trim() === "") throw new UsageError("缺少 --code <绑定码>(在页面「添加 agent」里生成)");
2052
+ if (typeof flags[FLAG_PORTAL] !== "string") throw new UsageError("缺少 --portal <门户地址>");
2053
+ const portal = portalFrom(flags, d.defaultPortal);
2054
+ const runtimes = await d.detector.detect();
2055
+ const creds = await registerWithBindCode(code, {
2056
+ portal,
2057
+ profile: d.profile,
2058
+ cliVersion: d.cliVersion,
2059
+ runtimes
2060
+ });
2061
+ d.log(`已注册这台电脑,电脑 id:${creds.runnerId}(门户 ${creds.portalHost})`);
2062
+ if (flags[FLAG_NO_AUTOSTART] === true) return skipAutostart(d);
2063
+ return installAndStart(d);
2064
+ }
2065
+ async function cmdSetup(args, d) {
2066
+ const flags = parseFlags(args, [FLAG_PORTAL], [FLAG_NO_AUTOSTART]);
2067
+ const portal = portalFrom(flags, d.defaultPortal);
2068
+ const runtimes = await d.detector.detect();
2069
+ const creds = await registerWithLogin({
2070
+ portal,
2071
+ profile: d.profile,
2072
+ cliVersion: d.cliVersion,
2073
+ runtimes,
2074
+ login: d.login
2075
+ });
2076
+ d.log(`已注册这台电脑,电脑 id:${creds.runnerId}(门户 ${creds.portalHost})`);
2077
+ if (flags[FLAG_NO_AUTOSTART] === true) return skipAutostart(d);
2078
+ d.log("正在把 runner 安装到 ~/.forge-runner …");
2079
+ await d.installPackage(d.cliVersion);
2080
+ return installAndStart(d);
2081
+ }
2082
+ function skipAutostart(d) {
2083
+ d.log("已跳过开机自启;需要时手动执行 runner start 前台运行(Ctrl+C 停止)");
2084
+ return EXIT_OK;
2085
+ }
2086
+ async function installAndStart(d) {
2087
+ await d.service.install();
2088
+ await d.service.start();
2089
+ d.log("已安装开机自启并启动 runner;之后开机会自动运行");
2090
+ return EXIT_OK;
2091
+ }
2092
+ async function cmdStart(args, d) {
2093
+ parseFlags(args, []);
2094
+ let lock;
2095
+ try {
2096
+ lock = acquireRunnerLock(d.profile.lockPath);
2097
+ } catch (e) {
2098
+ if (e instanceof RunnerLockedError) {
2099
+ d.err(describeRunnerError(e));
2100
+ return EXIT_FAILED;
2101
+ }
2102
+ throw e;
2103
+ }
2104
+ try {
2105
+ if (!d.startDaemon) {
2106
+ d.err("runner 守护进程入口还没有接入,无法前台运行");
2107
+ return EXIT_FAILED;
2108
+ }
2109
+ return await d.startDaemon({
2110
+ profile: d.profile,
2111
+ lock
2112
+ }) ?? EXIT_OK;
2113
+ } finally {
2114
+ lock.release();
2115
+ }
2116
+ }
2117
+ async function cmdStop(args, d) {
2118
+ parseFlags(args, []);
2119
+ if (!d.service.isInstalled()) {
2120
+ d.log("没有安装开机自启,没有可停止的后台服务;前台运行的 runner 请在它所在的终端按 Ctrl+C 结束");
2121
+ return EXIT_OK;
2122
+ }
2123
+ await d.service.stop();
2124
+ d.log("已停止 runner;下次登录系统会再次自动启动,要彻底移除请执行 runner uninstall");
2125
+ return EXIT_OK;
2126
+ }
2127
+ async function cmdStatus(args, d) {
2128
+ parseFlags(args, []);
2129
+ const pid = inspectRunnerLock(d.profile.lockPath)?.pid;
2130
+ if (pid === void 0) d.log("runner:未运行");
2131
+ else {
2132
+ const port = safePort(d.profile);
2133
+ d.log(`runner:运行中(pid ${pid}${port === void 0 ? "" : `,健康端口 ${port}`})`);
2134
+ }
2135
+ const registered = d.profile.listCredentials();
2136
+ if (registered.length === 0) d.log("电脑 id:未注册(先执行 runner setup 或 runner bind)");
2137
+ for (const c of registered) d.log(`电脑 id:${c.runnerId}(门户 ${c.portalHost})`);
2138
+ d.log(d.service.isInstalled() ? `开机自启:已安装(${d.service.unitPath})` : "开机自启:未安装");
2139
+ return EXIT_OK;
2140
+ }
2141
+ async function cmdDoctor(args, d) {
2142
+ const flags = parseFlags(args, [FLAG_PORTAL]);
2143
+ const registered = d.profile.listCredentials();
2144
+ const portal = doctorPortal(flags, registered, d);
2145
+ const creds = registered.find((c) => c.portalHost === portalHostOf(portal));
2146
+ if (!creds) {
2147
+ d.err("这台电脑还没注册到该门户,无法取得自检目标(先执行 runner setup 或 runner bind)");
2148
+ return EXIT_FAILED;
2149
+ }
2150
+ const http = new PlatformHttp({
2151
+ portal,
2152
+ token: creds.runnerToken
2153
+ });
2154
+ const targets = await loadDoctorTargets(http, d, creds.portalHost);
2155
+ const report = await runDoctor({
2156
+ detector: d.detector,
2157
+ targets,
2158
+ ...d.doctorOptions
2159
+ });
2160
+ for (const line of formatDoctorReport(report)) d.log(line);
2161
+ await reportDoctor(http, report);
2162
+ d.log("已上报自检结果");
2163
+ return EXIT_OK;
2164
+ }
2165
+ function doctorPortal(flags, registered, d) {
2166
+ if (typeof flags[FLAG_PORTAL] === "string") return portalFrom(flags, d.defaultPortal);
2167
+ const fallback = portalFrom(flags, d.defaultPortal);
2168
+ if (registered.length === 1 && registered[0].portalHost !== portalHostOf(fallback)) return registered[0].portal;
2169
+ return fallback;
2170
+ }
2171
+ async function loadDoctorTargets(http, d, portalHost) {
2172
+ try {
2173
+ const targets = normalizeDoctorTargets((await http.call("GET", RUNNER_CONFIG_PATH))?.doctor_targets);
2174
+ d.profile.writeDoctorTargets(portalHost, targets);
2175
+ return targets;
2176
+ } catch (e) {
2177
+ const cached = d.profile.readDoctorTargets(portalHost);
2178
+ if (!cached) throw e;
2179
+ d.log("平台暂时连不上,自检目标用本机缓存的");
2180
+ return cached;
2181
+ }
2182
+ }
2183
+ async function cmdUpdate(args, d) {
2184
+ const flags = parseFlags(args, [FLAG_VERSION]);
2185
+ const version = typeof flags[FLAG_VERSION] === "string" ? flags[FLAG_VERSION] : readUpdateError(d.profile)?.version;
2186
+ if (version === void 0) throw new UsageError("缺少 --version <版本>(这台电脑没有自动更新失败的记录,无法确定要装哪个版本)");
2187
+ clearUpdateError(d.profile);
2188
+ d.log(`正在把 runner 更新到 ${version} …`);
2189
+ const res = await performUpdate({
2190
+ version,
2191
+ profile: d.profile,
2192
+ run: d.updateRun,
2193
+ exit: () => void 0
2194
+ });
2195
+ if (res.skipped === "busy") {
2196
+ d.err("已有一次更新在进行(可能是 runner 正在自动更新),稍后再试");
2197
+ return EXIT_FAILED;
2198
+ }
2199
+ if (!res.ok) {
2200
+ d.err(`更新失败:${readUpdateError(d.profile)?.message ?? "原因未知"}`);
2201
+ return EXIT_FAILED;
2202
+ }
2203
+ if (inspectRunnerLock(d.profile.lockPath) !== void 0) {
2204
+ await notifyDaemonRestart(d.profile);
2205
+ d.log(`已装好 ${version};runner 不再接新活,当前在跑的任务结束后自动重启到新版本`);
2206
+ return EXIT_OK;
2207
+ }
2208
+ if (d.service.isInstalled()) {
2209
+ await d.service.start();
2210
+ d.log(`已装好 ${version} 并重启 runner`);
2211
+ return EXIT_OK;
2212
+ }
2213
+ d.log(`已装好 ${version};没有安装开机自启,执行 runner start 启动`);
2214
+ return EXIT_OK;
2215
+ }
2216
+ async function notifyDaemonRestart(profile) {
2217
+ const port = profile.readPort();
2218
+ if (port === void 0) throw new Error("runner is running but runner.port is missing");
2219
+ const res = await fetch(`http://127.0.0.1:${port}${LOCAL_RESTART_PATH}`, {
2220
+ method: "POST",
2221
+ signal: AbortSignal.timeout(RESTART_NOTIFY_TIMEOUT_MS)
2222
+ });
2223
+ if (!res.ok) throw new Error(`notify runner restart failed: status=${res.status}`);
2224
+ }
2225
+ async function cmdUninstall(args, d) {
2226
+ const flags = parseFlags(args, [], [FLAG_PURGE, FLAG_YES]);
2227
+ const purge = flags[FLAG_PURGE] === true;
2228
+ if (purge && flags[FLAG_YES] !== true) {
2229
+ if (!await d.confirm(`将清空 ${d.profile.root}(凭据、缓存、日志、已装的 CLI 都会删除),这台电脑要重新注册才能再用。确认吗?`)) {
2230
+ d.err("已取消,没有做任何改动");
2231
+ return EXIT_FAILED;
2232
+ }
2233
+ }
2234
+ await d.service.uninstall();
2235
+ d.log("已停止 runner 并移除开机自启");
2236
+ if (purge) {
2237
+ rmSync(d.profile.root, {
2238
+ recursive: true,
2239
+ force: true
2240
+ });
2241
+ d.log(`已清空 ${d.profile.root};页面上这台电脑的记录仍在,可在页面点「解绑这台电脑」`);
2242
+ }
2243
+ return EXIT_OK;
2244
+ }
2245
+ function safePort(profile) {
2246
+ try {
2247
+ return profile.readPort();
2248
+ } catch {
2249
+ return;
2250
+ }
2251
+ }
2252
+ function askYesNo(question) {
2253
+ if (!process.stdin.isTTY) return Promise.resolve(false);
2254
+ const rl = createInterface({
2255
+ input: process.stdin,
2256
+ output: process.stdout
2257
+ });
2258
+ return new Promise((resolve) => {
2259
+ rl.question(`${question} [y/N] `, (answer) => {
2260
+ rl.close();
2261
+ resolve(/^y(es)?$/i.test(answer.trim()));
2262
+ });
2263
+ });
2264
+ }
2265
+ export { defaultRunnerDeps, runRunnerCommand };