pi-web-ui 0.114.1 → 0.114.2

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.
Files changed (117) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/README.md +187 -187
  3. package/README.zh-CN.md +227 -227
  4. package/README.zh-TW.md +227 -227
  5. package/bin/device-hub-cli.mjs +577 -577
  6. package/bin/frp-manager.mjs +1573 -1573
  7. package/bin/pi-device-hub.mjs +9 -9
  8. package/bin/pi-web-ui.mjs +4081 -4081
  9. package/deploy/nginx-subpath.conf +100 -100
  10. package/deploy/pi-web-ui.service +36 -36
  11. package/dist/server/agent-service.js +59 -10
  12. package/dist/server/attachments.js +6 -6
  13. package/dist/server/canvas/canvas-orchestrator.js +3 -3
  14. package/dist/server/communicate-tool.js +37 -11
  15. package/dist/server/compaction-instructions.js +8 -8
  16. package/dist/server/device-center/desktop-page.js +228 -228
  17. package/dist/server/device-center/hub-page.js +64 -64
  18. package/dist/server/device-center/native-desktop/macos.js +190 -190
  19. package/dist/server/device-center/native-desktop/windows.js +116 -116
  20. package/dist/server/dsh/runtime/cordis.yml +1 -1
  21. package/dist/server/dsh/runtime/custom-prompt.mjs +33 -33
  22. package/dist/server/dsh/runtime/goal-rpc.mjs +1309 -1309
  23. package/dist/server/dsh/runtime/launcher.mjs +235 -235
  24. package/dist/server/dsh/runtime/override.patch.yml +89 -89
  25. package/dist/server/dsh/runtime/runtime-root.mjs +405 -405
  26. package/dist/server/durable/durable-event-projector.js +19 -3
  27. package/dist/server/durable/durable-models.js +134 -65
  28. package/dist/server/eval-tool.js +135 -135
  29. package/dist/server/model-resolver.js +4 -1
  30. package/dist/server/patch-bash-process.js +89 -89
  31. package/dist/server/patch-tool.js +9 -9
  32. package/dist/server/patch-turn-end-boundary.js +3 -3
  33. package/dist/server/persona-chain.js +8 -8
  34. package/dist/server/remote-ssh-service.js +39 -39
  35. package/dist/server/schedule-agent-tool.js +11 -6
  36. package/dist/server/scheduler-tasks.js +84 -2
  37. package/dist/server/scm-commitmsg.js +10 -10
  38. package/dist/server/setup-page.js +620 -620
  39. package/dist/server/universal/universal-session.js +19 -18
  40. package/dist/server/vision-bridge.js +18 -18
  41. package/docs/device-center.md +148 -148
  42. package/docs/device-desktop.md +48 -48
  43. package/docs/dsh-engine.md +493 -493
  44. package/extensions/webui.ts +335 -335
  45. package/package.json +1 -1
  46. package/plugin-sdk/README.md +174 -174
  47. package/plugin-sdk/client-utils.mjs +279 -279
  48. package/plugin-sdk/import-check.mjs +210 -210
  49. package/plugin-sdk/index.d.ts +698 -698
  50. package/plugin-sdk/index.mjs +696 -696
  51. package/plugin-sdk/package.json +13 -13
  52. package/plugin-sdk/ssh-host-trust.mjs +225 -225
  53. package/themes/aetheris.css +501 -501
  54. package/themes/ayu-light.css +116 -116
  55. package/themes/bases/flow-base.css +1357 -1357
  56. package/themes/bases/obsidian-base.css +895 -895
  57. package/themes/bases/statusbar-flat-base.css +112 -112
  58. package/themes/bases/zhujian-base.css +688 -688
  59. package/themes/bases/zhupi-base.css +660 -660
  60. package/themes/catppuccin-latte.css +119 -119
  61. package/themes/catppuccin.css +116 -116
  62. package/themes/claude-code-dark.css +147 -147
  63. package/themes/codex.css +114 -114
  64. package/themes/cyberpunk.css +50 -50
  65. package/themes/dark-teal.css +264 -264
  66. package/themes/dazzle.css +38 -38
  67. package/themes/everforest-light.css +115 -115
  68. package/themes/flow-light.css +164 -164
  69. package/themes/flow.css +161 -161
  70. package/themes/geist.css +114 -114
  71. package/themes/gruvbox-light.css +115 -115
  72. package/themes/kanagawa-lotus.css +115 -115
  73. package/themes/md-preview.css +24 -24
  74. package/themes/mist.css +166 -166
  75. package/themes/nord.css +107 -107
  76. package/themes/one-dark.css +106 -106
  77. package/themes/paper.css +174 -174
  78. package/themes/rose-pine-dawn.css +114 -114
  79. package/themes/sakura.css +166 -166
  80. package/themes/solarized-light.css +114 -114
  81. package/themes/tokyo-night.css +115 -115
  82. package/themes/translucent.css +85 -85
  83. package/themes/transparent.css +116 -116
  84. package/themes/vs-code-dark.css +147 -147
  85. package/themes/wallpaper-flow.css +382 -382
  86. package/themes/wallpaper-obsidian.css +74 -74
  87. package/themes/white.css +164 -164
  88. package/themes/zhujian-dark.css +115 -115
  89. package/themes/zhujian.css +114 -114
  90. package/themes/zhupi-dark.css +115 -115
  91. package/themes/zhupi.css +114 -114
  92. package/web/dist/.build-assets.json +1 -1
  93. package/web/dist/assets/{BgTasksModal-BcXJ20RO.js → BgTasksModal-BIlQ89vr.js} +1 -1
  94. package/web/dist/assets/{BgTasksModal-DjQmiKnE.js → BgTasksModal-Ck2sjlPM.js} +1 -1
  95. package/web/dist/assets/{CanvasStudio-PI9pid0Y.js → CanvasStudio-B3W6b_rA.js} +1 -1
  96. package/web/dist/assets/{CanvasStudio-nf5-HxLM.js → CanvasStudio-Csv1Sj1-.js} +1 -1
  97. package/web/dist/assets/{DeviceCenter-CYttJw2a.js → DeviceCenter-BQdDcO8A.js} +1 -1
  98. package/web/dist/assets/{DeviceCenter-DPe4sz74.js → DeviceCenter-CHRKL0Vy.js} +1 -1
  99. package/web/dist/assets/{FilePreview-C9Ut4Lq6.js → FilePreview-B9xoU6ON.js} +1 -1
  100. package/web/dist/assets/{FilePreview-CvK3ZzX5.js → FilePreview-DUQpVZkH.js} +1 -1
  101. package/web/dist/assets/{GlobalSearchModal-C5e-OCw2.js → GlobalSearchModal-BXEGvUZq.js} +1 -1
  102. package/web/dist/assets/{GlobalSearchModal-H7pFK2UC.js → GlobalSearchModal-CnVPmfOI.js} +1 -1
  103. package/web/dist/assets/{GroupConversation-C2wNM0dQ.js → GroupConversation-CyIpQzDd.js} +1 -1
  104. package/web/dist/assets/{GroupConversation-ChN3TWQK.js → GroupConversation-DgYV3uYS.js} +1 -1
  105. package/web/dist/assets/{SCMPanel-buTGziDB.js → SCMPanel-imYI2Ecw.js} +1 -1
  106. package/web/dist/assets/{SCMPanel-kx-SCL2s.js → SCMPanel-sVZcV7dR.js} +1 -1
  107. package/web/dist/assets/{SettingsModal-BsUF8jqr.js → SettingsModal-Xw1Yoi3_.js} +1 -1
  108. package/web/dist/assets/{SettingsModal-D357Ky7P.js → SettingsModal-mb4e34-0.js} +1 -1
  109. package/web/dist/assets/{TerminalPanel-BBuM_Sez.js → TerminalPanel-CLkJJvxg.js} +1 -1
  110. package/web/dist/assets/{TerminalPanel-D6x6xz8Q.js → TerminalPanel-DpcIellm.js} +1 -1
  111. package/web/dist/assets/{TuiOverlayModal-CdbGV3Za.js → TuiOverlayModal-4-fFAZe7.js} +1 -1
  112. package/web/dist/assets/{TuiOverlayModal-d6x9u25n.js → TuiOverlayModal-DCu01lks.js} +1 -1
  113. package/web/dist/assets/{index-D6u8xH0o.js → index-Cdh3sibd.js} +4 -4
  114. package/web/dist/assets/{index-BPvpea8t.js → index-DWw_SxRq.js} +4 -4
  115. package/web/dist/index.html +29 -29
  116. package/web/dist/sw.js +179 -179
  117. package/web/public/sw.js +179 -179
