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,332 @@
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
+ let bytes = 0;
210
+ res.on("data", (data) => {
211
+ bytes += data.length;
212
+ if (bytes > RELAY_LIMITS.body || !sendChunks(ws, "response_body", id, data)) {
213
+ res.destroy();
214
+ dispose(id);
215
+ sendFrame(ws, { type: "error", id });
216
+ }
217
+ });
218
+ res.on("end", () => {
219
+ sendFrame(ws, { type: "response_end", id });
220
+ dispose(id);
221
+ });
222
+ res.on("error", () => {
223
+ sendFrame(ws, { type: "error", id });
224
+ dispose(id);
225
+ });
226
+ });
227
+ stream.req = req;
228
+ req.on("error", () => {
229
+ if (streams.has(id)) {
230
+ sendFrame(ws, { type: "error", id });
231
+ dispose(id);
232
+ }
233
+ });
234
+ }
235
+ else {
236
+ const target = new URL(local);
237
+ target.protocol = local.protocol === "https:" ? "wss:" : "ws:";
238
+ const protocols = typeof frame.protocols === "string" ? frame.protocols.split(",").map((x) => x.trim()) : [];
239
+ const remote = new WebSocket(`${target.origin}${frame.path}`, protocols, {
240
+ headers: headers(frame.headers),
241
+ maxPayload: WS_MESSAGE_BYTES,
242
+ perMessageDeflate: false,
243
+ handshakeTimeout: 10_000,
244
+ });
245
+ stream.ws = remote;
246
+ remote.on("open", () => {
247
+ sendFrame(ws, { type: "ws_ready", id });
248
+ });
249
+ remote.on("message", (data, binary) => {
250
+ if (!messages.send(id, Buffer.from(data), binary))
251
+ remote.terminate();
252
+ });
253
+ remote.on("close", () => {
254
+ messages.discard(id);
255
+ sendFrame(ws, { type: "ws_close", id });
256
+ dispose(id);
257
+ });
258
+ remote.on("error", () => {
259
+ sendFrame(ws, { type: "error", id });
260
+ dispose(id);
261
+ });
262
+ }
263
+ return;
264
+ }
265
+ const stream = streams.get(id);
266
+ if (!stream)
267
+ return;
268
+ if (frame.type === "request_body") {
269
+ const data = decodeChunk(frame.data);
270
+ stream.bytes += data.length;
271
+ if (stream.req && stream.bytes <= RELAY_LIMITS.body)
272
+ stream.req.write(data);
273
+ if (stream.bytes > RELAY_LIMITS.body || !stream.req || stream.req.writableLength > RELAY_LIMITS.queue) {
274
+ sendFrame(ws, { type: "error", id });
275
+ dispose(id);
276
+ }
277
+ }
278
+ else if (frame.type === "request_end")
279
+ stream.req?.end();
280
+ else if (frame.type === "ws_chunk" || frame.type === "ws_end") {
281
+ if (!stream.ws)
282
+ throw new Error("Missing WS stream");
283
+ messages.receive(frame, stream.ws);
284
+ }
285
+ else
286
+ throw new Error("Unknown frame");
287
+ }
288
+ catch {
289
+ ws.terminate();
290
+ }
291
+ });
292
+ ws.on("error", () => ws.terminate());
293
+ ws.on("close", () => {
294
+ rpc.close();
295
+ messages.close();
296
+ if (socket !== ws)
297
+ return;
298
+ socket = undefined;
299
+ stopTasks();
300
+ for (const id of streams.keys())
301
+ dispose(id);
302
+ if (!closed) {
303
+ const delay = Math.min(30_000, 500 * 2 ** Math.min(attempts++, 6)) + Math.floor(Math.random() * 250);
304
+ retry = setTimeout(connect, delay);
305
+ retry.unref();
306
+ }
307
+ });
308
+ }
309
+ const runningTasks = new Set();
310
+ const heartbeat = setInterval(() => {
311
+ if (socket?.readyState === WebSocket.OPEN) {
312
+ if (Date.now() - lastPong > 45_000)
313
+ socket.terminate();
314
+ else
315
+ socket.ping();
316
+ }
317
+ }, 15_000);
318
+ heartbeat.unref();
319
+ connect();
320
+ return {
321
+ isOnline: () => socket?.readyState === WebSocket.OPEN,
322
+ close() {
323
+ closed = true;
324
+ stopTasks();
325
+ clearInterval(heartbeat);
326
+ clearTimeout(retry);
327
+ socket?.terminate();
328
+ for (const id of streams.keys())
329
+ dispose(id);
330
+ },
331
+ };
332
+ }