pi-web-ui 0.113.1 → 0.114.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (280) hide show
  1. package/CHANGELOG.md +71 -1
  2. package/README.md +187 -316
  3. package/README.zh-CN.md +227 -299
  4. package/README.zh-TW.md +227 -299
  5. package/bin/device-hub-cli.mjs +577 -0
  6. package/bin/frp-manager.mjs +1573 -1573
  7. package/bin/pi-device-hub.mjs +9 -0
  8. package/bin/pi-web-ui.mjs +4081 -4041
  9. package/deploy/nginx-subpath.conf +100 -100
  10. package/deploy/pi-web-ui.service +36 -36
  11. package/dist/server/agent-service-daemon.js +102 -24
  12. package/dist/server/agent-service.js +2419 -1174
  13. package/dist/server/approval-rules.js +29 -3
  14. package/dist/server/ask-user-question-tool.js +8 -8
  15. package/dist/server/atomic-file.js +35 -14
  16. package/dist/server/attachment-store.js +71 -35
  17. package/dist/server/attachments.js +69 -13
  18. package/dist/server/canvas/canvas-agent-tool.js +68 -18
  19. package/dist/server/canvas/canvas-cards.js +1 -1
  20. package/dist/server/canvas/canvas-dispatch.js +61 -20
  21. package/dist/server/canvas/canvas-orchestrator.js +519 -202
  22. package/dist/server/canvas/canvas-scheduled-task.js +45 -0
  23. package/dist/server/canvas/canvas-scheduler.js +99 -0
  24. package/dist/server/canvas/canvas-store.js +107 -54
  25. package/dist/server/canvas/canvas-validation.js +131 -0
  26. package/dist/server/canvas/canvas-workspace.js +284 -0
  27. package/dist/server/client-id-utils.js +8 -0
  28. package/dist/server/client-state.js +110 -24
  29. package/dist/server/communicate-tool.js +76 -0
  30. package/dist/server/compact-context-tool.js +2 -3
  31. package/dist/server/compaction-instructions.js +75 -0
  32. package/dist/server/compaction-markers.js +7 -2
  33. package/dist/server/compaction-state.js +84 -0
  34. package/dist/server/composer-drafts.js +43 -40
  35. package/dist/server/context-evidence.js +346 -0
  36. package/dist/server/conversation-communication.js +368 -0
  37. package/dist/server/conversation-read-tool.js +3 -4
  38. package/dist/server/conversation-tool-names.js +14 -0
  39. package/dist/server/conversation-tool.js +57 -0
  40. package/dist/server/delegate-mode.js +17 -4
  41. package/dist/server/device-center/bot-catalog.js +88 -0
  42. package/dist/server/device-center/bot-execution.js +106 -0
  43. package/dist/server/device-center/bots.js +170 -0
  44. package/dist/server/device-center/collab-service.js +153 -0
  45. package/dist/server/device-center/collab-tool.js +184 -0
  46. package/dist/server/device-center/connector.js +351 -0
  47. package/dist/server/device-center/desktop-linux.js +372 -0
  48. package/dist/server/device-center/desktop-native.js +413 -0
  49. package/dist/server/device-center/desktop-page.js +232 -0
  50. package/dist/server/device-center/desktop-setup.js +30 -0
  51. package/dist/server/device-center/desktop.js +387 -0
  52. package/dist/server/device-center/device-portals.js +241 -0
  53. package/dist/server/device-center/execution-failure.js +70 -0
  54. package/dist/server/device-center/executor.js +371 -0
  55. package/dist/server/device-center/file-sync.js +493 -0
  56. package/dist/server/device-center/hub-auth.js +69 -0
  57. package/dist/server/device-center/hub-page.js +68 -0
  58. package/dist/server/device-center/hub-setup.js +214 -0
  59. package/dist/server/device-center/hub.js +830 -0
  60. package/dist/server/device-center/local-hub.js +92 -0
  61. package/dist/server/device-center/local.js +529 -0
  62. package/dist/server/device-center/main.js +118 -0
  63. package/dist/server/device-center/native-desktop/macos.js +192 -0
  64. package/dist/server/device-center/native-desktop/windows.js +118 -0
  65. package/dist/server/device-center/path-portal.js +120 -0
  66. package/dist/server/device-center/relay.js +996 -0
  67. package/dist/server/device-center/runtime.js +253 -0
  68. package/dist/server/device-center/store.js +122 -0
  69. package/dist/server/device-center/task-error.js +14 -0
  70. package/dist/server/device-center/transfers.js +293 -0
  71. package/dist/server/device-center/workspaces.js +45 -0
  72. package/dist/server/dispatch-domain-handlers.js +84 -27
  73. package/dist/server/dsh/dsh-agent-service.js +282 -159
  74. package/dist/server/dsh/dsh-client.js +12 -2
  75. package/dist/server/dsh/runtime/cordis.yml +1 -1
  76. package/dist/server/dsh/runtime/custom-prompt.mjs +33 -33
  77. package/dist/server/dsh/runtime/goal-rpc.mjs +1309 -1309
  78. package/dist/server/dsh/runtime/launcher.mjs +235 -235
  79. package/dist/server/dsh/runtime/override.patch.yml +89 -89
  80. package/dist/server/dsh/runtime/runtime-root.mjs +405 -405
  81. package/dist/server/durable/durable-agent-service.js +1 -1
  82. package/dist/server/engine-probe.js +36 -6
  83. package/dist/server/eval-tool.js +135 -135
  84. package/dist/server/evidence-tool-hooks.js +49 -0
  85. package/dist/server/file-save.js +95 -0
  86. package/dist/server/file-transfer-routes.js +97 -47
  87. package/dist/server/files-service.js +38 -26
  88. package/dist/server/global-loader.js +40 -2
  89. package/dist/server/goal-review-gate.js +16 -6
  90. package/dist/server/goal-service.js +54 -30
  91. package/dist/server/http-proxy.js +120 -0
  92. package/dist/server/index.js +285 -255
  93. package/dist/server/load-timing.js +31 -0
  94. package/dist/server/mcp-bridge.js +219 -94
  95. package/dist/server/mcp-hot-reload.js +31 -5
  96. package/dist/server/mcp-manager.js +192 -93
  97. package/dist/server/mcp-oauth-login.js +169 -0
  98. package/dist/server/mcp-oauth-ui.js +137 -0
  99. package/dist/server/mcp-oauth.js +395 -0
  100. package/dist/server/mcp-project-runtime.js +207 -0
  101. package/dist/server/message-window.js +74 -21
  102. package/dist/server/net-guard.js +122 -20
  103. package/dist/server/patch-bash-process.js +125 -0
  104. package/dist/server/patch-tool.js +9 -9
  105. package/dist/server/patch-turn-end-boundary.js +3 -3
  106. package/dist/server/payload-limits.js +17 -0
  107. package/dist/server/pending-question.js +82 -0
  108. package/dist/server/persona-chain.js +8 -8
  109. package/dist/server/plan-mode.js +338 -137
  110. package/dist/server/plugin-assets.js +8 -4
  111. package/dist/server/plugin-chat-attachments.js +48 -0
  112. package/dist/server/plugin-facilities.js +67 -220
  113. package/dist/server/plugin-installer.js +2 -1
  114. package/dist/server/plugin-removal.js +49 -0
  115. package/dist/server/plugin-secrets.js +179 -0
  116. package/dist/server/plugins.js +288 -94
  117. package/dist/server/preset-fields.js +56 -0
  118. package/dist/server/preset-plugin-dependencies.js +57 -0
  119. package/dist/server/preset-share.js +113 -72
  120. package/dist/server/prompt-templates.js +106 -0
  121. package/dist/server/protocol-version.js +1 -1
  122. package/dist/server/queue-modes.js +10 -0
  123. package/dist/server/remote-ssh-service.js +199 -106
  124. package/dist/server/request-context.js +164 -0
  125. package/dist/server/resolve-global-sdk.js +2 -0
  126. package/dist/server/sandbox-data.js +655 -0
  127. package/dist/server/sandbox-engines.js +7 -0
  128. package/dist/server/sandbox-runtime-gate.js +41 -0
  129. package/dist/server/sandbox-service.js +139 -698
  130. package/dist/server/sandbox-tool.js +21 -4
  131. package/dist/server/schedule-agent-tool.js +39 -21
  132. package/dist/server/scheduler-tasks.js +106 -55
  133. package/dist/server/scm-commitmsg.js +10 -10
  134. package/dist/server/serialize.js +48 -19
  135. package/dist/server/session-branch.js +25 -3
  136. package/dist/server/session-parser.js +28 -18
  137. package/dist/server/session-scan.js +130 -0
  138. package/dist/server/session-search.js +51 -37
  139. package/dist/server/settings-service.js +273 -111
  140. package/dist/server/setup-config.js +58 -0
  141. package/dist/server/setup-page.js +620 -620
  142. package/dist/server/skill-maintenance.js +112 -24
  143. package/dist/server/subagent-helpers.js +4 -1
  144. package/dist/server/subagent-notify.js +4 -1
  145. package/dist/server/subagent-security-gate.js +52 -11
  146. package/dist/server/subagent-task.js +27 -0
  147. package/dist/server/subagents.js +217 -46
  148. package/dist/server/tabs.js +9 -1
  149. package/dist/server/terminals.js +467 -363
  150. package/dist/server/text-quote.js +9 -0
  151. package/dist/server/tool-guards.js +42 -6
  152. package/dist/server/tool-manager.js +48 -20
  153. package/dist/server/tool-overrides.js +13 -11
  154. package/dist/server/tool-prompt-overrides.js +32 -2
  155. package/dist/server/tool-prompts.js +1 -1
  156. package/dist/server/turn-timing.js +11 -0
  157. package/dist/server/universal/drivers/claude-code.js +5 -0
  158. package/dist/server/universal/drivers/codex.js +336 -0
  159. package/dist/server/universal/index.js +1 -0
  160. package/dist/server/universal/session-store.js +48 -6
  161. package/dist/server/universal/universal-attachments.js +24 -1
  162. package/dist/server/universal/universal-service.js +1 -1
  163. package/dist/server/universal/universal-session.js +357 -231
  164. package/dist/server/uploads.js +64 -5
  165. package/dist/server/vision-bridge.js +18 -18
  166. package/dist/server/worktree-service.js +32 -24
  167. package/dist/server/ws-pending-queue.js +73 -27
  168. package/docs/device-center.md +148 -0
  169. package/docs/device-desktop.md +48 -0
  170. package/docs/dsh-engine.md +493 -493
  171. package/extensions/webui.ts +335 -335
  172. package/package.json +5 -2
  173. package/plugin-sdk/README.md +174 -174
  174. package/plugin-sdk/client-utils.mjs +279 -279
  175. package/plugin-sdk/import-check.mjs +210 -210
  176. package/plugin-sdk/index.d.ts +698 -676
  177. package/plugin-sdk/index.mjs +696 -696
  178. package/plugin-sdk/package.json +13 -13
  179. package/plugin-sdk/ssh-host-trust.mjs +225 -0
  180. package/plugins/catalog.json +11 -1
  181. package/themes/aetheris.css +501 -607
  182. package/themes/ayu-light.css +116 -140
  183. package/themes/bases/flow-base.css +1357 -1363
  184. package/themes/bases/obsidian-base.css +895 -895
  185. package/themes/bases/statusbar-flat-base.css +112 -0
  186. package/themes/bases/zhujian-base.css +688 -687
  187. package/themes/bases/zhupi-base.css +660 -659
  188. package/themes/catppuccin-latte.css +119 -142
  189. package/themes/catppuccin.css +116 -147
  190. package/themes/claude-code-dark.css +147 -146
  191. package/themes/codex.css +114 -138
  192. package/themes/cyberpunk.css +50 -108
  193. package/themes/dark-teal.css +264 -265
  194. package/themes/dazzle.css +38 -108
  195. package/themes/everforest-light.css +115 -138
  196. package/themes/flow-light.css +164 -164
  197. package/themes/flow.css +161 -161
  198. package/themes/geist.css +114 -138
  199. package/themes/gruvbox-light.css +115 -138
  200. package/themes/kanagawa-lotus.css +115 -138
  201. package/themes/md-preview.css +24 -234
  202. package/themes/mist.css +166 -186
  203. package/themes/nord.css +107 -138
  204. package/themes/one-dark.css +106 -139
  205. package/themes/paper.css +174 -186
  206. package/themes/rose-pine-dawn.css +114 -138
  207. package/themes/sakura.css +166 -186
  208. package/themes/solarized-light.css +114 -137
  209. package/themes/tokyo-night.css +115 -146
  210. package/themes/translucent.css +85 -85
  211. package/themes/transparent.css +116 -116
  212. package/themes/vs-code-dark.css +147 -147
  213. package/themes/wallpaper-flow.css +382 -382
  214. package/themes/wallpaper-obsidian.css +74 -74
  215. package/themes/white.css +164 -186
  216. package/themes/zhujian-dark.css +115 -114
  217. package/themes/zhujian.css +114 -114
  218. package/themes/zhupi-dark.css +115 -114
  219. package/themes/zhupi.css +114 -114
  220. package/web/dist/.build-assets.json +1 -0
  221. package/web/dist/assets/BgTasksModal-BcXJ20RO.js +1 -0
  222. package/web/dist/assets/BgTasksModal-DjQmiKnE.js +1 -0
  223. package/web/dist/assets/CanvasStudio-PI9pid0Y.js +1579 -0
  224. package/web/dist/assets/CanvasStudio-nf5-HxLM.js +1579 -0
  225. package/web/dist/assets/DeviceCenter-CYttJw2a.js +3 -0
  226. package/web/dist/assets/DeviceCenter-DPe4sz74.js +3 -0
  227. package/web/dist/assets/DeviceGroups-D2rogxEN.js +1 -0
  228. package/web/dist/assets/Dropdown-ZLS04O8p.js +1 -0
  229. package/web/dist/assets/FilePreview-C9Ut4Lq6.js +2 -0
  230. package/web/dist/assets/FilePreview-CvK3ZzX5.js +2 -0
  231. package/web/dist/assets/GlobalSearchModal-C5e-OCw2.js +1 -0
  232. package/web/dist/assets/GlobalSearchModal-H7pFK2UC.js +1 -0
  233. package/web/dist/assets/GroupConversation-C2wNM0dQ.js +1 -0
  234. package/web/dist/assets/GroupConversation-ChN3TWQK.js +1 -0
  235. package/web/dist/assets/ModelConfigModal-DDZccDYt.js +2 -0
  236. package/web/dist/assets/PiSetupModal-DHbqfx8T.js +1 -0
  237. package/web/dist/assets/ProviderOAuthControls-C-MK36Dk.js +1 -0
  238. package/web/dist/assets/SCMPanel-buTGziDB.js +2 -0
  239. package/web/dist/assets/SCMPanel-kx-SCL2s.js +2 -0
  240. package/web/dist/assets/SettingsModal-BsUF8jqr.js +20 -0
  241. package/web/dist/assets/SettingsModal-D357Ky7P.js +20 -0
  242. package/web/dist/assets/TerminalPanel-BBuM_Sez.js +3 -0
  243. package/web/dist/assets/TerminalPanel-D6x6xz8Q.js +3 -0
  244. package/web/dist/assets/TuiOverlayModal-CdbGV3Za.js +1 -0
  245. package/web/dist/assets/TuiOverlayModal-d6x9u25n.js +1 -0
  246. package/web/dist/assets/app-globals-DcyO0UPi.js +1 -0
  247. package/web/dist/assets/desktop-YguLbrX1.js +1 -0
  248. package/web/dist/assets/es-DWMIuDU2.js +2 -0
  249. package/web/dist/assets/fi-DaSO0Q-m.js +325 -0
  250. package/web/dist/assets/index-BPvpea8t.js +85 -0
  251. package/web/dist/assets/index-D6u8xH0o.js +85 -0
  252. package/web/dist/assets/index-DDZMv6LO.css +1 -0
  253. package/web/dist/assets/markdown-BggnuQ4H.js +40 -0
  254. package/web/dist/assets/markdown-C8LL_u4z.css +1 -0
  255. package/web/dist/assets/math-1uRJCsA9.js +257 -0
  256. package/web/dist/assets/math-BorAY7qD.css +1 -0
  257. package/web/dist/assets/plugin-host-BRBg6zmQ.js +1 -0
  258. package/web/dist/assets/shortcut-stack-hhrDyRBn.js +1 -0
  259. package/web/dist/assets/theme-DDl-Oy1b.js +1 -0
  260. package/web/dist/assets/uuid-BzDIGCwP.js +1 -0
  261. package/web/dist/index.html +42 -35
  262. package/web/dist/sw.js +179 -179
  263. package/web/public/sw.js +179 -179
  264. package/dist/gh-comment-781.md +0 -5
  265. package/dist/server/durable/durable-capabilities.js +0 -11
  266. package/dist/server/markers/builtins/services.js +0 -123
  267. package/dist/server/markers/builtins/todo.js +0 -189
  268. package/dist/server/markers-list-tool.js +0 -34
  269. package/dist/server/orchestrator.js +0 -109
  270. package/dist/server/system-prompt-soul.js +0 -41
  271. package/dist/server/univer-service.js +0 -448
  272. package/dist/server/universal/drivers/dsh-driver.js +0 -379
  273. package/dist/test-artifact.md +0 -9
  274. package/dist/test-preview-modal.md +0 -11
  275. package/dist/test-report.html +0 -20
  276. package/web/dist/assets/TerminalPanel-Ci55JtJL.js +0 -3
  277. package/web/dist/assets/index-ByiO9f-N.js +0 -2008
  278. package/web/dist/assets/index-ycGLh4a4.css +0 -1
  279. package/web/dist/assets/markdown-BJZlfvdP.js +0 -296
  280. package/web/dist/assets/markdown-DSNUiDzp.css +0 -1
