pi-web-ui 0.114.2 → 0.115.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 (195) hide show
  1. package/CHANGELOG.md +55 -1
  2. package/bin/pi-web-ui.mjs +69 -7
  3. package/dist/server/agent-service-daemon.js +440 -32
  4. package/dist/server/agent-service.js +878 -383
  5. package/dist/server/canvas/canvas-dispatch.js +13 -1
  6. package/dist/server/client-state.js +25 -0
  7. package/dist/server/communicate-tool.js +2 -0
  8. package/dist/server/context-usage.js +105 -0
  9. package/dist/server/conversation-communication.js +14 -0
  10. package/dist/server/conversation-identity.js +27 -0
  11. package/dist/server/device-center/approval-summary.js +31 -0
  12. package/dist/server/device-center/bot-catalog.js +21 -7
  13. package/dist/server/device-center/bot-execution.js +72 -9
  14. package/dist/server/device-center/bot-presets.js +46 -0
  15. package/dist/server/device-center/collab-service.js +328 -10
  16. package/dist/server/device-center/collab-tool.js +738 -12
  17. package/dist/server/device-center/connector.js +359 -23
  18. package/dist/server/device-center/desktop-page.js +22 -16
  19. package/dist/server/device-center/device-integration.js +595 -0
  20. package/dist/server/device-center/execution-guides.js +32 -0
  21. package/dist/server/device-center/execution-instructions.js +19 -0
  22. package/dist/server/device-center/execution-settings.js +100 -0
  23. package/dist/server/device-center/execution-system-prompt.js +38 -0
  24. package/dist/server/device-center/execution-workspace.js +20 -0
  25. package/dist/server/device-center/executor.js +389 -40
  26. package/dist/server/device-center/file-sync-paths.js +171 -0
  27. package/dist/server/device-center/file-sync.js +180 -91
  28. package/dist/server/device-center/group-context-delta.js +37 -0
  29. package/dist/server/device-center/group-context-message.js +208 -0
  30. package/dist/server/device-center/group-context.js +109 -0
  31. package/dist/server/device-center/group-events.js +136 -0
  32. package/dist/server/device-center/group-plan-guard.js +138 -0
  33. package/dist/server/device-center/hub-conversations.js +178 -0
  34. package/dist/server/device-center/hub-deliveries.js +277 -0
  35. package/dist/server/device-center/hub-integration.js +451 -0
  36. package/dist/server/device-center/hub.js +1544 -80
  37. package/dist/server/device-center/human-interaction.js +232 -0
  38. package/dist/server/device-center/integration-errors.js +25 -0
  39. package/dist/server/device-center/local-hub.js +18 -0
  40. package/dist/server/device-center/local.js +356 -40
  41. package/dist/server/device-center/main.js +11 -1
  42. package/dist/server/device-center/path-portal.js +11 -3
  43. package/dist/server/device-center/relay.js +364 -35
  44. package/dist/server/device-center/report-metadata.js +66 -0
  45. package/dist/server/device-center/report-upload.js +63 -0
  46. package/dist/server/device-center/runtime.js +549 -41
  47. package/dist/server/device-center/store.js +66 -3
  48. package/dist/server/device-center/task-context-budget.js +161 -0
  49. package/dist/server/device-center/task-journal.js +385 -0
  50. package/dist/server/device-center/task-plan.js +33 -0
  51. package/dist/server/device-center/task-progress.js +141 -0
  52. package/dist/server/device-center/task-recovery.js +452 -0
  53. package/dist/server/device-center/task-report-outbox.js +216 -0
  54. package/dist/server/device-center/task-report.js +384 -0
  55. package/dist/server/device-center/task-scheduler.js +400 -0
  56. package/dist/server/device-center/task-state.js +333 -0
  57. package/dist/server/device-center/transfer-stream.js +1006 -0
  58. package/dist/server/device-center/transfers.js +815 -8
  59. package/dist/server/dispatch-domain-handlers.js +21 -3
  60. package/dist/server/dsh/dsh-agent-service.js +6 -0
  61. package/dist/server/goal-service.js +10 -5
  62. package/dist/server/index.js +89 -13
  63. package/dist/server/message-deletion.js +40 -0
  64. package/dist/server/message-window.js +9 -0
  65. package/dist/server/patch-executable-lookup.js +396 -0
  66. package/dist/server/payload-limits.js +2 -0
  67. package/dist/server/plugin-llm.js +100 -9
  68. package/dist/server/plugins.js +1 -0
  69. package/dist/server/preset-fields.js +24 -0
  70. package/dist/server/preset-share.js +2 -0
  71. package/dist/server/prompt-base-store.js +85 -0
  72. package/dist/server/prompt-composer.js +5 -2
  73. package/dist/server/protocol-version.js +1 -1
  74. package/dist/server/protocol.js +2 -2
  75. package/dist/server/remote-ssh-service.js +22 -9
  76. package/dist/server/resolve-global-sdk.js +2 -0
  77. package/dist/server/session-search.js +1 -1
  78. package/dist/server/settings-service.js +90 -39
  79. package/dist/server/skill-content-filler.js +29 -8
  80. package/dist/server/skill-tool.js +12 -3
  81. package/dist/server/subagent-helpers.js +4 -1
  82. package/dist/server/subagents.js +50 -36
  83. package/dist/server/tool-host-factories.js +1 -0
  84. package/dist/server/universal/universal-session.js +5 -0
  85. package/dist/server/webui-context.js +25 -5
  86. package/docs/README.md +94 -0
  87. package/docs/device-center.md +100 -12
  88. package/docs/dsh-engine.md +10 -10
  89. package/extensions/webui.ts +43 -1
  90. package/package.json +1 -1
  91. package/themes/aetheris.css +5 -0
  92. package/themes/ayu-light.css +6 -0
  93. package/themes/bases/flow-base.css +68 -68
  94. package/themes/catppuccin-latte.css +6 -0
  95. package/themes/catppuccin.css +6 -0
  96. package/themes/claude-code-dark.css +5 -0
  97. package/themes/codex.css +6 -0
  98. package/themes/cyberpunk.css +6 -0
  99. package/themes/dark-teal.css +6 -1
  100. package/themes/dazzle.css +6 -0
  101. package/themes/everforest-light.css +6 -0
  102. package/themes/flow-light.css +8 -1
  103. package/themes/flow.css +6 -1
  104. package/themes/geist.css +6 -0
  105. package/themes/gruvbox-light.css +6 -0
  106. package/themes/kanagawa-lotus.css +6 -0
  107. package/themes/md-preview.css +6 -0
  108. package/themes/mist.css +6 -0
  109. package/themes/nord.css +6 -0
  110. package/themes/one-dark.css +6 -0
  111. package/themes/paper.css +6 -0
  112. package/themes/rose-pine-dawn.css +6 -0
  113. package/themes/sakura.css +6 -0
  114. package/themes/solarized-light.css +6 -0
  115. package/themes/tokyo-night.css +6 -0
  116. package/themes/translucent.css +6 -0
  117. package/themes/transparent.css +6 -0
  118. package/themes/vs-code-dark.css +5 -0
  119. package/themes/wallpaper-flow.css +5 -1
  120. package/themes/wallpaper-obsidian.css +6 -0
  121. package/themes/white.css +6 -0
  122. package/themes/zhujian-dark.css +6 -1
  123. package/themes/zhujian.css +6 -1
  124. package/themes/zhupi-dark.css +6 -1
  125. package/themes/zhupi.css +6 -1
  126. package/web/dist/.build-assets.json +1 -1
  127. package/web/dist/assets/BgTasksModal-BYzPgmoq.js +1 -0
  128. package/web/dist/assets/BgTasksModal-ni0VTmAQ.js +1 -0
  129. package/web/dist/assets/{CanvasStudio-B3W6b_rA.js → CanvasStudio-BCUeEf25.js} +3 -3
  130. package/web/dist/assets/{CanvasStudio-Csv1Sj1-.js → CanvasStudio-DNmDNBod.js} +3 -3
  131. package/web/dist/assets/DeviceCenter-BcBhRgL6.js +3 -0
  132. package/web/dist/assets/DeviceCenter-CmL5FZmt.js +3 -0
  133. package/web/dist/assets/DeviceGroups-CLdpdnI7.js +1 -0
  134. package/web/dist/assets/DeviceGroups-CgBaDPrD.js +1 -0
  135. package/web/dist/assets/Dropdown-CGXD0DfT.js +1 -0
  136. package/web/dist/assets/FilePreview-B8iqnBjy.js +2 -0
  137. package/web/dist/assets/FilePreview-BqviZKCN.js +2 -0
  138. package/web/dist/assets/GlobalSearchModal-mevF-ySi.js +1 -0
  139. package/web/dist/assets/GlobalSearchModal-qL99FN_F.js +1 -0
  140. package/web/dist/assets/GroupConversation-B88Yy-lt.js +3 -0
  141. package/web/dist/assets/GroupConversation-BwP5NVOE.js +3 -0
  142. package/web/dist/assets/HintTip-LHwkS2jV.js +1 -0
  143. package/web/dist/assets/ModelConfigModal-Do3Fe3jH.js +2 -0
  144. package/web/dist/assets/PiSetupModal-DE5-gEtI.js +1 -0
  145. package/web/dist/assets/ProviderOAuthControls-6UMARucA.js +1 -0
  146. package/web/dist/assets/SCMPanel-Hi6QqC1Q.js +2 -0
  147. package/web/dist/assets/SCMPanel-ezY_ZtCu.js +2 -0
  148. package/web/dist/assets/SettingsModal-6HgeEsJ8.js +20 -0
  149. package/web/dist/assets/SettingsModal-CF-7MwqS.js +20 -0
  150. package/web/dist/assets/TerminalPanel-CTp_BZ4S.js +3 -0
  151. package/web/dist/assets/TerminalPanel-CkYxC-Gh.js +3 -0
  152. package/web/dist/assets/TuiOverlayModal-1cRLP8IF.js +1 -0
  153. package/web/dist/assets/TuiOverlayModal-2xlptqWX.js +1 -0
  154. package/web/dist/assets/app-globals-DZNa9v8u.js +325 -0
  155. package/web/dist/assets/canvas-client-Bye9nSFO.js +1 -0
  156. package/web/dist/assets/{desktop-YguLbrX1.js → desktop-kjBoE3Nu.js} +1 -1
  157. package/web/dist/assets/group-view-state-CGCzYF8k.js +1 -0
  158. package/web/dist/assets/index-CsFs_HMb.css +1 -0
  159. package/web/dist/assets/index-DHeeHS_l.js +85 -0
  160. package/web/dist/assets/index-DTZch8uz.js +85 -0
  161. package/web/dist/assets/plugin-host-C8mNgghx.js +1 -0
  162. package/web/dist/assets/remote-ssh-client-CeP3CLUW.js +1 -0
  163. package/web/dist/assets/theme-BXGpyTMh.js +1 -0
  164. package/web/dist/index.html +10 -9
  165. package/web/dist/sw.js +1 -1
  166. package/web/dist/assets/BgTasksModal-BIlQ89vr.js +0 -1
  167. package/web/dist/assets/BgTasksModal-Ck2sjlPM.js +0 -1
  168. package/web/dist/assets/DeviceCenter-BQdDcO8A.js +0 -3
  169. package/web/dist/assets/DeviceCenter-CHRKL0Vy.js +0 -3
  170. package/web/dist/assets/DeviceGroups-D2rogxEN.js +0 -1
  171. package/web/dist/assets/Dropdown-ZLS04O8p.js +0 -1
  172. package/web/dist/assets/FilePreview-B9xoU6ON.js +0 -2
  173. package/web/dist/assets/FilePreview-DUQpVZkH.js +0 -2
  174. package/web/dist/assets/GlobalSearchModal-BXEGvUZq.js +0 -1
  175. package/web/dist/assets/GlobalSearchModal-CnVPmfOI.js +0 -1
  176. package/web/dist/assets/GroupConversation-CyIpQzDd.js +0 -1
  177. package/web/dist/assets/GroupConversation-DgYV3uYS.js +0 -1
  178. package/web/dist/assets/ModelConfigModal-DDZccDYt.js +0 -2
  179. package/web/dist/assets/PiSetupModal-DHbqfx8T.js +0 -1
  180. package/web/dist/assets/ProviderOAuthControls-C-MK36Dk.js +0 -1
  181. package/web/dist/assets/SCMPanel-imYI2Ecw.js +0 -2
  182. package/web/dist/assets/SCMPanel-sVZcV7dR.js +0 -2
  183. package/web/dist/assets/SettingsModal-Xw1Yoi3_.js +0 -20
  184. package/web/dist/assets/SettingsModal-mb4e34-0.js +0 -20
  185. package/web/dist/assets/TerminalPanel-CLkJJvxg.js +0 -3
  186. package/web/dist/assets/TerminalPanel-DpcIellm.js +0 -3
  187. package/web/dist/assets/TuiOverlayModal-4-fFAZe7.js +0 -1
  188. package/web/dist/assets/TuiOverlayModal-DCu01lks.js +0 -1
  189. package/web/dist/assets/app-globals-DcyO0UPi.js +0 -1
  190. package/web/dist/assets/fi-DaSO0Q-m.js +0 -325
  191. package/web/dist/assets/index-Cdh3sibd.js +0 -85
  192. package/web/dist/assets/index-DDZMv6LO.css +0 -1
  193. package/web/dist/assets/index-DWw_SxRq.js +0 -85
  194. package/web/dist/assets/plugin-host-BRBg6zmQ.js +0 -1
  195. package/web/dist/assets/theme-DDl-Oy1b.js +0 -1
