pi-web-ui 0.113.0 → 0.114.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (228) hide show
  1. package/CHANGELOG.md +69 -1
  2. package/README.md +117 -252
  3. package/README.zh-CN.md +145 -223
  4. package/README.zh-TW.md +145 -223
  5. package/bin/device-hub-cli.mjs +577 -0
  6. package/bin/pi-device-hub.mjs +9 -0
  7. package/bin/pi-web-ui.mjs +145 -20
  8. package/dist/gh-comment-781.md +5 -0
  9. package/dist/server/agent-service-daemon.js +102 -24
  10. package/dist/server/agent-service.js +2296 -1121
  11. package/dist/server/approval-rules.js +29 -3
  12. package/dist/server/ask-user-question-tool.js +8 -8
  13. package/dist/server/atomic-file.js +35 -14
  14. package/dist/server/attachment-store.js +71 -35
  15. package/dist/server/attachments.js +18 -8
  16. package/dist/server/canvas/canvas-agent-tool.js +65 -15
  17. package/dist/server/canvas/canvas-dispatch.js +61 -20
  18. package/dist/server/canvas/canvas-orchestrator.js +516 -199
  19. package/dist/server/canvas/canvas-scheduler.js +99 -0
  20. package/dist/server/canvas/canvas-store.js +107 -54
  21. package/dist/server/canvas/canvas-validation.js +131 -0
  22. package/dist/server/canvas/canvas-workspace.js +284 -0
  23. package/dist/server/client-id-utils.js +8 -0
  24. package/dist/server/client-state.js +104 -22
  25. package/dist/server/communicate-tool.js +76 -0
  26. package/dist/server/compact-context-tool.js +2 -3
  27. package/dist/server/compaction-instructions.js +75 -0
  28. package/dist/server/compaction-markers.js +7 -2
  29. package/dist/server/compaction-state.js +84 -0
  30. package/dist/server/composer-drafts.js +43 -40
  31. package/dist/server/context-evidence.js +346 -0
  32. package/dist/server/control-socket.js +6 -2
  33. package/dist/server/conversation-communication.js +368 -0
  34. package/dist/server/conversation-read-tool.js +3 -4
  35. package/dist/server/conversation-tool-names.js +14 -0
  36. package/dist/server/conversation-tool.js +57 -0
  37. package/dist/server/delegate-mode.js +17 -4
  38. package/dist/server/device-center/bot-catalog.js +88 -0
  39. package/dist/server/device-center/bot-execution.js +106 -0
  40. package/dist/server/device-center/bots.js +170 -0
  41. package/dist/server/device-center/collab-service.js +153 -0
  42. package/dist/server/device-center/collab-tool.js +184 -0
  43. package/dist/server/device-center/connector.js +332 -0
  44. package/dist/server/device-center/desktop-linux.js +372 -0
  45. package/dist/server/device-center/desktop-native.js +413 -0
  46. package/dist/server/device-center/desktop-page.js +232 -0
  47. package/dist/server/device-center/desktop-setup.js +30 -0
  48. package/dist/server/device-center/desktop.js +387 -0
  49. package/dist/server/device-center/device-portals.js +241 -0
  50. package/dist/server/device-center/execution-failure.js +70 -0
  51. package/dist/server/device-center/executor.js +371 -0
  52. package/dist/server/device-center/file-sync.js +493 -0
  53. package/dist/server/device-center/hub-auth.js +69 -0
  54. package/dist/server/device-center/hub-page.js +68 -0
  55. package/dist/server/device-center/hub-setup.js +214 -0
  56. package/dist/server/device-center/hub.js +829 -0
  57. package/dist/server/device-center/local-page.js +17 -0
  58. package/dist/server/device-center/local.js +476 -0
  59. package/dist/server/device-center/main.js +118 -0
  60. package/dist/server/device-center/native-desktop/macos.js +192 -0
  61. package/dist/server/device-center/native-desktop/windows.js +118 -0
  62. package/dist/server/device-center/path-portal.js +120 -0
  63. package/dist/server/device-center/relay.js +959 -0
  64. package/dist/server/device-center/runtime.js +253 -0
  65. package/dist/server/device-center/smoke-preview.js +3 -0
  66. package/dist/server/device-center/store.js +122 -0
  67. package/dist/server/device-center/task-error.js +14 -0
  68. package/dist/server/device-center/transfers.js +293 -0
  69. package/dist/server/device-center/workspaces.js +45 -0
  70. package/dist/server/dispatch-domain-handlers.js +83 -27
  71. package/dist/server/dsh/dsh-agent-service.js +277 -158
  72. package/dist/server/dsh/dsh-client.js +12 -2
  73. package/dist/server/durable/durable-agent-service.js +1 -1
  74. package/dist/server/evidence-tool-hooks.js +49 -0
  75. package/dist/server/file-save.js +95 -0
  76. package/dist/server/file-transfer-routes.js +97 -47
  77. package/dist/server/files-service.js +110 -34
  78. package/dist/server/goal-review-gate.js +16 -6
  79. package/dist/server/goal-service.js +54 -30
  80. package/dist/server/http-proxy.js +120 -0
  81. package/dist/server/index.js +236 -232
  82. package/dist/server/load-timing.js +31 -0
  83. package/dist/server/mcp-bridge.js +219 -94
  84. package/dist/server/mcp-hot-reload.js +31 -5
  85. package/dist/server/mcp-manager.js +192 -93
  86. package/dist/server/mcp-oauth-login.js +169 -0
  87. package/dist/server/mcp-oauth-ui.js +137 -0
  88. package/dist/server/mcp-oauth.js +395 -0
  89. package/dist/server/mcp-project-runtime.js +207 -0
  90. package/dist/server/message-window.js +74 -21
  91. package/dist/server/net-guard.js +122 -20
  92. package/dist/server/payload-limits.js +17 -0
  93. package/dist/server/pending-question.js +82 -0
  94. package/dist/server/plan-mode.js +338 -137
  95. package/dist/server/plugin-assets.js +8 -4
  96. package/dist/server/plugin-chat-attachments.js +48 -0
  97. package/dist/server/plugin-facilities.js +67 -220
  98. package/dist/server/plugin-installer.js +2 -1
  99. package/dist/server/plugin-removal.js +49 -0
  100. package/dist/server/plugin-secrets.js +179 -0
  101. package/dist/server/plugins.js +262 -92
  102. package/dist/server/preset-fields.js +49 -0
  103. package/dist/server/preset-plugin-dependencies.js +57 -0
  104. package/dist/server/preset-share.js +112 -72
  105. package/dist/server/protocol-version.js +1 -1
  106. package/dist/server/queue-modes.js +10 -0
  107. package/dist/server/remote-ssh-service.js +160 -67
  108. package/dist/server/request-context.js +164 -0
  109. package/dist/server/sandbox-data.js +655 -0
  110. package/dist/server/sandbox-engines.js +7 -0
  111. package/dist/server/sandbox-runtime-gate.js +41 -0
  112. package/dist/server/sandbox-service.js +139 -698
  113. package/dist/server/sandbox-tool.js +21 -4
  114. package/dist/server/scheduler-tasks.js +63 -48
  115. package/dist/server/serialize.js +48 -19
  116. package/dist/server/session-branch.js +25 -3
  117. package/dist/server/session-parser.js +28 -18
  118. package/dist/server/session-scan.js +130 -0
  119. package/dist/server/session-search.js +51 -37
  120. package/dist/server/settings-service.js +267 -111
  121. package/dist/server/setup-config.js +58 -0
  122. package/dist/server/skill-maintenance.js +112 -24
  123. package/dist/server/subagent-helpers.js +4 -1
  124. package/dist/server/subagent-notify.js +4 -1
  125. package/dist/server/subagent-security-gate.js +52 -11
  126. package/dist/server/subagent-task.js +27 -0
  127. package/dist/server/subagents.js +217 -46
  128. package/dist/server/tabs.js +9 -1
  129. package/dist/server/terminals.js +467 -363
  130. package/dist/server/tool-guards.js +42 -6
  131. package/dist/server/tool-manager.js +47 -20
  132. package/dist/server/tool-overrides.js +13 -11
  133. package/dist/server/tool-prompt-overrides.js +32 -2
  134. package/dist/server/tool-prompts.js +1 -1
  135. package/dist/server/turn-timing.js +11 -0
  136. package/dist/server/universal/session-store.js +48 -6
  137. package/dist/server/universal/universal-service.js +1 -1
  138. package/dist/server/universal/universal-session.js +334 -231
  139. package/dist/server/uploads.js +64 -5
  140. package/dist/server/webui-context.js +6 -6
  141. package/dist/server/worktree-service.js +32 -24
  142. package/dist/server/ws-pending-queue.js +73 -27
  143. package/dist/test-artifact.md +9 -0
  144. package/dist/test-preview-modal.md +11 -0
  145. package/dist/test-report.html +20 -0
  146. package/docs/device-center.md +142 -0
  147. package/docs/device-desktop.md +48 -0
  148. package/package.json +4 -1
  149. package/plugin-sdk/index.d.ts +45 -9
  150. package/plugin-sdk/ssh-host-trust.mjs +225 -0
  151. package/plugins/catalog.json +1 -1
  152. package/themes/aetheris.css +1 -107
  153. package/themes/ayu-light.css +5 -29
  154. package/themes/bases/flow-base.css +0 -6
  155. package/themes/bases/statusbar-flat-base.css +112 -0
  156. package/themes/bases/zhujian-base.css +1 -0
  157. package/themes/bases/zhupi-base.css +1 -0
  158. package/themes/catppuccin-latte.css +4 -27
  159. package/themes/catppuccin.css +4 -35
  160. package/themes/claude-code-dark.css +1 -0
  161. package/themes/codex.css +4 -28
  162. package/themes/cyberpunk.css +3 -61
  163. package/themes/dark-teal.css +0 -1
  164. package/themes/dazzle.css +3 -73
  165. package/themes/everforest-light.css +4 -27
  166. package/themes/geist.css +4 -28
  167. package/themes/gruvbox-light.css +4 -27
  168. package/themes/kanagawa-lotus.css +4 -27
  169. package/themes/md-preview.css +3 -213
  170. package/themes/mist.css +4 -24
  171. package/themes/nord.css +4 -35
  172. package/themes/one-dark.css +4 -37
  173. package/themes/paper.css +4 -16
  174. package/themes/rose-pine-dawn.css +4 -28
  175. package/themes/sakura.css +4 -24
  176. package/themes/solarized-light.css +4 -27
  177. package/themes/tokyo-night.css +3 -34
  178. package/themes/white.css +4 -26
  179. package/themes/zhujian-dark.css +1 -0
  180. package/themes/zhupi-dark.css +1 -0
  181. package/web/dist/.build-assets.json +1 -0
  182. package/web/dist/assets/BgTasksModal-CS7UNzcw.js +1 -0
  183. package/web/dist/assets/BgTasksModal-Dk-tp78W.js +1 -0
  184. package/web/dist/assets/CanvasStudio-BEJZE5BI.js +1579 -0
  185. package/web/dist/assets/CanvasStudio-CgUNHqos.js +1579 -0
  186. package/web/dist/assets/DeviceCenter-C8_CbxQ3.js +3 -0
  187. package/web/dist/assets/DeviceCenter-CVblvhNX.js +3 -0
  188. package/web/dist/assets/Dropdown-Oug0DDte.js +1 -0
  189. package/web/dist/assets/FilePreview-CvdX6nr6.js +2 -0
  190. package/web/dist/assets/FilePreview-kCZhfBAF.js +2 -0
  191. package/web/dist/assets/GlobalSearchModal-BLH63yYP.js +1 -0
  192. package/web/dist/assets/GlobalSearchModal-DAkvlvp6.js +1 -0
  193. package/web/dist/assets/GroupConversation-Cgo4xbpa.js +1 -0
  194. package/web/dist/assets/GroupConversation-DZ71jEi8.js +1 -0
  195. package/web/dist/assets/ModelConfigModal-BpWdFdQC.js +2 -0
  196. package/web/dist/assets/PiSetupModal-mkWPSxMj.js +1 -0
  197. package/web/dist/assets/ProviderOAuthControls-VK_jqXYS.js +1 -0
  198. package/web/dist/assets/SCMPanel-BP1TUT-V.js +2 -0
  199. package/web/dist/assets/SCMPanel-BscPm9kf.js +2 -0
  200. package/web/dist/assets/SettingsModal-C8UgMjVM.js +20 -0
  201. package/web/dist/assets/SettingsModal-VynB7jNb.js +20 -0
  202. package/web/dist/assets/TerminalPanel-D6cPRFei.js +3 -0
  203. package/web/dist/assets/TerminalPanel-DL20uKgU.js +3 -0
  204. package/web/dist/assets/TuiOverlayModal-Dst3BmT8.js +1 -0
  205. package/web/dist/assets/TuiOverlayModal-NCkpNtTp.js +1 -0
  206. package/web/dist/assets/UniversalPathPicker-CfQFc_c3.js +1 -0
  207. package/web/dist/assets/UniversalPathPicker-DwxwNcFw.js +1 -0
  208. package/web/dist/assets/app-globals-CnO6KlEM.js +325 -0
  209. package/web/dist/assets/desktop-DPyTy4M3.js +1 -0
  210. package/web/dist/assets/es-DWMIuDU2.js +2 -0
  211. package/web/dist/assets/index-CPgAH5q7.js +83 -0
  212. package/web/dist/assets/index-Cje8iugL.js +83 -0
  213. package/web/dist/assets/index-DnKeiDbj.css +1 -0
  214. package/web/dist/assets/markdown-BggnuQ4H.js +40 -0
  215. package/web/dist/assets/markdown-C8LL_u4z.css +1 -0
  216. package/web/dist/assets/math-1uRJCsA9.js +257 -0
  217. package/web/dist/assets/math-BorAY7qD.css +1 -0
  218. package/web/dist/assets/plugin-host-CqA4yW6w.js +1 -0
  219. package/web/dist/assets/shortcut-stack-hhrDyRBn.js +1 -0
  220. package/web/dist/assets/theme-BqdAjEjF.js +1 -0
  221. package/web/dist/assets/uuid-BzDIGCwP.js +1 -0
  222. package/web/dist/index.html +15 -9
  223. package/web/dist/sw.js +1 -1
  224. package/web/dist/assets/TerminalPanel-3wojLfLk.js +0 -3
  225. package/web/dist/assets/index-A8YXwnpZ.js +0 -2008
  226. package/web/dist/assets/index-BwL7qBh6.css +0 -1
  227. package/web/dist/assets/markdown-BJZlfvdP.js +0 -296
  228. package/web/dist/assets/markdown-DSNUiDzp.css +0 -1
@@ -0,0 +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
+ }
@@ -0,0 +1,9 @@
1
+ #!/usr/bin/env node
2
+ /** Standalone Hub CLI; no main CLI or agent SDK dependencies. */
3
+ import { runHubCliEntry } from "./device-hub-cli.mjs";
4
+ try {
5
+ await runHubCliEntry();
6
+ } catch (error) {
7
+ console.error(`[device-hub] ${error.message}`);
8
+ process.exitCode = 1;
9
+ }