@@ -1,577 +1,577 @@
1
- /** Standalone Hub lifecycle. Only Node built-ins; never imports the main CLI or agent SDK. */
2
- import { spawnSync } from "node:child_process";
3
- import { randomUUID } from "node:crypto";
4
- import { createServer } from "node:net";
5
- import { request } from "node:http";
6
- import {
7
- mkdirSync,
8
- readFileSync,
9
- writeFileSync,
10
- renameSync,
11
- unlinkSync,
12
- existsSync,
13
- rmdirSync,
14
- readdirSync,
15
- } from "node:fs";
16
- import { homedir, hostname } from "node:os";
17
- import { setTimeout as delay, setImmediate as yieldImmediate } from "node:timers/promises";
18
- import { join, resolve } from "node:path";
19
- import { fileURLToPath } from "node:url";
20
-
21
- export const HUB_HELP = `Usage: pi-web-ui hub [install|start|stop|restart|status|uninstall] [options]
22
- Without a command, run in the foreground (Ctrl+C to stop).
23
- Options: --host HOST --port PORT --public-url URL --data-dir PATH
24
- --allow-registration[=true|false] --help
25
- install saves configuration, enables login autostart and starts the Hub.
26
- Other lifecycle commands use the saved configuration; status accepts --json.
27
- Close registration after the first account: hub restart --allow-registration=false
28
- Only that saved setting changes; all other settings are retained.
29
- Registration is disabled unless explicitly enabled. Foreground mode also accepts PI_DEVICE_HUB_*.
30
- Service: systemd --user (Linux), launchd user agent (macOS), logon scheduled task (Windows).
31
- Linux boot without login requires an administrator to enable linger for your user.
32
- uninstall stops and removes the service; Hub account/device data is retained.`;
33
- const ENTRY = fileURLToPath(new URL("./pi-device-hub.mjs", import.meta.url));
34
- const LABEL = "com.xingshuyin.pi-device-hub";
35
- const TASK = "pi-device-hub";
36
- const UNIT = "pi-device-hub.service";
37
- const flags = { "--host": "HOST", "--port": "PORT", "--public-url": "PUBLIC_URL", "--data-dir": "DATA_DIR" };
38
- const optionalEnv = ["DEVICE_DOMAIN", "PATH_ACCESS", "PORTAL_PORTS"];
39
-
40
- export function parseHubArgs(argv, env = process.env) {
41
- const args = [...argv];
42
- const command = args[0] && !args[0].startsWith("-") ? args.shift() : "foreground";
43
- if (!["foreground", "install", "start", "stop", "restart", "status", "uninstall"].includes(command))
44
- throw new Error(`Unknown Hub command: ${command}`);
45
- const values = {};
46
- if (command === "status" && args.length === 1 && args[0] === "--json") return { command, json: true };
47
- if (command === "restart" && args.length === 1 && /^--allow-registration=(true|false)$/.test(args[0]))
48
- return { command, registration: args[0].endsWith("=true") ? "1" : "0" };
49
- for (let i = 0; i < args.length; i++) {
50
- const [key, ...rest] = args[i].split("=");
51
- if (key === "--help" || key === "-h") return { command, help: true };
52
- if (!["foreground", "install"].includes(command)) throw new Error(`${command} accepts no options`);
53
- if (key === "--allow-registration") {
54
- const value = rest.length ? rest.join("=") : "true";
55
- if (!["true", "false"].includes(value)) throw new Error("--allow-registration expects true or false");
56
- values.ALLOW_REGISTRATION = value === "true" ? "1" : "0";
57
- continue;
58
- }
59
- if (!flags[key]) throw new Error(`Unknown Hub option: ${key}`);
60
- const value = rest.length ? rest.join("=") : args[++i];
61
- if (!value || value.startsWith("--") || /[\x00-\x1f]/.test(value)) throw new Error(`Invalid value for ${key}`);
62
- values[flags[key]] = value;
63
- }
64
- if (!["foreground", "install"].includes(command)) return { command };
65
- const settings = {};
66
- for (const key of [...Object.values(flags), ...optionalEnv]) {
67
- const value = values[key] ?? env[`PI_DEVICE_HUB_${key}`];
68
- if (value !== undefined) settings[`PI_DEVICE_HUB_${key}`] = value;
69
- }
70
- settings.PI_DEVICE_HUB_HOST ??= "127.0.0.1";
71
- settings.PI_DEVICE_HUB_PORT ??= "8790";
72
- settings.PI_DEVICE_HUB_DATA_DIR = resolve(settings.PI_DEVICE_HUB_DATA_DIR ?? join(homedir(), ".pi-device-hub"));
73
- // Installing must not inherit an accidentally enabled registration environment variable.
74
- settings.PI_DEVICE_HUB_ALLOW_REGISTRATION =
75
- values.ALLOW_REGISTRATION ?? (command === "foreground" && env.PI_DEVICE_HUB_ALLOW_REGISTRATION === "1" ? "1" : "0");
76
- validateSettings(settings);
77
- return { command, settings };
78
- }
79
-
80
- function validateSettings(settings) {
81
- for (const value of Object.values(settings))
82
- if (typeof value !== "string" || /[\x00-\x1f]/.test(value)) throw new Error("Invalid Hub configuration value");
83
- if (!settings.PI_DEVICE_HUB_HOST) throw new Error("Hub host must not be empty");
84
- const port = settings.PI_DEVICE_HUB_PORT;
85
- if (!/^\d+$/.test(port) || Number(port) < 1 || Number(port) > 65535) throw new Error("Invalid Hub port");
86
- if (!settings.PI_DEVICE_HUB_PUBLIC_URL) throw new Error("--public-url (or PI_DEVICE_HUB_PUBLIC_URL) is required");
87
- const url = new URL(settings.PI_DEVICE_HUB_PUBLIC_URL);
88
- if (
89
- !["http:", "https:"].includes(url.protocol) ||
90
- url.origin !== settings.PI_DEVICE_HUB_PUBLIC_URL ||
91
- url.username ||
92
- url["pass" + "word"]
93
- )
94
- throw new Error("--public-url (or PI_DEVICE_HUB_PUBLIC_URL) must be a canonical HTTP(S) root origin");
95
- }
96
-
97
- const xml = (s) =>
98
- String(s).replace(/[<>&"']/g, (c) => ({ "<": "&lt;", ">": "&gt;", "&": "&amp;", '"': "&quot;", "'": "&apos;" })[c]);
99
- // CommandLineToArgvW quoting, not shell quoting. Every argument is passed directly to node.exe.
100
- export const windowsArg = (s) =>
101
- `"${String(s)
102
- .replace(/(\\*)"/g, '$1$1\\"')
103
- .replace(/(\\+)$/g, "$1$1")}"`;
104
- const systemdArg = (s) =>
105
- `"${String(s)
106
- .replace(/\\/g, "\\\\")
107
- .replace(/"/g, '\\"')
108
- .replace(/%/g, "%%")
109
- .replace(/\$/g, () => "$$")}"`;
110
-
111
- export function hubServicePlan({
112
- platform = process.platform,
113
- home = homedir(),
114
- env = process.env,
115
- node = process.execPath,
116
- entry = ENTRY,
117
- uid = process.getuid?.(),
118
- user = env.USERNAME,
119
- } = {}) {
120
- const root =
121
- platform === "win32"
122
- ? join(env.APPDATA || join(home, "AppData", "Roaming"), "pi-device-hub-cli")
123
- : join(home, ".config", "pi-device-hub-cli");
124
- const config = join(root, "service.json");
125
- const args = [entry, "--service-config", config];
126
- if (platform === "linux")
127
- return {
128
- root,
129
- config,
130
- file: join(home, ".config", "systemd", "user", UNIT),
131
- content: `[Unit]\nDescription=pi device Hub\nAfter=network.target\n\n[Service]\nExecStart=${[node, ...args].map(systemdArg).join(" ")}\nRestart=on-failure\nRestartSec=5\n\n[Install]\nWantedBy=default.target\n`,
132
- manager: "systemctl",
133
- commands: {
134
- install: [
135
- ["--user", "daemon-reload"],
136
- ["--user", "enable", "--now", UNIT],
137
- ],
138
- start: [["--user", "start", UNIT]],
139
- stop: [["--user", "stop", UNIT]],
140
- restart: [["--user", "restart", UNIT]],
141
- status: [["--user", "show", UNIT, "--property=ActiveState,SubState,UnitFileState"]],
142
- uninstall: [["--user", "disable", "--now", UNIT]],
143
- },
144
- };
145
- if (platform === "darwin") {
146
- const file = join(home, "Library", "LaunchAgents", `${LABEL}.plist`);
147
- const target = `gui/${uid}/${LABEL}`;
148
- return {
149
- root,
150
- config,
151
- file,
152
- content: `<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n<plist version="1.0"><dict><key>Label</key><string>${LABEL}</string><key>ProgramArguments</key><array>${[node, ...args].map((s) => `<string>${xml(s)}</string>`).join("")}</array><key>RunAtLoad</key><true/><key>KeepAlive</key><dict><key>SuccessfulExit</key><false/></dict><key>StandardOutPath</key><string>${xml(join(root, "stdout.log"))}</string><key>StandardErrorPath</key><string>${xml(join(root, "stderr.log"))}</string></dict></plist>\n`,
153
- manager: "launchctl",
154
- commands: {
155
- install: [["bootstrap", `gui/${uid}`, file]],
156
- start: [["bootstrap", `gui/${uid}`, file]],
157
- stop: [["bootout", target]],
158
- restart: [
159
- ["bootout", target],
160
- ["bootstrap", `gui/${uid}`, file],
161
- ],
162
- status: [["print", target]],
163
- uninstall: [["bootout", target]],
164
- },
165
- };
166
- }
167
- if (platform === "win32") {
168
- if (!user) throw new Error("Cannot determine Windows task user");
169
- const identity = env.USERDOMAIN ? `${env.USERDOMAIN}\\${user}` : user;
170
- return {
171
- root,
172
- config,
173
- file: join(root, "task.xml"),
174
- content: `<?xml version="1.0" encoding="UTF-16"?>\n<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task"><Triggers><LogonTrigger><Enabled>true</Enabled><UserId>${xml(identity)}</UserId></LogonTrigger></Triggers><Principals><Principal id="Author"><UserId>${xml(identity)}</UserId><LogonType>InteractiveToken</LogonType><RunLevel>LeastPrivilege</RunLevel></Principal></Principals><Settings><MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy><DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries><StopIfGoingOnBatteries>false</StopIfGoingOnBatteries><ExecutionTimeLimit>PT0S</ExecutionTimeLimit><RestartOnFailure><Interval>PT1M</Interval><Count>3</Count></RestartOnFailure></Settings><Actions Context="Author"><Exec><Command>${xml(node)}</Command><Arguments>${xml(args.map(windowsArg).join(" "))}</Arguments></Exec></Actions></Task>`,
175
- manager: "schtasks.exe",
176
- commands: {
177
- install: [
178
- ["/Create", "/TN", TASK, "/XML", join(root, "task.xml")],
179
- ["/Run", "/TN", TASK],
180
- ],
181
- start: [["/Run", "/TN", TASK]],
182
- stop: [["/End", "/TN", TASK]],
183
- restart: [
184
- ["/End", "/TN", TASK],
185
- ["/Run", "/TN", TASK],
186
- ],
187
- status: [["/Query", "/TN", TASK, "/V", "/FO", "LIST"]],
188
- uninstall: [
189
- ["/End", "/TN", TASK],
190
- ["/Delete", "/TN", TASK, "/F"],
191
- ],
192
- },
193
- };
194
- }
195
- throw new Error(`Unsupported Hub service platform: ${platform}`);
196
- }
197
-
198
- // One budget per composite native phase, rather than a fresh timeout per subprocess.
199
- // SIGKILL prevents a timed-out native command from extending the runner's 45s grace.
200
- function nativePhase(inspect, now) {
201
- const deadline = now() + 30000;
202
- return (file, args) => {
203
- const remaining = Math.floor(deadline - now());
204
- if (remaining <= 0) throw new Error("Hub native operation exceeded its 30s deadline");
205
- return inspect(file, args, { encoding: "utf8", windowsHide: true, timeout: remaining, killSignal: "SIGKILL" });
206
- };
207
- }
208
-
209
- async function yieldForCancellation(signal) {
210
- await yieldImmediate(undefined, { signal });
211
- await yieldImmediate(undefined, { signal });
212
- signal?.throwIfAborted();
213
- }
214
-
215
- export function assertServiceAbsent(plan, inspect = spawnSync, now = () => performance.now()) {
216
- const native = nativePhase(inspect, now);
217
- const result = native(
218
- plan.manager,
219
- plan.manager === "systemctl"
220
- ? ["--user", "show", UNIT, "--property=LoadState", "--value"]
221
- : plan.commands.status[0],
222
- );
223
- if (result.error) throw result.error;
224
- if (plan.manager === "systemctl" && result.status === 0 && result.stdout.trim() === "not-found") return;
225
- if (plan.manager === "launchctl" && result.status !== 0 && /Could not find service/i.test(result.stderr)) return;
226
- if (plan.manager === "schtasks.exe") {
227
- // Locale-independent absence check: query the scheduler COM API and accept only file-not-found.
228
- const script = `$s=New-Object -ComObject Schedule.Service; $s.Connect(); try { $null=$s.GetFolder('\\').GetTask('${TASK}'); exit 0 } catch { if ($_.Exception.HResult -eq -2147024894) { exit 3 }; exit 4 }`;
229
- const check = native("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", script]);
230
- if (!check.error && check.status === 3) return;
231
- }
232
- throw new Error("Hub service already exists or service absence could not be verified. Refusing to overwrite.");
233
- }
234
-
235
- export function assertPortAvailable(settings) {
236
- return new Promise((done, reject) => {
237
- const server = createServer();
238
- server.once("error", reject);
239
- server.listen(
240
- { host: settings.PI_DEVICE_HUB_HOST, port: Number(settings.PI_DEVICE_HUB_PORT), exclusive: true },
241
- () => server.close((error) => (error ? reject(error) : done())),
242
- );
243
- });
244
- }
245
-
246
- export function probeHub(settings, signal) {
247
- signal?.throwIfAborted();
248
- return new Promise((done) => {
249
- const host =
250
- settings.PI_DEVICE_HUB_HOST === "::"
251
- ? "::1"
252
- : settings.PI_DEVICE_HUB_HOST === "0.0.0.0"
253
- ? "127.0.0.1"
254
- : settings.PI_DEVICE_HUB_HOST;
255
- const req = request(
256
- {
257
- signal,
258
- host,
259
- port: Number(settings.PI_DEVICE_HUB_PORT),
260
- path: "/health",
261
- headers: { Host: new URL(settings.PI_DEVICE_HUB_PUBLIC_URL).host },
262
- timeout: 1000,
263
- },
264
- (res) => {
265
- let body = "";
266
- res.on("data", (chunk) => {
267
- body += chunk;
268
- if (body.length > 8192) req.destroy();
269
- });
270
- res.on("error", () => done(null));
271
- res.on("end", () => {
272
- try {
273
- const health = JSON.parse(body);
274
- done(
275
- res.statusCode === 200 && health.service === "pi-device-hub" && health.status === "ok" ? health : null,
276
- );
277
- } catch {
278
- done(null);
279
- }
280
- });
281
- },
282
- );
283
- req.on("timeout", () => req.destroy());
284
- req.on("error", () => done(null));
285
- req.end();
286
- });
287
- }
288
-
289
- async function waitForHub(settings, signal) {
290
- const deadline = Date.now() + 15000;
291
- while (Date.now() < deadline) {
292
- signal?.throwIfAborted();
293
- const health = await probeHub(settings, signal);
294
- signal?.throwIfAborted();
295
- if (health) {
296
- if (
297
- health.instanceId !== settings.PI_DEVICE_HUB_INSTANCE_ID ||
298
- health.allowRegistration !== (settings.PI_DEVICE_HUB_ALLOW_REGISTRATION === "1")
299
- )
300
- throw new Error("Hub health does not match the saved instance/configuration");
301
- return;
302
- }
303
- await delay(250, undefined, { signal });
304
- }
305
- throw new Error("Hub did not become healthy within 15 seconds; service configuration retained for diagnosis");
306
- }
307
-
308
- export function runManager(file, args, inspect = spawnSync, now = () => performance.now()) {
309
- const native = nativePhase(inspect, now);
310
- if (file === "launchctl" && ["bootout", "bootstrap"].includes(args[0])) {
311
- const target = args[0] === "bootout" ? args[1] : `${args[1]}/${LABEL}`;
312
- const state = native(file, ["print", target]);
313
- if (state.error) throw state.error;
314
- if (state.status === 0 && args[0] === "bootstrap") return "Hub is already loaded";
315
- if (state.status !== 0) {
316
- if (!/Could not find service/i.test(state.stderr))
317
- throw new Error(state.stderr || "Could not inspect launchd job");
318
- if (args[0] === "bootout") return "Hub is already stopped";
319
- }
320
- }
321
- // Ending an already stopped task is successful; scheduler errors still propagate.
322
- if (file === "schtasks.exe" && args[0] === "/End") {
323
- file = "powershell.exe";
324
- args = [
325
- "-NoProfile",
326
- "-NonInteractive",
327
- "-Command",
328
- `$ErrorActionPreference='Stop'; $s=New-Object -ComObject Schedule.Service; $s.Connect(); $t=$s.GetFolder('\\').GetTask('${TASK}'); if ($t.State -eq 4) { $t.Stop(0) }`,
329
- ];
330
- }
331
- const result = native(file, args);
332
- if (result.error || result.status !== 0)
333
- throw new Error(
334
- `${file} ${args.join(" ")}: ${result.error?.message || result.stderr || result.stdout || `exit ${result.status}`}`,
335
- );
336
- return result.stdout?.trim();
337
- }
338
- export function acquireHubLock(
339
- root,
340
- {
341
- pid = process.pid,
342
- machine = hostname(),
343
- alive = (ownerPid) => {
344
- try {
345
- process.kill(ownerPid, 0);
346
- return true;
347
- } catch (error) {
348
- return error.code !== "ESRCH";
349
- }
350
- },
351
- } = {},
352
- ) {
353
- const lock = join(root, "lifecycle.lock");
354
- const token = randomUUID();
355
- const ownerFile = `owner-${token}.json`;
356
- try {
357
- mkdirSync(lock);
358
- } catch (error) {
359
- if (error.code !== "EEXIST") throw error;
360
- const files = readdirSync(lock);
361
- if (files.length !== 1 || !/^owner-[a-f0-9-]+\.json$/.test(files[0]))
362
- throw new Error(`Hub lifecycle lock has unknown ownership: ${lock}`);
363
- const previousPath = join(lock, files[0]);
364
- const previous = JSON.parse(readFileSync(previousPath, "utf8"));
365
- if (
366
- previous.hostname !== machine ||
367
- !Number.isSafeInteger(previous.pid) ||
368
- previous.pid <= 0 ||
369
- previous.token !== files[0].slice(6, -5) ||
370
- alive(previous.pid)
371
- )
372
- throw new Error(`Hub lifecycle operation is locked by PID ${previous.pid}: ${lock}`);
373
- // Remove only the observed unique owner file. Competing recovery cannot delete a new owner's file.
374
- unlinkSync(previousPath);
375
- rmdirSync(lock);
376
- mkdirSync(lock);
377
- }
378
- const path = join(lock, ownerFile);
379
- try {
380
- writeFileSync(path, JSON.stringify({ pid, hostname: machine, token, createdAt: new Date().toISOString() }), {
381
- flag: "wx",
382
- mode: 0o600,
383
- });
384
- } catch (error) {
385
- rmdirSync(lock);
386
- throw error;
387
- }
388
- return () => {
389
- unlinkSync(path);
390
- rmdirSync(lock);
391
- };
392
- }
393
-
394
- /** Cancel orchestration without killing a native service manager or the installed service. */
395
- export async function runHubCliEntry(argv = process.argv.slice(2), options = {}) {
396
- if (!["install", "start", "stop", "restart", "status", "uninstall"].includes(argv[0]))
397
- return runHubCli(argv, options);
398
- const controller = new AbortController();
399
- const abort = () => controller.abort(new Error("Hub CLI cancelled; installed configuration is retained"));
400
- // The runner uses IPC on Windows, where kill(SIGTERM) terminates the process immediately.
401
- // A queued message is handled after spawnSync returns and the orchestration yields.
402
- const onMessage = (message) => {
403
- if (message && typeof message === "object" && !Array.isArray(message) && message.type === "cancel-hub-operation")
404
- abort();
405
- };
406
- process.on("SIGTERM", abort);
407
- process.on("SIGINT", abort);
408
- process.on("message", onMessage);
409
- try {
410
- return await runHubCli(argv, { ...options, signal: controller.signal });
411
- } finally {
412
- process.off("SIGTERM", abort);
413
- process.off("SIGINT", abort);
414
- process.off("message", onMessage);
415
- }
416
- }
417
-
418
- function atomicWrite(path, content) {
419
- const temp = `${path}.${process.pid}.tmp`;
420
- try {
421
- writeFileSync(temp, content, { mode: 0o600, flag: "wx" });
422
- renameSync(temp, path);
423
- } finally {
424
- if (existsSync(temp)) unlinkSync(temp);
425
- }
426
- }
427
-
428
- export async function runHubCli(
429
- argv = process.argv.slice(2),
430
- {
431
- env = process.env,
432
- plan: suppliedPlan,
433
- run = runManager,
434
- inspect = spawnSync,
435
- log = console.log,
436
- foreground = runForeground,
437
- signal,
438
- } = {},
439
- ) {
440
- signal?.throwIfAborted();
441
- // Internal service entry uses an explicit saved environment, never ambient Hub overrides.
442
- if (argv[0] === "--service-config") {
443
- if (argv.length !== 2) throw new Error("Invalid service configuration arguments");
444
- const settings = JSON.parse(readFileSync(argv[1], "utf8"));
445
- validateSettings(settings);
446
- return foreground(settings);
447
- }
448
- const parsed = parseHubArgs(argv, env);
449
- if (parsed.help) return log(HUB_HELP);
450
- if (parsed.command === "foreground") return foreground(parsed.settings);
451
- const plan = suppliedPlan ?? hubServicePlan({ env });
452
- const command = parsed.command;
453
- if (command === "status") {
454
- const installed = existsSync(plan.config);
455
- const settings = installed ? JSON.parse(readFileSync(plan.config, "utf8")) : undefined;
456
- const health = settings ? await probeHub(settings, signal) : null;
457
- signal?.throwIfAborted();
458
- const result = {
459
- schemaVersion: 1,
460
- service: "pi-device-hub",
461
- installed,
462
- running: !!health,
463
- owned: !!health && health.instanceId === settings?.PI_DEVICE_HUB_INSTANCE_ID,
464
- instanceId: settings?.PI_DEVICE_HUB_INSTANCE_ID ?? null,
465
- host: settings?.PI_DEVICE_HUB_HOST ?? null,
466
- port: settings ? Number(settings.PI_DEVICE_HUB_PORT) : null,
467
- publicUrl: settings?.PI_DEVICE_HUB_PUBLIC_URL ?? null,
468
- allowRegistration: settings ? settings.PI_DEVICE_HUB_ALLOW_REGISTRATION === "1" : null,
469
- registration: {
470
- configured: settings ? settings.PI_DEVICE_HUB_ALLOW_REGISTRATION === "1" : null,
471
- active: health?.allowRegistration ?? null,
472
- },
473
- dataDir: settings?.PI_DEVICE_HUB_DATA_DIR ?? null,
474
- configPath: plan.config,
475
- health,
476
- };
477
- log(parsed.json ? JSON.stringify(result) : JSON.stringify(result, null, 2));
478
- return result;
479
- }
480
- mkdirSync(plan.root, { recursive: true, mode: 0o700 });
481
- const releaseLock = acquireHubLock(plan.root);
482
- try {
483
- if (command === "install") {
484
- if (existsSync(plan.config) || existsSync(plan.file))
485
- throw new Error(
486
- `Hub service configuration already exists at ${plan.config}. Inspect with 'hub status --json'; recover with 'hub start' or 'hub restart'. To replace configuration, 'hub uninstall' first (data retained).`,
487
- );
488
- // A failed query is not proof of absence unless the native manager says so.
489
- assertServiceAbsent(plan, inspect);
490
- await yieldForCancellation(signal);
491
- await assertPortAvailable(parsed.settings);
492
- signal?.throwIfAborted();
493
- parsed.settings.PI_DEVICE_HUB_INSTANCE_ID = randomUUID();
494
- mkdirSync(resolve(plan.file, ".."), { recursive: true });
495
- atomicWrite(plan.config, `${JSON.stringify(parsed.settings, null, 2)}\n`);
496
- atomicWrite(
497
- plan.file,
498
- process.platform === "win32" ? Buffer.from(`\uFEFF${plan.content}`, "utf16le") : plan.content,
499
- );
500
- } else if (!existsSync(plan.config))
501
- throw new Error("Hub service is not installed. Run pi-web-ui hub install first.");
502
- signal?.throwIfAborted();
503
- if (parsed.registration !== undefined) {
504
- const settings = JSON.parse(readFileSync(plan.config, "utf8"));
505
- validateSettings(settings);
506
- settings.PI_DEVICE_HUB_ALLOW_REGISTRATION = parsed.registration;
507
- atomicWrite(plan.config, `${JSON.stringify(settings, null, 2)}\n`);
508
- }
509
- let serviceMissing = false;
510
- if (command === "uninstall") {
511
- try {
512
- assertServiceAbsent(plan, inspect);
513
- serviceMissing = true;
514
- } catch {
515
- /* Native commands must still report failures for an existing or inaccessible service. */
516
- }
517
- }
518
- // Absence checks are native phases too: drain pending IPC before another phase.
519
- await yieldForCancellation(signal);
520
- for (const args of serviceMissing ? [] : plan.commands[command]) {
521
- signal?.throwIfAborted();
522
- const output = run(plan.manager, args);
523
- // Timer callbacks can precede IPC polling. Cross a full poll/check cycle before
524
- // starting another native command, including when entered outside an I/O callback.
525
- await yieldForCancellation(signal);
526
- signal?.throwIfAborted();
527
- if (output) log(output);
528
- }
529
- if (command === "uninstall") {
530
- if (existsSync(plan.file)) unlinkSync(plan.file);
531
- if (plan.manager === "systemctl") run(plan.manager, ["--user", "daemon-reload"]);
532
- unlinkSync(plan.config);
533
- }
534
- if (["install", "start", "restart"].includes(command)) {
535
- const settings = JSON.parse(readFileSync(plan.config, "utf8"));
536
- await waitForHub(settings, signal);
537
- }
538
- log(`Hub ${command} completed.${command === "uninstall" ? " Account/device data retained." : ""}`);
539
- } catch (error) {
540
- throw new Error(
541
- `${signal?.aborted ? signal.reason?.message || "Hub CLI cancelled" : error.message}\nHub configuration: ${plan.config}. Inspect: hub status --json; retry: hub restart. Windows scheduled tasks require Task Scheduler permissions; access denied means installation failed. Configuration is retained; hub uninstall removes it while retaining Hub data.`,
542
- );
543
- } finally {
544
- releaseLock();
545
- }
546
- }
547
-
548
- async function runForeground(settings) {
549
- const { startDeviceHub } = await import("../dist/server/device-center/main.js");
550
- const hub = await startDeviceHub(settings);
551
- hub.app.get("/health", (_req, res) => {
552
- res.setHeader("Cache-Control", "no-store");
553
- res.json({
554
- schemaVersion: 1,
555
- service: "pi-device-hub",
556
- status: "ok",
557
- instanceId: settings.PI_DEVICE_HUB_INSTANCE_ID ?? null,
558
- publicUrl: settings.PI_DEVICE_HUB_PUBLIC_URL,
559
- port: Number(settings.PI_DEVICE_HUB_PORT),
560
- allowRegistration: settings.PI_DEVICE_HUB_ALLOW_REGISTRATION === "1",
561
- });
562
- });
563
- let closing = false;
564
- for (const signal of ["SIGINT", "SIGTERM"])
565
- process.on(signal, () => {
566
- if (closing) return;
567
- closing = true;
568
- void hub.close().then(
569
- () => process.exit(0),
570
- (error) => {
571
- console.error(error.message);
572
- process.exit(1);
573
- },
574
- );
575
- });
576
- return hub;
577
- }
1
+ /** Standalone Hub lifecycle. Only Node built-ins; never imports the main CLI or agent SDK. */
2
+ import { spawnSync } from "node:child_process";
3
+ import { randomUUID } from "node:crypto";
4
+ import { createServer } from "node:net";
5
+ import { request } from "node:http";
6
+ import {
7
+ mkdirSync,
8
+ readFileSync,
9
+ writeFileSync,
10
+ renameSync,
11
+ unlinkSync,
12
+ existsSync,
13
+ rmdirSync,
14
+ readdirSync,
15
+ } from "node:fs";
16
+ import { homedir, hostname } from "node:os";
17
+ import { setTimeout as delay, setImmediate as yieldImmediate } from "node:timers/promises";
18
+ import { join, resolve } from "node:path";
19
+ import { fileURLToPath } from "node:url";
20
+
21
+ export const HUB_HELP = `Usage: pi-web-ui hub [install|start|stop|restart|status|uninstall] [options]
22
+ Without a command, run in the foreground (Ctrl+C to stop).
23
+ Options: --host HOST --port PORT --public-url URL --data-dir PATH
24
+ --allow-registration[=true|false] --help
25
+ install saves configuration, enables login autostart and starts the Hub.
26
+ Other lifecycle commands use the saved configuration; status accepts --json.
27
+ Close registration after the first account: hub restart --allow-registration=false
28
+ Only that saved setting changes; all other settings are retained.
29
+ Registration is disabled unless explicitly enabled. Foreground mode also accepts PI_DEVICE_HUB_*.
30
+ Service: systemd --user (Linux), launchd user agent (macOS), logon scheduled task (Windows).
31
+ Linux boot without login requires an administrator to enable linger for your user.
32
+ uninstall stops and removes the service; Hub account/device data is retained.`;
33
+ const ENTRY = fileURLToPath(new URL("./pi-device-hub.mjs", import.meta.url));
34
+ const LABEL = "com.xingshuyin.pi-device-hub";
35
+ const TASK = "pi-device-hub";
36
+ const UNIT = "pi-device-hub.service";
37
+ const flags = { "--host": "HOST", "--port": "PORT", "--public-url": "PUBLIC_URL", "--data-dir": "DATA_DIR" };
38
+ const optionalEnv = ["DEVICE_DOMAIN", "PATH_ACCESS", "PORTAL_PORTS"];
39
+
40
+ export function parseHubArgs(argv, env = process.env) {
41
+ const args = [...argv];
42
+ const command = args[0] && !args[0].startsWith("-") ? args.shift() : "foreground";
43
+ if (!["foreground", "install", "start", "stop", "restart", "status", "uninstall"].includes(command))
44
+ throw new Error(`Unknown Hub command: ${command}`);
45
+ const values = {};
46
+ if (command === "status" && args.length === 1 && args[0] === "--json") return { command, json: true };
47
+ if (command === "restart" && args.length === 1 && /^--allow-registration=(true|false)$/.test(args[0]))
48
+ return { command, registration: args[0].endsWith("=true") ? "1" : "0" };
49
+ for (let i = 0; i < args.length; i++) {
50
+ const [key, ...rest] = args[i].split("=");
51
+ if (key === "--help" || key === "-h") return { command, help: true };
52
+ if (!["foreground", "install"].includes(command)) throw new Error(`${command} accepts no options`);
53
+ if (key === "--allow-registration") {
54
+ const value = rest.length ? rest.join("=") : "true";
55
+ if (!["true", "false"].includes(value)) throw new Error("--allow-registration expects true or false");
56
+ values.ALLOW_REGISTRATION = value === "true" ? "1" : "0";
57
+ continue;
58
+ }
59
+ if (!flags[key]) throw new Error(`Unknown Hub option: ${key}`);
60
+ const value = rest.length ? rest.join("=") : args[++i];
61
+ if (!value || value.startsWith("--") || /[\x00-\x1f]/.test(value)) throw new Error(`Invalid value for ${key}`);
62
+ values[flags[key]] = value;
63
+ }
64
+ if (!["foreground", "install"].includes(command)) return { command };
65
+ const settings = {};
66
+ for (const key of [...Object.values(flags), ...optionalEnv]) {
67
+ const value = values[key] ?? env[`PI_DEVICE_HUB_${key}`];
68
+ if (value !== undefined) settings[`PI_DEVICE_HUB_${key}`] = value;
69
+ }
70
+ settings.PI_DEVICE_HUB_HOST ??= "127.0.0.1";
71
+ settings.PI_DEVICE_HUB_PORT ??= "8790";
72
+ settings.PI_DEVICE_HUB_DATA_DIR = resolve(settings.PI_DEVICE_HUB_DATA_DIR ?? join(homedir(), ".pi-device-hub"));
73
+ // Installing must not inherit an accidentally enabled registration environment variable.
74
+ settings.PI_DEVICE_HUB_ALLOW_REGISTRATION =
75
+ values.ALLOW_REGISTRATION ?? (command === "foreground" && env.PI_DEVICE_HUB_ALLOW_REGISTRATION === "1" ? "1" : "0");
76
+ validateSettings(settings);
77
+ return { command, settings };
78
+ }
79
+
80
+ function validateSettings(settings) {
81
+ for (const value of Object.values(settings))
82
+ if (typeof value !== "string" || /[\x00-\x1f]/.test(value)) throw new Error("Invalid Hub configuration value");
83
+ if (!settings.PI_DEVICE_HUB_HOST) throw new Error("Hub host must not be empty");
84
+ const port = settings.PI_DEVICE_HUB_PORT;
85
+ if (!/^\d+$/.test(port) || Number(port) < 1 || Number(port) > 65535) throw new Error("Invalid Hub port");
86
+ if (!settings.PI_DEVICE_HUB_PUBLIC_URL) throw new Error("--public-url (or PI_DEVICE_HUB_PUBLIC_URL) is required");
87
+ const url = new URL(settings.PI_DEVICE_HUB_PUBLIC_URL);
88
+ if (
89
+ !["http:", "https:"].includes(url.protocol) ||
90
+ url.origin !== settings.PI_DEVICE_HUB_PUBLIC_URL ||
91
+ url.username ||
92
+ url["pass" + "word"]
93
+ )
94
+ throw new Error("--public-url (or PI_DEVICE_HUB_PUBLIC_URL) must be a canonical HTTP(S) root origin");
95
+ }
96
+
97
+ const xml = (s) =>
98
+ String(s).replace(/[<>&"']/g, (c) => ({ "<": "&lt;", ">": "&gt;", "&": "&amp;", '"': "&quot;", "'": "&apos;" })[c]);
99
+ // CommandLineToArgvW quoting, not shell quoting. Every argument is passed directly to node.exe.
100
+ export const windowsArg = (s) =>
101
+ `"${String(s)
102
+ .replace(/(\\*)"/g, '$1$1\\"')
103
+ .replace(/(\\+)$/g, "$1$1")}"`;
104
+ const systemdArg = (s) =>
105
+ `"${String(s)
106
+ .replace(/\\/g, "\\\\")
107
+ .replace(/"/g, '\\"')
108
+ .replace(/%/g, "%%")
109
+ .replace(/\$/g, () => "$$")}"`;
110
+
111
+ export function hubServicePlan({
112
+ platform = process.platform,
113
+ home = homedir(),
114
+ env = process.env,
115
+ node = process.execPath,
116
+ entry = ENTRY,
117
+ uid = process.getuid?.(),
118
+ user = env.USERNAME,
119
+ } = {}) {
120
+ const root =
121
+ platform === "win32"
122
+ ? join(env.APPDATA || join(home, "AppData", "Roaming"), "pi-device-hub-cli")
123
+ : join(home, ".config", "pi-device-hub-cli");
124
+ const config = join(root, "service.json");
125
+ const args = [entry, "--service-config", config];
126
+ if (platform === "linux")
127
+ return {
128
+ root,
129
+ config,
130
+ file: join(home, ".config", "systemd", "user", UNIT),
131
+ content: `[Unit]\nDescription=pi device Hub\nAfter=network.target\n\n[Service]\nExecStart=${[node, ...args].map(systemdArg).join(" ")}\nRestart=on-failure\nRestartSec=5\n\n[Install]\nWantedBy=default.target\n`,
132
+ manager: "systemctl",
133
+ commands: {
134
+ install: [
135
+ ["--user", "daemon-reload"],
136
+ ["--user", "enable", "--now", UNIT],
137
+ ],
138
+ start: [["--user", "start", UNIT]],
139
+ stop: [["--user", "stop", UNIT]],
140
+ restart: [["--user", "restart", UNIT]],
141
+ status: [["--user", "show", UNIT, "--property=ActiveState,SubState,UnitFileState"]],
142
+ uninstall: [["--user", "disable", "--now", UNIT]],
143
+ },
144
+ };
145
+ if (platform === "darwin") {
146
+ const file = join(home, "Library", "LaunchAgents", `${LABEL}.plist`);
147
+ const target = `gui/${uid}/${LABEL}`;
148
+ return {
149
+ root,
150
+ config,
151
+ file,
152
+ content: `<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n<plist version="1.0"><dict><key>Label</key><string>${LABEL}</string><key>ProgramArguments</key><array>${[node, ...args].map((s) => `<string>${xml(s)}</string>`).join("")}</array><key>RunAtLoad</key><true/><key>KeepAlive</key><dict><key>SuccessfulExit</key><false/></dict><key>StandardOutPath</key><string>${xml(join(root, "stdout.log"))}</string><key>StandardErrorPath</key><string>${xml(join(root, "stderr.log"))}</string></dict></plist>\n`,
153
+ manager: "launchctl",
154
+ commands: {
155
+ install: [["bootstrap", `gui/${uid}`, file]],
156
+ start: [["bootstrap", `gui/${uid}`, file]],
157
+ stop: [["bootout", target]],
158
+ restart: [
159
+ ["bootout", target],
160
+ ["bootstrap", `gui/${uid}`, file],
161
+ ],
162
+ status: [["print", target]],
163
+ uninstall: [["bootout", target]],
164
+ },
165
+ };
166
+ }
167
+ if (platform === "win32") {
168
+ if (!user) throw new Error("Cannot determine Windows task user");
169
+ const identity = env.USERDOMAIN ? `${env.USERDOMAIN}\\${user}` : user;
170
+ return {
171
+ root,
172
+ config,
173
+ file: join(root, "task.xml"),
174
+ content: `<?xml version="1.0" encoding="UTF-16"?>\n<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task"><Triggers><LogonTrigger><Enabled>true</Enabled><UserId>${xml(identity)}</UserId></LogonTrigger></Triggers><Principals><Principal id="Author"><UserId>${xml(identity)}</UserId><LogonType>InteractiveToken</LogonType><RunLevel>LeastPrivilege</RunLevel></Principal></Principals><Settings><MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy><DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries><StopIfGoingOnBatteries>false</StopIfGoingOnBatteries><ExecutionTimeLimit>PT0S</ExecutionTimeLimit><RestartOnFailure><Interval>PT1M</Interval><Count>3</Count></RestartOnFailure></Settings><Actions Context="Author"><Exec><Command>${xml(node)}</Command><Arguments>${xml(args.map(windowsArg).join(" "))}</Arguments></Exec></Actions></Task>`,
175
+ manager: "schtasks.exe",
176
+ commands: {
177
+ install: [
178
+ ["/Create", "/TN", TASK, "/XML", join(root, "task.xml")],
179
+ ["/Run", "/TN", TASK],
180
+ ],
181
+ start: [["/Run", "/TN", TASK]],
182
+ stop: [["/End", "/TN", TASK]],
183
+ restart: [
184
+ ["/End", "/TN", TASK],
185
+ ["/Run", "/TN", TASK],
186
+ ],
187
+ status: [["/Query", "/TN", TASK, "/V", "/FO", "LIST"]],
188
+ uninstall: [
189
+ ["/End", "/TN", TASK],
190
+ ["/Delete", "/TN", TASK, "/F"],
191
+ ],
192
+ },
193
+ };
194
+ }
195
+ throw new Error(`Unsupported Hub service platform: ${platform}`);
196
+ }
197
+
198
+ // One budget per composite native phase, rather than a fresh timeout per subprocess.
199
+ // SIGKILL prevents a timed-out native command from extending the runner's 45s grace.
200
+ function nativePhase(inspect, now) {
201
+ const deadline = now() + 30000;
202
+ return (file, args) => {
203
+ const remaining = Math.floor(deadline - now());
204
+ if (remaining <= 0) throw new Error("Hub native operation exceeded its 30s deadline");
205
+ return inspect(file, args, { encoding: "utf8", windowsHide: true, timeout: remaining, killSignal: "SIGKILL" });
206
+ };
207
+ }
208
+
209
+ async function yieldForCancellation(signal) {
210
+ await yieldImmediate(undefined, { signal });
211
+ await yieldImmediate(undefined, { signal });
212
+ signal?.throwIfAborted();
213
+ }
214
+
215
+ export function assertServiceAbsent(plan, inspect = spawnSync, now = () => performance.now()) {
216
+ const native = nativePhase(inspect, now);
217
+ const result = native(
218
+ plan.manager,
219
+ plan.manager === "systemctl"
220
+ ? ["--user", "show", UNIT, "--property=LoadState", "--value"]
221
+ : plan.commands.status[0],
222
+ );
223
+ if (result.error) throw result.error;
224
+ if (plan.manager === "systemctl" && result.status === 0 && result.stdout.trim() === "not-found") return;
225
+ if (plan.manager === "launchctl" && result.status !== 0 && /Could not find service/i.test(result.stderr)) return;
226
+ if (plan.manager === "schtasks.exe") {
227
+ // Locale-independent absence check: query the scheduler COM API and accept only file-not-found.
228
+ const script = `$s=New-Object -ComObject Schedule.Service; $s.Connect(); try { $null=$s.GetFolder('\\').GetTask('${TASK}'); exit 0 } catch { if ($_.Exception.HResult -eq -2147024894) { exit 3 }; exit 4 }`;
229
+ const check = native("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", script]);
230
+ if (!check.error && check.status === 3) return;
231
+ }
232
+ throw new Error("Hub service already exists or service absence could not be verified. Refusing to overwrite.");
233
+ }
234
+
235
+ export function assertPortAvailable(settings) {
236
+ return new Promise((done, reject) => {
237
+ const server = createServer();
238
+ server.once("error", reject);
239
+ server.listen(
240
+ { host: settings.PI_DEVICE_HUB_HOST, port: Number(settings.PI_DEVICE_HUB_PORT), exclusive: true },
241
+ () => server.close((error) => (error ? reject(error) : done())),
242
+ );
243
+ });
244
+ }
245
+
246
+ export function probeHub(settings, signal) {
247
+ signal?.throwIfAborted();
248
+ return new Promise((done) => {
249
+ const host =
250
+ settings.PI_DEVICE_HUB_HOST === "::"
251
+ ? "::1"
252
+ : settings.PI_DEVICE_HUB_HOST === "0.0.0.0"
253
+ ? "127.0.0.1"
254
+ : settings.PI_DEVICE_HUB_HOST;
255
+ const req = request(
256
+ {
257
+ signal,
258
+ host,
259
+ port: Number(settings.PI_DEVICE_HUB_PORT),
260
+ path: "/health",
261
+ headers: { Host: new URL(settings.PI_DEVICE_HUB_PUBLIC_URL).host },
262
+ timeout: 1000,
263
+ },
264
+ (res) => {
265
+ let body = "";
266
+ res.on("data", (chunk) => {
267
+ body += chunk;
268
+ if (body.length > 8192) req.destroy();
269
+ });
270
+ res.on("error", () => done(null));
271
+ res.on("end", () => {
272
+ try {
273
+ const health = JSON.parse(body);
274
+ done(
275
+ res.statusCode === 200 && health.service === "pi-device-hub" && health.status === "ok" ? health : null,
276
+ );
277
+ } catch {
278
+ done(null);
279
+ }
280
+ });
281
+ },
282
+ );
283
+ req.on("timeout", () => req.destroy());
284
+ req.on("error", () => done(null));
285
+ req.end();
286
+ });
287
+ }
288
+
289
+ async function waitForHub(settings, signal) {
290
+ const deadline = Date.now() + 15000;
291
+ while (Date.now() < deadline) {
292
+ signal?.throwIfAborted();
293
+ const health = await probeHub(settings, signal);
294
+ signal?.throwIfAborted();
295
+ if (health) {
296
+ if (
297
+ health.instanceId !== settings.PI_DEVICE_HUB_INSTANCE_ID ||
298
+ health.allowRegistration !== (settings.PI_DEVICE_HUB_ALLOW_REGISTRATION === "1")
299
+ )
300
+ throw new Error("Hub health does not match the saved instance/configuration");
301
+ return;
302
+ }
303
+ await delay(250, undefined, { signal });
304
+ }
305
+ throw new Error("Hub did not become healthy within 15 seconds; service configuration retained for diagnosis");
306
+ }
307
+
308
+ export function runManager(file, args, inspect = spawnSync, now = () => performance.now()) {
309
+ const native = nativePhase(inspect, now);
310
+ if (file === "launchctl" && ["bootout", "bootstrap"].includes(args[0])) {
311
+ const target = args[0] === "bootout" ? args[1] : `${args[1]}/${LABEL}`;
312
+ const state = native(file, ["print", target]);
313
+ if (state.error) throw state.error;
314
+ if (state.status === 0 && args[0] === "bootstrap") return "Hub is already loaded";
315
+ if (state.status !== 0) {
316
+ if (!/Could not find service/i.test(state.stderr))
317
+ throw new Error(state.stderr || "Could not inspect launchd job");
318
+ if (args[0] === "bootout") return "Hub is already stopped";
319
+ }
320
+ }
321
+ // Ending an already stopped task is successful; scheduler errors still propagate.
322
+ if (file === "schtasks.exe" && args[0] === "/End") {
323
+ file = "powershell.exe";
324
+ args = [
325
+ "-NoProfile",
326
+ "-NonInteractive",
327
+ "-Command",
328
+ `$ErrorActionPreference='Stop'; $s=New-Object -ComObject Schedule.Service; $s.Connect(); $t=$s.GetFolder('\\').GetTask('${TASK}'); if ($t.State -eq 4) { $t.Stop(0) }`,
329
+ ];
330
+ }
331
+ const result = native(file, args);
332
+ if (result.error || result.status !== 0)
333
+ throw new Error(
334
+ `${file} ${args.join(" ")}: ${result.error?.message || result.stderr || result.stdout || `exit ${result.status}`}`,
335
+ );
336
+ return result.stdout?.trim();
337
+ }
338
+ export function acquireHubLock(
339
+ root,
340
+ {
341
+ pid = process.pid,
342
+ machine = hostname(),
343
+ alive = (ownerPid) => {
344
+ try {
345
+ process.kill(ownerPid, 0);
346
+ return true;
347
+ } catch (error) {
348
+ return error.code !== "ESRCH";
349
+ }
350
+ },
351
+ } = {},
352
+ ) {
353
+ const lock = join(root, "lifecycle.lock");
354
+ const token = randomUUID();
355
+ const ownerFile = `owner-${token}.json`;
356
+ try {
357
+ mkdirSync(lock);
358
+ } catch (error) {
359
+ if (error.code !== "EEXIST") throw error;
360
+ const files = readdirSync(lock);
361
+ if (files.length !== 1 || !/^owner-[a-f0-9-]+\.json$/.test(files[0]))
362
+ throw new Error(`Hub lifecycle lock has unknown ownership: ${lock}`);
363
+ const previousPath = join(lock, files[0]);
364
+ const previous = JSON.parse(readFileSync(previousPath, "utf8"));
365
+ if (
366
+ previous.hostname !== machine ||
367
+ !Number.isSafeInteger(previous.pid) ||
368
+ previous.pid <= 0 ||
369
+ previous.token !== files[0].slice(6, -5) ||
370
+ alive(previous.pid)
371
+ )
372
+ throw new Error(`Hub lifecycle operation is locked by PID ${previous.pid}: ${lock}`);
373
+ // Remove only the observed unique owner file. Competing recovery cannot delete a new owner's file.
374
+ unlinkSync(previousPath);
375
+ rmdirSync(lock);
376
+ mkdirSync(lock);
377
+ }
378
+ const path = join(lock, ownerFile);
379
+ try {
380
+ writeFileSync(path, JSON.stringify({ pid, hostname: machine, token, createdAt: new Date().toISOString() }), {
381
+ flag: "wx",
382
+ mode: 0o600,
383
+ });
384
+ } catch (error) {
385
+ rmdirSync(lock);
386
+ throw error;
387
+ }
388
+ return () => {
389
+ unlinkSync(path);
390
+ rmdirSync(lock);
391
+ };
392
+ }
393
+
394
+ /** Cancel orchestration without killing a native service manager or the installed service. */
395
+ export async function runHubCliEntry(argv = process.argv.slice(2), options = {}) {
396
+ if (!["install", "start", "stop", "restart", "status", "uninstall"].includes(argv[0]))
397
+ return runHubCli(argv, options);
398
+ const controller = new AbortController();
399
+ const abort = () => controller.abort(new Error("Hub CLI cancelled; installed configuration is retained"));
400
+ // The runner uses IPC on Windows, where kill(SIGTERM) terminates the process immediately.
401
+ // A queued message is handled after spawnSync returns and the orchestration yields.
402
+ const onMessage = (message) => {
403
+ if (message && typeof message === "object" && !Array.isArray(message) && message.type === "cancel-hub-operation")
404
+ abort();
405
+ };
406
+ process.on("SIGTERM", abort);
407
+ process.on("SIGINT", abort);
408
+ process.on("message", onMessage);
409
+ try {
410
+ return await runHubCli(argv, { ...options, signal: controller.signal });
411
+ } finally {
412
+ process.off("SIGTERM", abort);
413
+ process.off("SIGINT", abort);
414
+ process.off("message", onMessage);
415
+ }
416
+ }
417
+
418
+ function atomicWrite(path, content) {
419
+ const temp = `${path}.${process.pid}.tmp`;
420
+ try {
421
+ writeFileSync(temp, content, { mode: 0o600, flag: "wx" });
422
+ renameSync(temp, path);
423
+ } finally {
424
+ if (existsSync(temp)) unlinkSync(temp);
425
+ }
426
+ }
427
+
428
+ export async function runHubCli(
429
+ argv = process.argv.slice(2),
430
+ {
431
+ env = process.env,
432
+ plan: suppliedPlan,
433
+ run = runManager,
434
+ inspect = spawnSync,
435
+ log = console.log,
436
+ foreground = runForeground,
437
+ signal,
438
+ } = {},
439
+ ) {
440
+ signal?.throwIfAborted();
441
+ // Internal service entry uses an explicit saved environment, never ambient Hub overrides.
442
+ if (argv[0] === "--service-config") {
443
+ if (argv.length !== 2) throw new Error("Invalid service configuration arguments");
444
+ const settings = JSON.parse(readFileSync(argv[1], "utf8"));
445
+ validateSettings(settings);
446
+ return foreground(settings);
447
+ }
448
+ const parsed = parseHubArgs(argv, env);
449
+ if (parsed.help) return log(HUB_HELP);
450
+ if (parsed.command === "foreground") return foreground(parsed.settings);
451
+ const plan = suppliedPlan ?? hubServicePlan({ env });
452
+ const command = parsed.command;
453
+ if (command === "status") {
454
+ const installed = existsSync(plan.config);
455
+ const settings = installed ? JSON.parse(readFileSync(plan.config, "utf8")) : undefined;
456
+ const health = settings ? await probeHub(settings, signal) : null;
457
+ signal?.throwIfAborted();
458
+ const result = {
459
+ schemaVersion: 1,
460
+ service: "pi-device-hub",
461
+ installed,
462
+ running: !!health,
463
+ owned: !!health && health.instanceId === settings?.PI_DEVICE_HUB_INSTANCE_ID,
464
+ instanceId: settings?.PI_DEVICE_HUB_INSTANCE_ID ?? null,
465
+ host: settings?.PI_DEVICE_HUB_HOST ?? null,
466
+ port: settings ? Number(settings.PI_DEVICE_HUB_PORT) : null,
467
+ publicUrl: settings?.PI_DEVICE_HUB_PUBLIC_URL ?? null,
468
+ allowRegistration: settings ? settings.PI_DEVICE_HUB_ALLOW_REGISTRATION === "1" : null,
469
+ registration: {
470
+ configured: settings ? settings.PI_DEVICE_HUB_ALLOW_REGISTRATION === "1" : null,
471
+ active: health?.allowRegistration ?? null,
472
+ },
473
+ dataDir: settings?.PI_DEVICE_HUB_DATA_DIR ?? null,
474
+ configPath: plan.config,
475
+ health,
476
+ };
477
+ log(parsed.json ? JSON.stringify(result) : JSON.stringify(result, null, 2));
478
+ return result;
479
+ }
480
+ mkdirSync(plan.root, { recursive: true, mode: 0o700 });
481
+ const releaseLock = acquireHubLock(plan.root);
482
+ try {
483
+ if (command === "install") {
484
+ if (existsSync(plan.config) || existsSync(plan.file))
485
+ throw new Error(
486
+ `Hub service configuration already exists at ${plan.config}. Inspect with 'hub status --json'; recover with 'hub start' or 'hub restart'. To replace configuration, 'hub uninstall' first (data retained).`,
487
+ );
488
+ // A failed query is not proof of absence unless the native manager says so.
489
+ assertServiceAbsent(plan, inspect);
490
+ await yieldForCancellation(signal);
491
+ await assertPortAvailable(parsed.settings);
492
+ signal?.throwIfAborted();
493
+ parsed.settings.PI_DEVICE_HUB_INSTANCE_ID = randomUUID();
494
+ mkdirSync(resolve(plan.file, ".."), { recursive: true });
495
+ atomicWrite(plan.config, `${JSON.stringify(parsed.settings, null, 2)}\n`);
496
+ atomicWrite(
497
+ plan.file,
498
+ process.platform === "win32" ? Buffer.from(`\uFEFF${plan.content}`, "utf16le") : plan.content,
499
+ );
500
+ } else if (!existsSync(plan.config))
501
+ throw new Error("Hub service is not installed. Run pi-web-ui hub install first.");
502
+ signal?.throwIfAborted();
503
+ if (parsed.registration !== undefined) {
504
+ const settings = JSON.parse(readFileSync(plan.config, "utf8"));
505
+ validateSettings(settings);
506
+ settings.PI_DEVICE_HUB_ALLOW_REGISTRATION = parsed.registration;
507
+ atomicWrite(plan.config, `${JSON.stringify(settings, null, 2)}\n`);
508
+ }
509
+ let serviceMissing = false;
510
+ if (command === "uninstall") {
511
+ try {
512
+ assertServiceAbsent(plan, inspect);
513
+ serviceMissing = true;
514
+ } catch {
515
+ /* Native commands must still report failures for an existing or inaccessible service. */
516
+ }
517
+ }
518
+ // Absence checks are native phases too: drain pending IPC before another phase.
519
+ await yieldForCancellation(signal);
520
+ for (const args of serviceMissing ? [] : plan.commands[command]) {
521
+ signal?.throwIfAborted();
522
+ const output = run(plan.manager, args);
523
+ // Timer callbacks can precede IPC polling. Cross a full poll/check cycle before
524
+ // starting another native command, including when entered outside an I/O callback.
525
+ await yieldForCancellation(signal);
526
+ signal?.throwIfAborted();
527
+ if (output) log(output);
528
+ }
529
+ if (command === "uninstall") {
530
+ if (existsSync(plan.file)) unlinkSync(plan.file);
531
+ if (plan.manager === "systemctl") run(plan.manager, ["--user", "daemon-reload"]);
532
+ unlinkSync(plan.config);
533
+ }
534
+ if (["install", "start", "restart"].includes(command)) {
535
+ const settings = JSON.parse(readFileSync(plan.config, "utf8"));
536
+ await waitForHub(settings, signal);
537
+ }
538
+ log(`Hub ${command} completed.${command === "uninstall" ? " Account/device data retained." : ""}`);
539
+ } catch (error) {
540
+ throw new Error(
541
+ `${signal?.aborted ? signal.reason?.message || "Hub CLI cancelled" : error.message}\nHub configuration: ${plan.config}. Inspect: hub status --json; retry: hub restart. Windows scheduled tasks require Task Scheduler permissions; access denied means installation failed. Configuration is retained; hub uninstall removes it while retaining Hub data.`,
542
+ );
543
+ } finally {
544
+ releaseLock();
545
+ }
546
+ }
547
+
548
+ async function runForeground(settings) {
549
+ const { startDeviceHub } = await import("../dist/server/device-center/main.js");
550
+ const hub = await startDeviceHub(settings);
551
+ hub.app.get("/health", (_req, res) => {
552
+ res.setHeader("Cache-Control", "no-store");
553
+ res.json({
554
+ schemaVersion: 1,
555
+ service: "pi-device-hub",
556
+ status: "ok",
557
+ instanceId: settings.PI_DEVICE_HUB_INSTANCE_ID ?? null,
558
+ publicUrl: settings.PI_DEVICE_HUB_PUBLIC_URL,
559
+ port: Number(settings.PI_DEVICE_HUB_PORT),
560
+ allowRegistration: settings.PI_DEVICE_HUB_ALLOW_REGISTRATION === "1",
561
+ });
562
+ });
563
+ let closing = false;
564
+ for (const signal of ["SIGINT", "SIGTERM"])
565
+ process.on(signal, () => {
566
+ if (closing) return;
567
+ closing = true;
568
+ void hub.close().then(
569
+ () => process.exit(0),
570
+ (error) => {
571
+ console.error(error.message);
572
+ process.exit(1);
573
+ },
574
+ );
575
+ });
576
+ return hub;
577
+ }