@@ -1,4 +1,6 @@
1
1
  import { randomBytes, randomUUID } from "node:crypto";
2
+ import { parseReportMetadata } from "./report-metadata.js";
3
+ import { integrationErrorFromCode } from "./integration-errors.js";
2
4
  import { WebSocket, WebSocketServer } from "ws";
3
5
  import { capabilityBase, createPortalResponse, parseDevicePath, portalHeaders, wrapperHtml } from "./path-portal.js";
4
6
  export const RELAY_LIMITS = {
@@ -7,6 +9,7 @@ export const RELAY_LIMITS = {
7
9
  queue: 2 * 1024 * 1024,
8
10
  body: 64 * 1024 * 1024,
9
11
  streams: 32,
12
+ cancellations: 16,
10
13
  devices: 128,
11
14
  sessions: 2048,
12
15
  };
@@ -98,10 +101,10 @@ export function safePath(path, method = "GET") {
98
101
  if (normalized === "/api/device-center" || normalized.startsWith("/api/device-center/")) {
99
102
  // Only account-scoped chat routes may cross a device portal.
100
103
  if (method === "GET") {
101
- return /^\/api\/device-center\/(chat-status|devices|bots|rooms(?:\/[^/]+)?)$/.test(normalized);
104
+ return /^\/api\/device-center\/(chat-status|devices|bots|rooms(?:\/[^/]+(?:\/(?:events|interactions|conversations(?:\/[^/]+)?))?)?)$/.test(normalized);
102
105
  }
103
106
  if (method === "POST")
104
- return /^\/api\/device-center\/rooms(?:\/[^/]+\/(messages|rename|members|delete))?$/.test(normalized);
107
+ return /^\/api\/device-center\/rooms(?:\/[^/]+\/(messages|rename|members|clear|delete|interactions|conversations(?:\/[^/]+\/(messages|stop|deliveries|reviews))?))?$/.test(normalized);
105
108
  return false;
106
109
  }
107
110
  return !["/devices", "/setup", "/api/setup"].some((prefix) => normalized === prefix || normalized.startsWith(prefix + "/"));
@@ -110,7 +113,22 @@ export function safePath(path, method = "GET") {
110
113
  return false;
111
114
  }
112
115
  }
113
- export const COMMANDS = ["transfer_stage", "transfer_preview", "transfer_apply"];
116
+ export const COMMANDS = [
117
+ "transfer_stage",
118
+ "transfer_preview",
119
+ "transfer_apply",
120
+ "transfer_init",
121
+ "transfer_chunk",
122
+ "transfer_status",
123
+ "transfer_abort",
124
+ "transfer_prepare_export",
125
+ "transfer_read_chunk",
126
+ "transfer_fence",
127
+ "integration_prepare",
128
+ "integration_verify",
129
+ "integration_confirm",
130
+ "integration_cancel",
131
+ ];
114
132
  const RPC_BYTES = 12 * 1024 * 1024;
115
133
  /** Bounded chunked RPC, scoped to exactly one authenticated connection. */
116
134
  export function createCommandChannel(ws, handler) {
@@ -132,7 +150,8 @@ export function createCommandChannel(ws, handler) {
132
150
  throw new Error("Command capacity exceeded");
133
151
  const timer = setTimeout(() => {
134
152
  sendFrame(ws, { type: "rpc_cancel", id });
135
- remove(id, new Error("Command timed out"));
153
+ const err = Object.assign(new Error("Command timed out"), { stopUnconfirmed: true });
154
+ remove(id, err);
136
155
  }, 60_000);
137
156
  timer.unref();
138
157
  const item = {
@@ -191,9 +210,20 @@ export function createCommandChannel(ws, handler) {
191
210
  }
192
211
  item.resolve = resolve;
193
212
  item.reject = reject;
213
+ item.action = action;
194
214
  const abort = () => {
215
+ if (item.cancelling)
216
+ return;
217
+ item.cancelling = true;
195
218
  sendFrame(ws, { type: "rpc_cancel", id });
196
- remove(id, new Error("Command cancelled"));
219
+ clearTimeout(item.timer);
220
+ item.timer = setTimeout(() => {
221
+ const err = Object.assign(new Error("Command cancellation unconfirmed: timeout"), {
222
+ stopUnconfirmed: true,
223
+ });
224
+ remove(id, err);
225
+ }, 30_000);
226
+ item.timer.unref();
197
227
  };
198
228
  options.signal?.addEventListener("abort", abort, { once: true });
199
229
  item.detach = () => options.signal?.removeEventListener("abort", abort);
@@ -202,8 +232,10 @@ export function createCommandChannel(ws, handler) {
202
232
  return;
203
233
  }
204
234
  void transmit(id, "rpc_request", payload, item.controller.signal).catch((error) => {
205
- sendFrame(ws, { type: "rpc_cancel", id });
206
- remove(id, error);
235
+ if (!item.cancelling) {
236
+ sendFrame(ws, { type: "rpc_cancel", id });
237
+ remove(id, error);
238
+ }
207
239
  });
208
240
  });
209
241
  },
@@ -225,10 +257,23 @@ export function createCommandChannel(ws, handler) {
225
257
  const item = pending.get(id);
226
258
  if (!item)
227
259
  return true;
228
- if (frame.type === "rpc_cancel" || frame.type === "rpc_error") {
260
+ if (frame.type === "rpc_cancel") {
261
+ if (item.incoming && item.executing) {
262
+ item.controller.abort();
263
+ return true;
264
+ }
229
265
  remove(id, new Error("Remote command rejected"));
230
266
  return true;
231
267
  }
268
+ if (frame.type === "rpc_cancel_ack") {
269
+ remove(id, new Error("Remote command cancelled"));
270
+ return true;
271
+ }
272
+ if (frame.type === "rpc_error") {
273
+ const safeError = item.action?.startsWith("integration_") ? integrationErrorFromCode(frame.code) : undefined;
274
+ remove(id, safeError ?? new Error("Remote command rejected"));
275
+ return true;
276
+ }
232
277
  if (item.executing)
233
278
  throw new Error("Command already executing");
234
279
  const prefix = item.incoming ? "rpc_request" : "rpc_response";
@@ -252,17 +297,31 @@ export function createCommandChannel(ws, handler) {
252
297
  }
253
298
  item.executing = true;
254
299
  const run = async () => {
300
+ let wasAborted = false;
301
+ const onAbort = () => {
302
+ wasAborted = true;
303
+ };
304
+ item.controller.signal.addEventListener("abort", onAbort, { once: true });
255
305
  try {
256
306
  const result = await handler(item.action, value, item.controller.signal);
257
307
  if (pending.get(id) !== item)
258
308
  return;
309
+ if (wasAborted || item.controller.signal.aborted)
310
+ return;
259
311
  await transmit(id, "rpc_response", result, item.controller.signal);
260
312
  }
261
- catch {
262
- if (pending.get(id) === item)
263
- sendFrame(ws, { type: "rpc_error", id });
313
+ catch (error) {
314
+ if (!wasAborted && !item.controller.signal.aborted && pending.get(id) === item) {
315
+ const code = error && typeof error === "object" && "code" in error ? error.code : undefined;
316
+ const safeError = item.action?.startsWith("integration_") ? integrationErrorFromCode(code) : undefined;
317
+ sendFrame(ws, { type: "rpc_error", id, ...(safeError ? { code } : {}) });
318
+ }
264
319
  }
265
320
  finally {
321
+ item.controller.signal.removeEventListener("abort", onAbort);
322
+ if (wasAborted || item.controller.signal.aborted) {
323
+ sendFrame(ws, { type: "rpc_cancel_ack", id });
324
+ }
266
325
  remove(id);
267
326
  }
268
327
  };
@@ -271,8 +330,12 @@ export function createCommandChannel(ws, handler) {
271
330
  },
272
331
  close() {
273
332
  ended = true;
274
- for (const id of pending.keys())
275
- remove(id, new Error("Device disconnected"));
333
+ for (const [id, item] of pending.entries()) {
334
+ const err = Object.assign(new Error(item.cancelling
335
+ ? "Command cancellation unconfirmed: device disconnected"
336
+ : "Device disconnected before command completed"), { stopUnconfirmed: true });
337
+ remove(id, err);
338
+ }
276
339
  },
277
340
  };
278
341
  }
@@ -400,6 +463,8 @@ export function createDeviceRelay(options) {
400
463
  }
401
464
  if (!["http:", "https:"].includes(hub.protocol) || hub.pathname !== "/" || hub.search)
402
465
  throw new Error("publicUrl must be an HTTP(S) root origin");
466
+ const interactionAcks = new Map();
467
+ const deviceGenerations = new Map();
403
468
  const devices = new Map();
404
469
  // Slow browser responses apply transport backpressure instead of losing resource bodies.
405
470
  const stalledResponses = new WeakMap();
@@ -424,7 +489,15 @@ export function createDeviceRelay(options) {
424
489
  const tickets = new Map();
425
490
  const sessions = new Map();
426
491
  const capabilities = new Map();
427
- const pathRequest = (req) => options.pathAccess && req.headers.host?.toLowerCase() === hub.host.toLowerCase() ? parseDevicePath(req.url) : null;
492
+ const pathRequest = (req) => {
493
+ if (req.headers.host?.toLowerCase() !== hub.host.toLowerCase())
494
+ return null;
495
+ const path = parseDevicePath(req.url);
496
+ // Desktop embedding uses an opaque capability on the Hub even with legacy device origins.
497
+ return options.pathAccess || path?.tail === "/__open" || (path?.token && capabilities.has(path.token))
498
+ ? path
499
+ : null;
500
+ };
428
501
  function pathAuthorized(req, id, websocket = false) {
429
502
  const path = pathRequest(req);
430
503
  const session = path?.token ? capabilities.get(path.token) : undefined;
@@ -479,19 +552,34 @@ export function createDeviceRelay(options) {
479
552
  return false;
480
553
  return true;
481
554
  }
482
- function drop(id, entry) {
555
+ function drop(id, entry, optionsDrop) {
556
+ for (const pending of interactionAcks.values())
557
+ if (pending.ws === entry.ws)
558
+ pending.finish(false);
559
+ for (const pending of entry.cancellations.values())
560
+ pending.finish(false);
483
561
  entry.rpc.close();
484
562
  entry.messages.close();
485
- for (const [taskId, { attemptId, botId }] of entry.tasks) {
486
- Promise.resolve()
487
- .then(() => options.onTaskEvent?.(id, {
488
- taskId,
489
- botId,
490
- attemptId,
491
- status: "interrupted",
492
- report: "Device connection lost; task is not replayed",
493
- }))
494
- .catch(() => { });
563
+ for (const [taskId, { attemptId, botId, hasLease }] of entry.tasks) {
564
+ if (optionsDrop?.isRevoke || !hasLease) {
565
+ Promise.resolve()
566
+ .then(() => options.onTaskEvent?.(id, {
567
+ taskId,
568
+ botId,
569
+ attemptId,
570
+ status: "interrupted",
571
+ report: optionsDrop?.isRevoke
572
+ ? "Device revoked; task interrupted."
573
+ : "Device connection lost; task is not replayed",
574
+ }))
575
+ .catch(() => { });
576
+ }
577
+ else {
578
+ // Retain recovery grace window on Hub for tasks with active lease!
579
+ Promise.resolve()
580
+ .then(() => options.onTaskDisconnect?.(id, taskId, attemptId))
581
+ .catch(() => { });
582
+ }
495
583
  }
496
584
  entry.tasks.clear();
497
585
  for (const stream of entry.streams.values()) {
@@ -567,7 +655,9 @@ export function createDeviceRelay(options) {
567
655
  }
568
656
  const token = randomBytes(32).toString("hex");
569
657
  capabilities.set(token, { deviceId: id, accountId, expiresAt: Date.now() + 8 * 60 * 60_000 });
570
- const wrapper = wrapperHtml(capabilityBase(id, token), initialPath);
658
+ const name = options.getDeviceName?.(id)?.trim();
659
+ const label = name && name !== id ? `${name} (${id})` : id;
660
+ const wrapper = wrapperHtml(capabilityBase(id, token), initialPath, initialPath === "desktop" ? hub : undefined, label);
571
661
  res
572
662
  .writeHead(200, {
573
663
  "content-type": "text/html; charset=utf-8",
@@ -640,6 +730,19 @@ export function createDeviceRelay(options) {
640
730
  return true;
641
731
  }
642
732
  tickets.delete(key);
733
+ if (url.searchParams.get("next") === "/desktop" && !path) {
734
+ // Exchange the one-use legacy ticket for a fresh one on the Hub origin.
735
+ const desktopTicket = randomBytes(32).toString("hex");
736
+ tickets.set(desktopTicket, ticket);
737
+ res
738
+ .writeHead(302, {
739
+ location: `${hub.origin}/device/${id}/__open?ticket=${desktopTicket}&next=/desktop`,
740
+ "cache-control": "no-store",
741
+ "referrer-policy": "no-referrer",
742
+ })
743
+ .end();
744
+ return true;
745
+ }
643
746
  if (path) {
644
747
  sendWrapper(res, id, ticket.accountId, url.searchParams.get("next") === "/desktop" ? "desktop" : "");
645
748
  return true;
@@ -809,10 +912,14 @@ export function createDeviceRelay(options) {
809
912
  drop(device, old);
810
913
  old.ws.terminate();
811
914
  }
915
+ const gen = (deviceGenerations.get(device) ?? 0) + 1;
916
+ deviceGenerations.set(device, gen);
812
917
  const entry = {
918
+ generation: gen,
813
919
  ws,
814
920
  streams: new Map(),
815
921
  tasks: new Map(),
922
+ cancellations: new Map(),
816
923
  rpc: createCommandChannel(ws),
817
924
  messages: createWsMessageChannel(ws),
818
925
  };
@@ -826,20 +933,190 @@ export function createDeviceRelay(options) {
826
933
  const frame = parseFrame(Buffer.from(raw));
827
934
  if (entry.rpc.handle(frame))
828
935
  return;
936
+ if (frame.type === "task_cancelled") {
937
+ const pending = typeof frame.id === "string" ? entry.cancellations.get(frame.id) : undefined;
938
+ if (!pending)
939
+ return;
940
+ if (pending.taskId !== frame.taskId ||
941
+ pending.attemptId !== frame.attemptId ||
942
+ typeof frame.stopped !== "boolean")
943
+ throw new Error("Invalid task cancellation acknowledgement");
944
+ pending.finish(frame.stopped);
945
+ return;
946
+ }
947
+ if (frame.type === "task_interaction_result") {
948
+ const pending = typeof frame.id === "string" ? interactionAcks.get(frame.id) : undefined;
949
+ if (pending?.ws === ws)
950
+ pending.finish(frame.accepted === true);
951
+ return;
952
+ }
953
+ if (frame.type === "task_interactions") {
954
+ if (typeof frame.taskId !== "string")
955
+ return;
956
+ const task = entry.tasks.get(frame.taskId);
957
+ if (!task || task.attemptId !== frame.attemptId || task.botId !== frame.botId)
958
+ return;
959
+ Promise.resolve()
960
+ .then(() => options.onTaskInteractions?.(device, frame))
961
+ .catch(() => { });
962
+ return;
963
+ }
964
+ if (frame.type === "task_tool_lifecycle") {
965
+ if (typeof frame.taskId !== "string")
966
+ return;
967
+ const task = entry.tasks.get(frame.taskId);
968
+ if (!task || task.attemptId !== frame.attemptId || task.botId !== frame.botId)
969
+ return;
970
+ Promise.resolve()
971
+ .then(() => options.onTaskToolLifecycle?.(device, frame))
972
+ .catch(() => { });
973
+ return;
974
+ }
975
+ if (frame.type === "task_plan_ready") {
976
+ if (typeof frame.taskId !== "string")
977
+ return;
978
+ const task = entry.tasks.get(frame.taskId);
979
+ const authorized = task && task.attemptId === frame.attemptId && task.botId === frame.botId;
980
+ Promise.resolve()
981
+ .then(() => authorized
982
+ ? options.onTaskPlanReady?.(device, frame)
983
+ : false)
984
+ .catch(() => false)
985
+ .then((accepted) => {
986
+ if (ws.readyState === WebSocket.OPEN)
987
+ sendFrame(ws, {
988
+ type: "task_plan_ack",
989
+ taskId: frame.taskId,
990
+ botId: frame.botId,
991
+ attemptId: frame.attemptId,
992
+ accepted: accepted === true,
993
+ });
994
+ });
995
+ return;
996
+ }
997
+ if (frame.type === "task_progress") {
998
+ if (typeof frame.taskId !== "string")
999
+ return;
1000
+ const task = entry.tasks.get(frame.taskId);
1001
+ if (!task || task.attemptId !== frame.attemptId || task.botId !== frame.botId)
1002
+ return;
1003
+ Promise.resolve()
1004
+ .then(() => options.onTaskProgress?.(device, frame))
1005
+ .catch(() => { });
1006
+ return;
1007
+ }
829
1008
  if (frame.type === "task_event") {
830
- if (typeof frame.taskId !== "string" ||
831
- typeof frame.botId !== "string" ||
832
- entry.tasks.get(frame.taskId)?.attemptId !== frame.attemptId ||
833
- entry.tasks.get(frame.taskId)?.botId !== frame.botId ||
834
- !["running", "completed", "failed"].includes(String(frame.status)))
1009
+ const taskId = frame.taskId;
1010
+ const botId = frame.botId;
1011
+ const attemptId = frame.attemptId;
1012
+ if (typeof taskId !== "string" ||
1013
+ typeof botId !== "string" ||
1014
+ typeof attemptId !== "string" ||
1015
+ !["running", "completed", "failed", "interrupted"].includes(String(frame.status)))
1016
+ throw new Error("Unknown task");
1017
+ if (frame.reportMetadata !== undefined)
1018
+ frame.reportMetadata = parseReportMetadata(frame.reportMetadata);
1019
+ const current = entry.tasks.get(taskId);
1020
+ if (current && (current.attemptId !== attemptId || current.botId !== botId))
835
1021
  throw new Error("Unknown task");
836
- if (frame.status === "completed" || frame.status === "failed")
837
- entry.tasks.delete(frame.taskId);
838
1022
  Promise.resolve()
839
1023
  .then(() => options.onTaskEvent?.(device, frame))
1024
+ .then(() => {
1025
+ if (devices.get(device) === entry) {
1026
+ const postCheck = entry.tasks.get(taskId);
1027
+ if (postCheck && postCheck.attemptId === attemptId && postCheck.botId === botId) {
1028
+ if (frame.status === "completed" || frame.status === "failed" || frame.status === "interrupted") {
1029
+ entry.tasks.delete(taskId);
1030
+ }
1031
+ }
1032
+ if (frame.status === "completed" || frame.status === "failed" || frame.status === "interrupted") {
1033
+ sendFrame(ws, {
1034
+ type: "task_result_ack",
1035
+ taskId: frame.taskId,
1036
+ attemptId: frame.attemptId,
1037
+ status: frame.status,
1038
+ ...(typeof frame.fingerprint === "string" ? { fingerprint: frame.fingerprint } : {}),
1039
+ });
1040
+ }
1041
+ }
1042
+ })
840
1043
  .catch(() => ws.terminate());
841
1044
  return;
842
1045
  }
1046
+ // === Task Recovery / Reconnect Claim / Lease Renewal ===
1047
+ if (frame.type === "task_claim") {
1048
+ const rawClaim = frame.claim ?? frame;
1049
+ if (!rawClaim ||
1050
+ typeof rawClaim !== "object" ||
1051
+ typeof rawClaim.taskId !== "string" ||
1052
+ rawClaim.taskId.length > 128 ||
1053
+ typeof rawClaim.attemptId !== "string" ||
1054
+ rawClaim.attemptId.length > 128 ||
1055
+ typeof rawClaim.botId !== "string" ||
1056
+ rawClaim.botId.length > 128)
1057
+ return;
1058
+ const claim = rawClaim;
1059
+ Promise.resolve()
1060
+ .then(() => options.onTaskClaim?.(device, claim))
1061
+ .then((result) => {
1062
+ if (devices.get(device) !== entry)
1063
+ return;
1064
+ const accepted = result?.accepted === true;
1065
+ if (accepted) {
1066
+ entry.tasks.set(claim.taskId, {
1067
+ attemptId: claim.attemptId,
1068
+ botId: claim.botId,
1069
+ hasLease: true,
1070
+ });
1071
+ }
1072
+ sendFrame(ws, {
1073
+ type: "task_claim_result",
1074
+ taskId: claim.taskId,
1075
+ attemptId: claim.attemptId,
1076
+ accepted,
1077
+ reason: result?.reason,
1078
+ });
1079
+ })
1080
+ .catch(() => {
1081
+ if (devices.get(device) === entry) {
1082
+ sendFrame(ws, {
1083
+ type: "task_claim_result",
1084
+ taskId: claim.taskId,
1085
+ attemptId: claim.attemptId,
1086
+ accepted: false,
1087
+ reason: "Claim rejected",
1088
+ });
1089
+ }
1090
+ });
1091
+ return;
1092
+ }
1093
+ if (frame.type === "task_lease_renew") {
1094
+ const rawRenew = frame.renew;
1095
+ if (!rawRenew ||
1096
+ typeof rawRenew !== "object" ||
1097
+ typeof rawRenew.taskId !== "string" ||
1098
+ rawRenew.taskId.length > 128 ||
1099
+ typeof rawRenew.attemptId !== "string" ||
1100
+ rawRenew.attemptId.length > 128)
1101
+ return;
1102
+ const renew = rawRenew;
1103
+ Promise.resolve()
1104
+ .then(() => options.onTaskLeaseRenew?.(device, renew))
1105
+ .then((result) => {
1106
+ if (devices.get(device) !== entry)
1107
+ return;
1108
+ sendFrame(ws, {
1109
+ type: "task_lease_result",
1110
+ taskId: renew.taskId,
1111
+ attemptId: renew.attemptId,
1112
+ accepted: result?.accepted === true,
1113
+ reason: result?.reason,
1114
+ });
1115
+ })
1116
+ .catch(() => { });
1117
+ return;
1118
+ }
1119
+ // ========================================================
843
1120
  const item = entry.streams.get(frame.id);
844
1121
  if (!item)
845
1122
  return;
@@ -930,6 +1207,53 @@ export function createDeviceRelay(options) {
930
1207
  }, 15_000);
931
1208
  heartbeat.unref();
932
1209
  return {
1210
+ async answerInteraction(deviceId, answer) {
1211
+ const entry = devices.get(deviceId);
1212
+ if (!entry ||
1213
+ entry.ws.readyState !== WebSocket.OPEN ||
1214
+ entry.tasks.get(answer.taskId)?.attemptId !== answer.attemptId)
1215
+ return false;
1216
+ if (interactionAcks.size >= 128)
1217
+ return false;
1218
+ const id = randomUUID();
1219
+ return new Promise((resolve) => {
1220
+ const finish = (ok) => {
1221
+ if (!interactionAcks.delete(id))
1222
+ return;
1223
+ clearTimeout(timer);
1224
+ resolve(ok);
1225
+ };
1226
+ const timer = setTimeout(() => finish(false), 5000);
1227
+ timer.unref();
1228
+ interactionAcks.set(id, { ws: entry.ws, finish });
1229
+ if (!sendFrame(entry.ws, { type: "task_interaction_answer", id, answer }))
1230
+ finish(false);
1231
+ });
1232
+ },
1233
+ cancelTask(deviceId, taskId, attemptId) {
1234
+ const entry = devices.get(deviceId);
1235
+ if (!entry ||
1236
+ entry.ws.readyState !== WebSocket.OPEN ||
1237
+ entry.tasks.get(taskId)?.attemptId !== attemptId ||
1238
+ entry.cancellations.size >= RELAY_LIMITS.cancellations)
1239
+ return Promise.resolve({ stopped: false });
1240
+ const id = randomUUID();
1241
+ return new Promise((resolve) => {
1242
+ const finish = (stopped) => {
1243
+ if (!entry.cancellations.delete(id))
1244
+ return;
1245
+ clearTimeout(timer);
1246
+ if (stopped && entry.tasks.get(taskId)?.attemptId === attemptId)
1247
+ entry.tasks.delete(taskId);
1248
+ resolve({ stopped });
1249
+ };
1250
+ const timer = setTimeout(() => finish(false), 10_000);
1251
+ timer.unref();
1252
+ entry.cancellations.set(id, { taskId, attemptId, finish });
1253
+ if (!sendFrame(entry.ws, { type: "task_cancel", id, taskId, attemptId }))
1254
+ finish(false);
1255
+ });
1256
+ },
933
1257
  callDevice(id, action, payload, options) {
934
1258
  const entry = devices.get(id);
935
1259
  return entry ? entry.rpc.call(action, payload, options) : Promise.reject(new Error("Device offline"));
@@ -946,6 +1270,7 @@ export function createDeviceRelay(options) {
946
1270
  },
947
1271
  isDeviceRequest: (req) => !!deviceId(req) || !!(domain && req.headers.host?.toLowerCase().endsWith(`.${domain}`)),
948
1272
  isOnline: (id) => devices.get(id)?.ws.readyState === WebSocket.OPEN,
1273
+ getDeviceGeneration: (id) => devices.get(id)?.generation,
949
1274
  sendTask(id, task) {
950
1275
  const entry = devices.get(id);
951
1276
  if (!entry ||
@@ -959,7 +1284,11 @@ export function createDeviceRelay(options) {
959
1284
  entry.tasks.has(task.id) ||
960
1285
  entry.tasks.size >= RELAY_LIMITS.streams)
961
1286
  return false;
962
- entry.tasks.set(task.id, { attemptId: task.attemptId, botId: task.botId });
1287
+ entry.tasks.set(task.id, {
1288
+ attemptId: task.attemptId,
1289
+ botId: task.botId,
1290
+ hasLease: typeof task.leaseToken === "string" && !!task.leaseToken,
1291
+ });
963
1292
  if (!sendFrame(entry.ws, { type: "task", task })) {
964
1293
  entry.tasks.delete(task.id);
965
1294
  return false;
@@ -974,7 +1303,7 @@ export function createDeviceRelay(options) {
974
1303
  map.delete(key);
975
1304
  const entry = devices.get(id);
976
1305
  if (entry) {
977
- drop(id, entry);
1306
+ drop(id, entry, { isRevoke: true });
978
1307
  entry.ws.terminate();
979
1308
  }
980
1309
  },
@@ -0,0 +1,66 @@
1
+ import { MAX_TASK_FULL_REPORT_BYTES } from "./task-report.js";
2
+ export function parseReportMetadata(value) {
3
+ if (!value || typeof value !== "object" || Array.isArray(value))
4
+ throw new Error("Invalid report metadata");
5
+ const e = value;
6
+ if (Object.keys(e).some((key) => !["sha256", "totalBytes", "missing", "rejected", "uploadPending", "publicError"].includes(key)) ||
7
+ !Number.isSafeInteger(e.totalBytes) ||
8
+ e.totalBytes < 0 ||
9
+ e.totalBytes > 1024 * 1024 * 1024 ||
10
+ ["missing", "rejected", "uploadPending"].some((key) => typeof e[key] !== "boolean") ||
11
+ (e.sha256 !== undefined && (typeof e.sha256 !== "string" || !/^[a-f0-9]{64}$/.test(e.sha256))) ||
12
+ (e.publicError !== undefined &&
13
+ !["report_quota_exceeded", "report_missing", "report_upload_pending"].includes(e.publicError)) ||
14
+ (e.rejected && (!e.missing || e.uploadPending)) ||
15
+ (e.uploadPending && !e.sha256))
16
+ throw new Error("Invalid report metadata");
17
+ return {
18
+ ...(e.sha256 ? { sha256: e.sha256 } : {}),
19
+ totalBytes: e.totalBytes,
20
+ missing: e.missing,
21
+ rejected: e.rejected,
22
+ uploadPending: e.uploadPending,
23
+ ...(e.publicError ? { publicError: e.publicError } : {}),
24
+ };
25
+ }
26
+ export function reportUploadMetadata(entry) {
27
+ return parseReportMetadata(entry
28
+ ? {
29
+ sha256: entry.sha256,
30
+ totalBytes: entry.totalBytes,
31
+ missing: entry.missing,
32
+ rejected: entry.rejected,
33
+ uploadPending: entry.uploadPending,
34
+ ...(entry.rejected
35
+ ? { publicError: "report_quota_exceeded" }
36
+ : entry.uploadPending
37
+ ? { publicError: "report_upload_pending" }
38
+ : entry.missing
39
+ ? { publicError: "report_missing" }
40
+ : {}),
41
+ }
42
+ : { totalBytes: 0, missing: true, rejected: false, uploadPending: false, publicError: "report_missing" });
43
+ }
44
+ export function mergeTaskReportMetadata(task, stored) {
45
+ if (stored?.complete)
46
+ return { ...stored, missing: false, rejected: false, uploadPending: false };
47
+ const metadata = task.reportMetadata ?? reportUploadMetadata();
48
+ return {
49
+ taskId: task.id,
50
+ attemptId: task.attemptId,
51
+ roomId: task.roomId,
52
+ accountId: task.accountId,
53
+ createdAt: task.createdAt,
54
+ updatedAt: task.updatedAt,
55
+ totalChunks: 0,
56
+ receivedChunks: 0,
57
+ storageLocation: { role: "hub", reportRef: "" },
58
+ quotaLimit: MAX_TASK_FULL_REPORT_BYTES,
59
+ quotaExceeded: metadata.rejected && metadata.totalBytes > MAX_TASK_FULL_REPORT_BYTES,
60
+ complete: false,
61
+ ...stored,
62
+ ...metadata,
63
+ missing: metadata.missing || stored?.missing === true || !stored,
64
+ ...(!metadata.uploadPending && !metadata.rejected ? { publicError: "report_missing" } : {}),
65
+ };
66
+ }