@@ -0,0 +1,351 @@
1
+ import http, {} from "node:http";
2
+ import https from "node:https";
3
+ import { WebSocket } from "ws";
4
+ import { deviceTaskFailure } from "./task-error.js";
5
+ import { checkedUrl, createCommandChannel, createWsMessageChannel, WS_MESSAGE_BYTES, cleanHeaders, decodeChunk, loopback, parseFrame, RELAY_LIMITS, safePath, sendChunks, sendFrame, } from "./relay.js";
6
+ export function createDeviceConnector(options) {
7
+ const hub = checkedUrl(options.hubUrl);
8
+ const local = new URL(options.localOrigin);
9
+ if (!["localhost", "127.0.0.1", "[::1]"].includes(local.hostname) ||
10
+ !["http:", "https:"].includes(local.protocol) ||
11
+ local.username ||
12
+ local[("pass" + "word")] ||
13
+ local.pathname !== "/" ||
14
+ local.search ||
15
+ local.hash)
16
+ throw new Error("localOrigin must be a fixed loopback origin");
17
+ if (!/^[a-z0-9][a-z0-9-]{0,62}$/.test(options.deviceId) ||
18
+ !options.credential ||
19
+ /[\r\n]/.test(options.credential) ||
20
+ (options.localAuthToken && /[\r\n]/.test(options.localAuthToken)))
21
+ throw new Error("Invalid device credentials");
22
+ const endpoint = new URL("/device-connect", hub);
23
+ endpoint.protocol = hub.protocol === "https:" || hub.protocol === "wss:" ? "wss:" : "ws:";
24
+ endpoint.searchParams.set("deviceId", options.deviceId);
25
+ let closed = false;
26
+ let tasksDisabled = false;
27
+ const taskControllers = new Set();
28
+ function stopTasks() {
29
+ if (tasksDisabled)
30
+ return;
31
+ tasksDisabled = true;
32
+ for (const controller of taskControllers)
33
+ controller.abort();
34
+ taskControllers.clear();
35
+ try {
36
+ options.onDisconnect?.();
37
+ }
38
+ catch { }
39
+ }
40
+ let socket;
41
+ let retry;
42
+ let attempts = 0;
43
+ let lastPong = Date.now();
44
+ const streams = new Map();
45
+ function dispose(id) {
46
+ const stream = streams.get(id);
47
+ if (stream) {
48
+ streams.delete(id);
49
+ clearTimeout(stream.timer);
50
+ stream.req?.destroy();
51
+ stream.ws?.terminate();
52
+ }
53
+ }
54
+ function headers(value) {
55
+ const result = cleanHeaders((value && typeof value === "object" ? value : {}));
56
+ result.host = local.host;
57
+ result.origin = local.origin;
58
+ if (options.localAuthToken) {
59
+ result.authorization = `Bearer ${options.localAuthToken}`;
60
+ result.cookie = `pi_web_token=${encodeURIComponent(options.localAuthToken)}`;
61
+ }
62
+ return result;
63
+ }
64
+ function location(value) {
65
+ try {
66
+ const url = new URL(value, local);
67
+ if (options.localAuthToken &&
68
+ (value.includes(options.localAuthToken) || value.includes(encodeURIComponent(options.localAuthToken))))
69
+ return undefined;
70
+ if (url.origin === local.origin)
71
+ return url.pathname + url.search + url.hash;
72
+ const decoded = decodeURIComponent(url.href);
73
+ if (/localhost|127\.0\.0\.1|\[::1\]/i.test(decoded))
74
+ return undefined;
75
+ if (url.protocol === "https:" &&
76
+ !loopback(url.hostname) &&
77
+ !url.username &&
78
+ !url[("pass" + "word")] &&
79
+ (!options.localAuthToken || !value.includes(options.localAuthToken)))
80
+ return url.href;
81
+ }
82
+ catch { }
83
+ return undefined;
84
+ }
85
+ function connect() {
86
+ if (closed)
87
+ return;
88
+ const ws = new WebSocket(endpoint, {
89
+ headers: { authorization: `Bearer ${options.credential}` },
90
+ maxPayload: RELAY_LIMITS.frame,
91
+ perMessageDeflate: false,
92
+ handshakeTimeout: 10_000,
93
+ });
94
+ socket = ws;
95
+ const rpc = createCommandChannel(ws, options.onCommand);
96
+ const messages = createWsMessageChannel(ws);
97
+ ws.on("open", () => {
98
+ if (socket !== ws || closed) {
99
+ ws.terminate();
100
+ return;
101
+ }
102
+ attempts = 0;
103
+ tasksDisabled = false;
104
+ runningTasks.clear();
105
+ lastPong = Date.now();
106
+ void Promise.resolve()
107
+ .then(() => options.onConnect?.())
108
+ .catch(() => ws.close(1011, "Bot sync failed"));
109
+ });
110
+ ws.on("pong", () => {
111
+ lastPong = Date.now();
112
+ });
113
+ ws.on("message", (raw) => {
114
+ if (socket !== ws || closed)
115
+ return;
116
+ try {
117
+ const frame = parseFrame(Buffer.from(raw));
118
+ if (rpc.handle(frame))
119
+ return;
120
+ if (frame.type === "task") {
121
+ if (tasksDisabled)
122
+ throw new Error("Task executor disconnected");
123
+ const task = frame.task;
124
+ if (!task ||
125
+ typeof task.id !== "string" ||
126
+ typeof task.attemptId !== "string" ||
127
+ typeof task.botId !== "string" ||
128
+ !task.botId ||
129
+ !Number.isSafeInteger(task.botRevision) ||
130
+ task.botRevision < 1 ||
131
+ task.deviceId !== options.deviceId ||
132
+ runningTasks.has(task.id) ||
133
+ runningTasks.size >= RELAY_LIMITS.streams)
134
+ throw new Error("Invalid task");
135
+ runningTasks.add(task.id);
136
+ const controller = new AbortController();
137
+ taskControllers.add(controller);
138
+ const emit = (status, report) => {
139
+ if (socket === ws && !closed)
140
+ sendFrame(ws, {
141
+ type: "task_event",
142
+ taskId: task.id,
143
+ botId: task.botId,
144
+ attemptId: task.attemptId,
145
+ status,
146
+ ...(report ? { report: report.slice(0, 16_000) } : {}),
147
+ });
148
+ };
149
+ emit("running");
150
+ Promise.resolve()
151
+ .then(() => {
152
+ if (!options.onTask)
153
+ throw new Error("Task handler unavailable");
154
+ if (controller.signal.aborted)
155
+ throw new Error("Task cancelled");
156
+ return options.onTask(task, controller.signal);
157
+ })
158
+ .then((result) => emit("completed", typeof result === "string" ? result : undefined), (error) => emit("failed", deviceTaskFailure(error)))
159
+ .finally(() => {
160
+ if (socket === ws)
161
+ runningTasks.delete(task.id);
162
+ taskControllers.delete(controller);
163
+ });
164
+ return;
165
+ }
166
+ if (typeof frame.id !== "string" || frame.id.length > 128)
167
+ throw new Error("Invalid stream");
168
+ const id = frame.id;
169
+ if (frame.type === "cancel" || frame.type === "ws_close") {
170
+ messages.discard(id);
171
+ dispose(id);
172
+ return;
173
+ }
174
+ if (frame.type === "request" || frame.type === "ws_open") {
175
+ if (streams.has(id) ||
176
+ streams.size >= RELAY_LIMITS.streams ||
177
+ !safePath(frame.path, frame.type === "ws_open" ? "WS" : String(frame.method)))
178
+ throw new Error("Invalid request");
179
+ const timer = setTimeout(() => {
180
+ dispose(id);
181
+ sendFrame(ws, { type: "error", id });
182
+ }, 30 * 60_000);
183
+ timer.unref();
184
+ const stream = {
185
+ bytes: 0,
186
+ timer,
187
+ };
188
+ streams.set(id, stream);
189
+ if (frame.type === "request") {
190
+ if (typeof frame.method !== "string" || !/^(GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS)$/.test(frame.method))
191
+ throw new Error("Invalid method");
192
+ const req = (local.protocol === "https:" ? https : http).request({
193
+ hostname: local.hostname.replace(/^\[|\]$/g, ""),
194
+ port: local.port || undefined,
195
+ protocol: local.protocol,
196
+ path: frame.path,
197
+ method: frame.method,
198
+ headers: headers(frame.headers),
199
+ }, (res) => {
200
+ const responseHeaders = cleanHeaders(res.headers);
201
+ if (res.headers.location) {
202
+ const target = location(res.headers.location);
203
+ if (target)
204
+ responseHeaders.location = target;
205
+ else
206
+ delete responseHeaders.location;
207
+ }
208
+ sendFrame(ws, { type: "response", id, status: res.statusCode, headers: responseHeaders });
209
+ void (async () => {
210
+ let bytes = 0;
211
+ try {
212
+ // Pull only as fast as the relay socket drains, instead of aborting bursts.
213
+ for await (const data of res) {
214
+ const chunk = Buffer.from(data);
215
+ bytes += chunk.length;
216
+ if (bytes > RELAY_LIMITS.body)
217
+ throw new Error("Response too large");
218
+ for (let offset = 0; offset < chunk.length; offset += RELAY_LIMITS.chunk) {
219
+ while (ws.bufferedAmount > RELAY_LIMITS.queue / 2) {
220
+ if (!streams.has(id) || ws.readyState !== WebSocket.OPEN)
221
+ throw new Error("Cancelled");
222
+ await new Promise((resolve) => setTimeout(resolve, 5));
223
+ }
224
+ if (!streams.has(id) || ws.readyState !== WebSocket.OPEN)
225
+ throw new Error("Cancelled");
226
+ await new Promise((resolve, reject) => {
227
+ ws.send(JSON.stringify({
228
+ type: "response_body",
229
+ id,
230
+ data: chunk.subarray(offset, offset + RELAY_LIMITS.chunk).toString("base64"),
231
+ }), (error) => (error ? reject(error) : resolve()));
232
+ });
233
+ }
234
+ }
235
+ sendFrame(ws, { type: "response_end", id });
236
+ }
237
+ catch {
238
+ res.destroy();
239
+ sendFrame(ws, { type: "error", id });
240
+ }
241
+ finally {
242
+ dispose(id);
243
+ }
244
+ })();
245
+ });
246
+ stream.req = req;
247
+ req.on("error", () => {
248
+ if (streams.has(id)) {
249
+ sendFrame(ws, { type: "error", id });
250
+ dispose(id);
251
+ }
252
+ });
253
+ }
254
+ else {
255
+ const target = new URL(local);
256
+ target.protocol = local.protocol === "https:" ? "wss:" : "ws:";
257
+ const protocols = typeof frame.protocols === "string" ? frame.protocols.split(",").map((x) => x.trim()) : [];
258
+ const remote = new WebSocket(`${target.origin}${frame.path}`, protocols, {
259
+ headers: headers(frame.headers),
260
+ maxPayload: WS_MESSAGE_BYTES,
261
+ perMessageDeflate: false,
262
+ handshakeTimeout: 10_000,
263
+ });
264
+ stream.ws = remote;
265
+ remote.on("open", () => {
266
+ sendFrame(ws, { type: "ws_ready", id });
267
+ });
268
+ remote.on("message", (data, binary) => {
269
+ if (!messages.send(id, Buffer.from(data), binary))
270
+ remote.terminate();
271
+ });
272
+ remote.on("close", () => {
273
+ messages.discard(id);
274
+ sendFrame(ws, { type: "ws_close", id });
275
+ dispose(id);
276
+ });
277
+ remote.on("error", () => {
278
+ sendFrame(ws, { type: "error", id });
279
+ dispose(id);
280
+ });
281
+ }
282
+ return;
283
+ }
284
+ const stream = streams.get(id);
285
+ if (!stream)
286
+ return;
287
+ if (frame.type === "request_body") {
288
+ const data = decodeChunk(frame.data);
289
+ stream.bytes += data.length;
290
+ if (stream.req && stream.bytes <= RELAY_LIMITS.body)
291
+ stream.req.write(data);
292
+ if (stream.bytes > RELAY_LIMITS.body || !stream.req || stream.req.writableLength > RELAY_LIMITS.queue) {
293
+ sendFrame(ws, { type: "error", id });
294
+ dispose(id);
295
+ }
296
+ }
297
+ else if (frame.type === "request_end")
298
+ stream.req?.end();
299
+ else if (frame.type === "ws_chunk" || frame.type === "ws_end") {
300
+ if (!stream.ws)
301
+ throw new Error("Missing WS stream");
302
+ messages.receive(frame, stream.ws);
303
+ }
304
+ else
305
+ throw new Error("Unknown frame");
306
+ }
307
+ catch {
308
+ ws.terminate();
309
+ }
310
+ });
311
+ ws.on("error", () => ws.terminate());
312
+ ws.on("close", () => {
313
+ rpc.close();
314
+ messages.close();
315
+ if (socket !== ws)
316
+ return;
317
+ socket = undefined;
318
+ stopTasks();
319
+ for (const id of streams.keys())
320
+ dispose(id);
321
+ if (!closed) {
322
+ const delay = Math.min(30_000, 500 * 2 ** Math.min(attempts++, 6)) + Math.floor(Math.random() * 250);
323
+ retry = setTimeout(connect, delay);
324
+ retry.unref();
325
+ }
326
+ });
327
+ }
328
+ const runningTasks = new Set();
329
+ const heartbeat = setInterval(() => {
330
+ if (socket?.readyState === WebSocket.OPEN) {
331
+ if (Date.now() - lastPong > 45_000)
332
+ socket.terminate();
333
+ else
334
+ socket.ping();
335
+ }
336
+ }, 15_000);
337
+ heartbeat.unref();
338
+ connect();
339
+ return {
340
+ isOnline: () => socket?.readyState === WebSocket.OPEN,
341
+ close() {
342
+ closed = true;
343
+ stopTasks();
344
+ clearInterval(heartbeat);
345
+ clearTimeout(retry);
346
+ socket?.terminate();
347
+ for (const id of streams.keys())
348
+ dispose(id);
349
+ },
350
+ };
351
+ }