shadow-claw 1.23.4 → 1.24.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 (267) hide show
  1. package/README.md +42 -5
  2. package/bin/cli.mjs +166 -0
  3. package/bin/cli.test.mjs +60 -0
  4. package/bin/commands/backup.mjs +70 -0
  5. package/bin/commands/clients.mjs +41 -0
  6. package/bin/commands/peer-id.mjs +76 -0
  7. package/bin/commands/peer-id.test.mjs +104 -0
  8. package/bin/commands/send.mjs +51 -0
  9. package/bin/commands/tasks.mjs +59 -0
  10. package/bin/commands/webrtc-listen.mjs +254 -0
  11. package/bin/prerender-dsd-shell/prerender-dsd-shell.test.mjs +46 -0
  12. package/bin/rolldown.config.test.mjs +401 -8
  13. package/bin/utils/control-client.mjs +243 -0
  14. package/bin/utils/control-client.test.mjs +83 -0
  15. package/bin/utils/ulid.mjs +45 -0
  16. package/bin/utils/webrtc-control-client.mjs +699 -0
  17. package/bin/utils/webrtc-control-client.test.mjs +318 -0
  18. package/dist/electron/main.cjs +1 -1
  19. package/dist/public/AGENTS.md +12 -3
  20. package/dist/public/README.md +42 -5
  21. package/dist/public/agent.worker.js +50 -50
  22. package/dist/public/backup-controller-CvzDOq4T.js +1 -0
  23. package/dist/public/components/settings/shadow-claw-control-plane/shadow-claw-control-plane.css +1 -0
  24. package/dist/public/components/settings/shadow-claw-control-plane/shadow-claw-control-plane.html +1 -0
  25. package/dist/public/components/settings/shadow-claw-task-server/shadow-claw-task-server.css +1 -1
  26. package/dist/public/components/settings/shadow-claw-task-server/shadow-claw-task-server.html +1 -1
  27. package/dist/public/components/shadow-claw-settings/shadow-claw-settings.html +1 -1
  28. package/dist/public/config-CrHchneq.js +1 -0
  29. package/dist/public/{configurePeerJs-B4Ym9VMj.js → configurePeerJs-UfQ6HUlv.js} +1 -1
  30. package/dist/public/{connections-BEn6JYdu.js → connections-DvbgdkaB.js} +1 -1
  31. package/dist/public/{custom-element-security-DdYlUozq.js → custom-element-security-NCqQ5lmC.js} +1 -1
  32. package/dist/public/docs/README.md +3 -1
  33. package/dist/public/docs/architecture/overview.md +12 -12
  34. package/dist/public/docs/decisions/bundled-typescript-architecture.md +1 -1
  35. package/dist/public/docs/decisions/indexeddb-and-opfs-storage.md +2 -2
  36. package/dist/public/docs/decisions/native-web-components-and-signals.md +1 -1
  37. package/dist/public/docs/example/article/index.html +1 -1
  38. package/dist/public/docs/guides/configuring-messaging-channels.md +41 -6
  39. package/dist/public/docs/guides/server-development-configuration.md +24 -0
  40. package/dist/public/docs/publishing/index.html +1 -1
  41. package/dist/public/docs/skill-creator/index.html +1 -1
  42. package/dist/public/docs/subsystems/backup.md +56 -0
  43. package/dist/public/docs/subsystems/cli.md +124 -0
  44. package/dist/public/docs/subsystems/control-plane.md +169 -0
  45. package/dist/public/docs/subsystems/notifications.md +54 -2
  46. package/dist/public/docs/subsystems/reactive-ui.md +1 -0
  47. package/dist/public/downloadGroupFile-9niHBj9n.js +1 -0
  48. package/dist/public/e2e/README.md +5 -1
  49. package/dist/public/{e2e-bridge-BQ4KzUt5.js → e2e-bridge-D28tOggc.js} +1 -1
  50. package/dist/public/file-viewer-BVg3B_JH.js +1 -0
  51. package/dist/public/getAllTasks-vpBlgGsc.js +1 -0
  52. package/dist/public/getGroupDir-P1h9wl6S.js +1 -0
  53. package/dist/public/{git-DEUvQTUA.js → git-7Vq_SJSp.js} +2 -2
  54. package/dist/public/{iframe-sanitizer-0NS4XLOd.js → iframe-sanitizer-y2Z1pPwY.js} +1 -1
  55. package/dist/public/index.html +1 -1
  56. package/dist/public/index.js +1 -1
  57. package/dist/public/{initChatSplitResize-llGkSJXg.js → initChatSplitResize-CzV2E7Ul.js} +1 -1
  58. package/dist/public/initControlPlane-DKNht5ph.js +1 -0
  59. package/dist/public/llms.txt +1 -1
  60. package/dist/public/main/index.html +1 -1
  61. package/dist/public/main/memory/index.html +1 -1
  62. package/dist/public/{markdown-CyYR4App.js → markdown-SiFq0PTy.js} +1 -1
  63. package/dist/public/{mcp-reconnect-CSx4aMwy.js → mcp-reconnect-9emsqGRe.js} +1 -1
  64. package/dist/public/{memoryStorage-Dwg8NhAZ.js → memoryStorage-C0KvLNUp.js} +1 -1
  65. package/dist/public/orchestrator-8w9-exfN.js +15 -0
  66. package/dist/public/{orchestrator-DRfEudXk.js → orchestrator-tHWrqi_F.js} +676 -676
  67. package/dist/public/{peerjs-CurBuKvk.js → peerjs-D8hck8Ih.js} +1 -1
  68. package/dist/public/push-client-D0lkwrK0.js +1 -0
  69. package/dist/public/service-worker/fetch-proxy.js +1 -1
  70. package/dist/public/service-worker/push-handler.js +1 -1
  71. package/dist/public/service-worker.js +1 -1
  72. package/dist/public/{shadow-claw-5IHaDDMJ.js → shadow-claw-Cs8wbk3d.js} +2 -2
  73. package/dist/public/{shadow-claw-accounts-CZvz4iQz.js → shadow-claw-accounts-B4sBTQEj.js} +1 -1
  74. package/dist/public/{shadow-claw-channels-BKXFyRS3.js → shadow-claw-channels-mY-JMvib.js} +1 -1
  75. package/dist/public/{shadow-claw-chat-CCLuhWdI.js → shadow-claw-chat-DGPKpmU5.js} +6 -6
  76. package/dist/public/shadow-claw-control-plane-B1F0jnPk.js +199 -0
  77. package/dist/public/{shadow-claw-conversations-DV-87UUh.js → shadow-claw-conversations-0Q-VC_7N.js} +1 -1
  78. package/dist/public/shadow-claw-dialog-BrOwAOdk.js +1 -0
  79. package/dist/public/{shadow-claw-file-viewer-Dk2dbAUd.js → shadow-claw-file-viewer-AZfG4D-u.js} +1 -1
  80. package/dist/public/shadow-claw-files-Bx4v0Ggp.js +840 -0
  81. package/dist/public/{shadow-claw-git-DRA7_qck.js → shadow-claw-git-DD7iQRxq.js} +2 -2
  82. package/dist/public/{shadow-claw-integrations-1Xu5snuV.js → shadow-claw-integrations-D7ufpwhX.js} +1 -1
  83. package/dist/public/{shadow-claw-llm-6Aci1BDP.js → shadow-claw-llm-CfeDBZKB.js} +2 -2
  84. package/dist/public/{shadow-claw-mcp-remote-BUjAeVXC.js → shadow-claw-mcp-remote-kY4LMFNN.js} +1 -1
  85. package/dist/public/{shadow-claw-networking-FQe4nCp3.js → shadow-claw-networking-e0EarDVs.js} +1 -1
  86. package/dist/public/{shadow-claw-notifications-DV2wibL3.js → shadow-claw-notifications-BkxuDEQI.js} +3 -3
  87. package/dist/public/{shadow-claw-page-header-B63S4HTU.js → shadow-claw-page-header-DMKbkv3s.js} +1 -1
  88. package/dist/public/{shadow-claw-pages-DE3jWj5K.js → shadow-claw-pages-BWSE91I1.js} +1 -1
  89. package/dist/public/{shadow-claw-settings-S6DAKfYx.js → shadow-claw-settings-D6lPBn6m.js} +10 -3
  90. package/dist/public/{shadow-claw-storage-DaacA3_K.js → shadow-claw-storage-Crs6LY15.js} +2 -2
  91. package/dist/public/{shadow-claw-task-server-IjKX042p.js → shadow-claw-task-server-CKm_Ennl.js} +25 -4
  92. package/dist/public/{shadow-claw-tasks-Cy0JYmGU.js → shadow-claw-tasks-Czx6Ucf5.js} +1 -1
  93. package/dist/public/{shadow-claw-terminal-znAt7HyP.js → shadow-claw-terminal-Dmtr9KY1.js} +1 -1
  94. package/dist/public/{shadow-claw-tools-Cutv9Si5.js → shadow-claw-tools-t3Qq4TDO.js} +1 -1
  95. package/dist/public/{shadow-claw-webvm-BH8mPDEu.js → shadow-claw-webvm-CIuSywD_.js} +1 -1
  96. package/dist/public/{syncWebMcpRegistration-BqJxaMGR.js → syncWebMcpRegistration-DzC80wVG.js} +1 -1
  97. package/dist/server.js +286 -189
  98. package/package.json +2 -1
  99. package/src/__mocks__/jszip.cjs +15 -5
  100. package/src/components/settings/shadow-claw-accounts/shadow-claw-accounts.test.ts +35 -0
  101. package/src/components/settings/shadow-claw-control-plane/shadow-claw-control-plane.css +117 -0
  102. package/src/components/settings/shadow-claw-control-plane/shadow-claw-control-plane.html +81 -0
  103. package/src/components/settings/shadow-claw-control-plane/shadow-claw-control-plane.test.ts +127 -0
  104. package/src/components/settings/shadow-claw-control-plane/shadow-claw-control-plane.ts +292 -0
  105. package/src/components/settings/shadow-claw-git/shadow-claw-git.test.ts +72 -0
  106. package/src/components/settings/shadow-claw-integrations/connection-test-auth.test.ts +20 -30
  107. package/src/components/settings/shadow-claw-integrations/shadow-claw-integrations.test.ts +116 -0
  108. package/src/components/settings/shadow-claw-llm/model-ranking.test.ts +143 -51
  109. package/src/components/settings/shadow-claw-llm/shadow-claw-llm.test.ts +307 -4
  110. package/src/components/settings/shadow-claw-llm/shadow-claw-llm.ts +8 -8
  111. package/src/components/settings/shadow-claw-mcp-remote/shadow-claw-mcp-remote.test.ts +31 -0
  112. package/src/components/settings/shadow-claw-notifications/shadow-claw-notifications.test.ts +3 -0
  113. package/src/components/settings/shadow-claw-notifications/shadow-claw-notifications.ts +43 -9
  114. package/src/components/settings/shadow-claw-peerjs/shadow-claw-peerjs.test.ts +186 -0
  115. package/src/components/settings/shadow-claw-storage/shadow-claw-storage.test.ts +76 -0
  116. package/src/components/settings/shadow-claw-task-server/shadow-claw-task-server.css +23 -2
  117. package/src/components/settings/shadow-claw-task-server/shadow-claw-task-server.html +1 -1
  118. package/src/components/settings/shadow-claw-task-server/shadow-claw-task-server.test.ts +19 -0
  119. package/src/components/settings/shadow-claw-task-server/shadow-claw-task-server.ts +2 -1
  120. package/src/components/shadow-claw/utils/initChatSplitResize.test.ts +180 -13
  121. package/src/components/shadow-claw/utils/setupEffects.test.ts +39 -0
  122. package/src/components/shadow-claw-a2ui/catalog/basic/shared.test.ts +117 -0
  123. package/src/components/shadow-claw-a2ui/shadow-claw-a2ui.test.ts +1159 -1
  124. package/src/components/shadow-claw-chat/shadow-claw-chat.test.ts +1523 -19
  125. package/src/components/shadow-claw-chat/utils/escapeHtml.test.ts +13 -0
  126. package/src/components/shadow-claw-chat/utils/getPeerChatDisplayStatus.test.ts +20 -0
  127. package/src/components/shadow-claw-conversations/shadow-claw-conversations.test.ts +494 -0
  128. package/src/components/shadow-claw-dialog/shadow-claw-dialog.ts +13 -2
  129. package/src/components/shadow-claw-file-viewer/shadow-claw-file-viewer.test.ts +273 -0
  130. package/src/components/shadow-claw-files/shadow-claw-files.test.ts +408 -1
  131. package/src/components/shadow-claw-pdf-viewer/utils/installGetOrInsertComputedPolyfill.test.ts +65 -0
  132. package/src/components/shadow-claw-settings/shadow-claw-settings.html +7 -0
  133. package/src/components/shadow-claw-settings/shadow-claw-settings.test.ts +221 -0
  134. package/src/components/shadow-claw-settings/shadow-claw-settings.ts +2 -0
  135. package/src/components/shadow-claw-tasks/shadow-claw-tasks.test.ts +407 -0
  136. package/src/components/shadow-claw-terminal/utils/consumeEscapeSequence.test.ts +58 -0
  137. package/src/components/shadow-claw-tools/shadow-claw-tools.test.ts +80 -0
  138. package/src/config/config.ts +10 -0
  139. package/src/core/backup-controller.test.ts +101 -0
  140. package/src/core/backup-controller.ts +166 -0
  141. package/src/core/control-plane-client.test.ts +415 -0
  142. package/src/core/control-plane-client.ts +441 -0
  143. package/src/core/orchestrator/orchestrator.ts +4 -0
  144. package/src/core/orchestrator/utils/compactContext.test.ts +78 -0
  145. package/src/core/orchestrator/utils/operations/channel.test.ts +254 -9
  146. package/src/core/orchestrator/utils/operations/provider.test.ts +326 -34
  147. package/src/core/orchestrator/utils/operations/task.ts +46 -15
  148. package/src/core/orchestrator/utils/operations/vm.test.ts +114 -2
  149. package/src/core/orchestrator/utils/syncProxyConfigToServiceWorker.test.ts +60 -0
  150. package/src/core/utils/initControlPlane.test.ts +276 -0
  151. package/src/core/utils/initControlPlane.ts +437 -0
  152. package/src/core/utils/initializeApp.ts +18 -0
  153. package/src/db/getSession.test.ts +13 -1
  154. package/src/server/app.test.ts +12 -0
  155. package/src/server/app.ts +20 -8
  156. package/src/server/client-registry.test.ts +250 -0
  157. package/src/server/client-registry.ts +477 -0
  158. package/src/server/config.ts +15 -0
  159. package/src/server/control-plane-types.ts +120 -0
  160. package/src/server/control-plane.test.ts +508 -0
  161. package/src/server/control-plane.ts +607 -0
  162. package/src/server/middleware/pna.test.ts +15 -3
  163. package/src/server/middleware/pna.ts +6 -2
  164. package/src/server/routes/backup.test.ts +277 -0
  165. package/src/server/routes/backup.ts +291 -0
  166. package/src/server/routes/integrations-email.test.ts +532 -0
  167. package/src/server/routes/llamafile.test.ts +172 -48
  168. package/src/server/routes/mesh-llm.test.ts +192 -0
  169. package/src/server/routes/ollama.test.ts +49 -0
  170. package/src/server/server-peer.test.ts +86 -0
  171. package/src/server/server-peer.ts +330 -0
  172. package/src/server/server.ts +37 -0
  173. package/src/server/services/llamafile-manager.test.ts +230 -6
  174. package/src/server/services/transformers-runtime.test.ts +186 -18
  175. package/src/server/webrtc.test.ts +21 -0
  176. package/src/server/webrtc.ts +72 -0
  177. package/src/service-worker/fetch-proxy-rules.test.ts +41 -0
  178. package/src/service-worker/fetch-proxy-rules.ts +15 -8
  179. package/src/service-worker/fetch-proxy.test.ts +64 -1
  180. package/src/service-worker/fetch-proxy.ts +18 -2
  181. package/src/service-worker/push-handler.ts +39 -0
  182. package/src/shell/vm.test.ts +744 -12
  183. package/src/storage/ensureMainGroupIndex.test.ts +153 -0
  184. package/src/storage/getGroupFile.test.ts +66 -0
  185. package/src/storage/memoryStorage.test.ts +82 -2
  186. package/src/storage/writeGroupFileBytes.test.ts +143 -0
  187. package/src/stores/chat-ui.test.ts +20 -0
  188. package/src/stores/orchestrator.test.ts +134 -0
  189. package/src/stores/toast.test.ts +50 -0
  190. package/src/stores/tools.test.ts +147 -10
  191. package/src/subsystems/channels/imessage.test.ts +59 -0
  192. package/src/subsystems/channels/peerjs.test.ts +500 -62
  193. package/src/subsystems/channels/peerjs.ts +71 -4
  194. package/src/subsystems/channels/telegram.test.ts +177 -0
  195. package/src/subsystems/email/catalog.test.ts +1 -0
  196. package/src/subsystems/email/connections.test.ts +39 -1
  197. package/src/subsystems/git/credentials.test.ts +160 -825
  198. package/src/subsystems/git/git.test.ts +463 -0
  199. package/src/subsystems/notifications/__mocks__/node-sqlite.cjs +12 -1
  200. package/src/subsystems/notifications/push-client.test.ts +5 -1
  201. package/src/subsystems/notifications/push-client.ts +50 -12
  202. package/src/subsystems/notifications/push-routes.test.ts +33 -0
  203. package/src/subsystems/notifications/push-routes.ts +23 -0
  204. package/src/subsystems/notifications/push-store.ts +1 -1
  205. package/src/subsystems/providers/builtin-ai-tasks.test.ts +74 -0
  206. package/src/subsystems/providers/litert-lm-provider.test.ts +212 -51
  207. package/src/subsystems/providers/model-registry.test.ts +115 -0
  208. package/src/subsystems/providers/providers.test.ts +94 -1
  209. package/src/subsystems/providers/transformers-js-provider.test.ts +279 -0
  210. package/src/subsystems/providers/utils/createModelCacheFetch.test.ts +2 -2
  211. package/src/subsystems/providers/utils/downloadModelToCache.test.ts +2 -2
  212. package/src/subsystems/providers/utils/loadModelStream.test.ts +2 -2
  213. package/src/subsystems/skills/activateSkill.test.ts +101 -0
  214. package/src/subsystems/skills/discoverSkills.test.ts +251 -0
  215. package/src/subsystems/tools/cron.test.ts +64 -0
  216. package/src/subsystems/tools/declarative.test.ts +255 -89
  217. package/src/testing/assets/v86.9pfs/libv86.mjs +63 -0
  218. package/src/testing/assets/v86.ext2/libv86.mjs +3 -0
  219. package/src/testing/assets_missing_v86/assets/v86.9pfs/libv86.mjs +1 -0
  220. package/src/testing/jest-setup.ts +328 -40
  221. package/src/testing/mock-v86.mjs +49 -0
  222. package/src/ui/a2ui/types.ts +4 -3
  223. package/src/ui/a2ui/utils/normaliseComponentsToMap.test.ts +102 -0
  224. package/src/ui/a2ui/utils/resolveChildIds.test.ts +63 -0
  225. package/src/ui/a2ui/utils/resolveDynamicNumber.test.ts +13 -1
  226. package/src/worker/tools/bash/utils/waitForVMReady.test.ts +40 -0
  227. package/src/worker/tools/email/email.test.ts +193 -8
  228. package/src/worker/tools/email/utils/asEmailAttachmentInputs.test.ts +47 -0
  229. package/src/worker/tools/git/git.test.ts +214 -3
  230. package/src/worker/tools/rooms/invite-to-room.test.ts +54 -0
  231. package/src/worker/tools/rooms/leave-room.test.ts +40 -0
  232. package/src/worker/tools/rooms/list-room-members.test.ts +75 -0
  233. package/src/worker/tools/tasks/tasks-utils.test.ts +22 -0
  234. package/src/worker/tools/ui/ask-user.test.ts +50 -0
  235. package/src/worker/tools/ui/clear-chat.test.ts +19 -0
  236. package/src/worker/tools/ui/get-current-time.test.ts +19 -0
  237. package/src/worker/tools/ui/javascript.test.ts +116 -0
  238. package/src/worker/tools/ui/list-components.test.ts +10 -0
  239. package/src/worker/tools/ui/list-tool-profiles.test.ts +42 -0
  240. package/src/worker/tools/ui/manage-tools.test.ts +34 -0
  241. package/src/worker/tools/ui/render-component.test.ts +346 -0
  242. package/src/worker/tools/ui/send-notification.test.ts +40 -0
  243. package/src/worker/tools/ui/utils/getAllowFullInternetAccess.test.ts +31 -0
  244. package/src/worker/tools/ui/utils/parseBooleanConfig.test.ts +25 -0
  245. package/src/worker/tools/workspace/attach-file.test.ts +84 -0
  246. package/src/worker/tools/workspace/copy-file.test.ts +69 -0
  247. package/src/worker/tools/workspace/create-directory.test.ts +40 -0
  248. package/src/worker/tools/workspace/delete-file.test.ts +73 -0
  249. package/src/worker/tools/workspace/diff-files.test.ts +94 -0
  250. package/src/worker/tools/workspace/list-files.test.ts +36 -0
  251. package/src/worker/tools/workspace/move-file.test.ts +66 -0
  252. package/src/worker/tools/workspace/open-file.test.ts +57 -0
  253. package/src/worker/tools/workspace/patch-file.test.ts +81 -0
  254. package/src/worker/tools/workspace/read-file.test.ts +116 -0
  255. package/src/worker/tools/workspace/send-file.test.ts +82 -0
  256. package/src/worker/tools/workspace/update-memory.test.ts +29 -0
  257. package/src/worker/tools/workspace/write-file.test.ts +28 -0
  258. package/src/worker/utils/rate-limit.test.ts +199 -0
  259. package/src/worker/utils/tool-state.test.ts +29 -0
  260. package/src/worker/utils/transformers-js-utils.test.ts +59 -0
  261. package/dist/public/config-BYAuxx3j.js +0 -1
  262. package/dist/public/downloadGroupFile-Drdvg1Ev.js +0 -1
  263. package/dist/public/file-viewer-CcZYw-PS.js +0 -1
  264. package/dist/public/orchestrator-o9Fj67BN.js +0 -15
  265. package/dist/public/push-client-Dii-vPEh.js +0 -1
  266. package/dist/public/shadow-claw-dialog-ByyHgxM9.js +0 -1
  267. package/dist/public/shadow-claw-files-BpfpJIuP.js +0 -840
@@ -0,0 +1,441 @@
1
+ /**
2
+ * ShadowClaw — Browser Control Plane Client
3
+ *
4
+ * Supports dual transport:
5
+ * 1. "sse" (default): HTTP Server-Sent Events (GET /api/control/events) for
6
+ * server-to-client commands + HTTP POST (/api/control/messages) for client-to-server.
7
+ * Highly proxy-, CDN-, and firewall-compatible.
8
+ * 2. "websocket": Full-duplex WebSocket connection to `/ws/control`.
9
+ */
10
+
11
+ import type {
12
+ ControlMessage,
13
+ ClientRegisterPayload,
14
+ HeartbeatPayload,
15
+ CommandExecutePayload,
16
+ CommandResultPayload,
17
+ ControlPlaneTransport,
18
+ } from "../server/control-plane-types.js";
19
+ import { ulid } from "../utils/ulid.js";
20
+
21
+ export type CommandHandler = (args: any) => Promise<any> | any;
22
+
23
+ export interface ControlPlaneClientOptions {
24
+ transport?: ControlPlaneTransport;
25
+ url?: string;
26
+ httpUrl?: string;
27
+ token?: string;
28
+ clientId: string;
29
+ deviceLabel?: string;
30
+ capabilities?: string[];
31
+ version?: string;
32
+ peerId?: string;
33
+ heartbeatIntervalMs?: number;
34
+ reconnectDelayMs?: number;
35
+ maxReconnectDelayMs?: number;
36
+ handlers?: Record<string, CommandHandler>;
37
+ WebSocketClass?: any;
38
+ EventSourceClass?: any;
39
+ fetchFn?: typeof fetch;
40
+ }
41
+
42
+ export class ControlPlaneClient {
43
+ private _transport: ControlPlaneTransport;
44
+ private _url: string;
45
+ private _httpUrl: string;
46
+ private _token?: string;
47
+ private _clientId: string;
48
+ private _peerId?: string;
49
+ private _deviceLabel: string;
50
+ private _capabilities: string[];
51
+ private _version: string;
52
+ private _heartbeatIntervalMs: number;
53
+ private _reconnectDelayMs: number;
54
+ private _maxReconnectDelayMs: number;
55
+ private _handlers: Map<string, CommandHandler>;
56
+ private _WebSocketClass: any;
57
+ private _EventSourceClass: any;
58
+ private _fetchFn: typeof fetch;
59
+
60
+ private _ws: WebSocket | null = null;
61
+ private _es: any = null;
62
+ private _heartbeatTimer: any = null;
63
+ private _reconnectTimer: any = null;
64
+ private _currentReconnectDelay: number;
65
+ private _isDestroyed: boolean = false;
66
+ private _state: "disconnected" | "connecting" | "connected" = "disconnected";
67
+
68
+ constructor(options: ControlPlaneClientOptions) {
69
+ this._transport = options.transport || "sse";
70
+ this._clientId = options.clientId;
71
+ this._peerId = options.peerId;
72
+ this._deviceLabel = options.deviceLabel || "ShadowClaw Browser Client";
73
+ this._capabilities = options.capabilities || ["webmcp", "opfs", "push"];
74
+ this._version = options.version || "1.23.4";
75
+ this._token = options.token;
76
+ this._heartbeatIntervalMs = options.heartbeatIntervalMs || 10000;
77
+ this._reconnectDelayMs = options.reconnectDelayMs || 1000;
78
+ this._maxReconnectDelayMs = options.maxReconnectDelayMs || 30000;
79
+ this._currentReconnectDelay = this._reconnectDelayMs;
80
+ this._handlers = new Map();
81
+
82
+ this._WebSocketClass =
83
+ options.WebSocketClass ||
84
+ (typeof WebSocket !== "undefined" ? WebSocket : null);
85
+ this._EventSourceClass =
86
+ options.EventSourceClass ||
87
+ (typeof EventSource !== "undefined" ? EventSource : null);
88
+ this._fetchFn =
89
+ options.fetchFn ||
90
+ (typeof fetch !== "undefined"
91
+ ? fetch.bind(globalThis)
92
+ : ((() => Promise.reject(new Error("fetch not available"))) as any));
93
+
94
+ if (options.handlers) {
95
+ for (const [action, handler] of Object.entries(options.handlers)) {
96
+ this.registerHandler(action, handler);
97
+ }
98
+ }
99
+
100
+ const loc = typeof location !== "undefined" ? location : null;
101
+ const origin = loc
102
+ ? `${loc.protocol}//${loc.host}`
103
+ : "http://127.0.0.1:8888";
104
+ const wsOrigin = loc
105
+ ? `${loc.protocol === "https:" ? "wss:" : "ws:"}//${loc.host}`
106
+ : "ws://127.0.0.1:8888";
107
+
108
+ this._url = options.url || `${wsOrigin}/ws/control`;
109
+ this._httpUrl = options.httpUrl || origin;
110
+ }
111
+
112
+ public get transport(): ControlPlaneTransport {
113
+ return this._transport;
114
+ }
115
+
116
+ public registerHandler(action: string, handler: CommandHandler): void {
117
+ this._handlers.set(action, handler);
118
+ }
119
+
120
+ public unregisterHandler(action: string): void {
121
+ this._handlers.delete(action);
122
+ }
123
+
124
+ public getState(): "disconnected" | "connecting" | "connected" {
125
+ return this._state;
126
+ }
127
+
128
+ public connect(): void {
129
+ if (
130
+ this._isDestroyed ||
131
+ this._state === "connected" ||
132
+ this._state === "connecting"
133
+ ) {
134
+ return;
135
+ }
136
+
137
+ if (this._transport === "websocket") {
138
+ this._connectWebSocket();
139
+ } else {
140
+ this._connectSse();
141
+ }
142
+ }
143
+
144
+ private _connectWebSocket(): void {
145
+ if (!this._WebSocketClass) {
146
+ console.warn(
147
+ "[ControlPlaneClient] WebSocket not supported in this environment",
148
+ );
149
+ return;
150
+ }
151
+
152
+ this._state = "connecting";
153
+ const wsUrl = new URL(this._url, "ws://127.0.0.1:8888");
154
+ if (this._token) {
155
+ wsUrl.searchParams.set("token", this._token);
156
+ }
157
+
158
+ try {
159
+ const ws = new this._WebSocketClass(wsUrl.toString());
160
+ this._ws = ws;
161
+
162
+ ws.onopen = () => {
163
+ this._state = "connected";
164
+ this._currentReconnectDelay = this._reconnectDelayMs;
165
+ this._sendRegister();
166
+ this._startHeartbeat();
167
+ };
168
+
169
+ ws.onmessage = (event: MessageEvent) => {
170
+ this._handleMessage(event.data);
171
+ };
172
+
173
+ ws.onclose = () => {
174
+ this._cleanupConnection();
175
+ if (!this._isDestroyed) {
176
+ this._scheduleReconnect();
177
+ }
178
+ };
179
+
180
+ ws.onerror = (err: any) => {
181
+ console.warn("[ControlPlaneClient] WebSocket error:", err);
182
+ };
183
+ } catch (err) {
184
+ console.warn(
185
+ "[ControlPlaneClient] Failed to establish WebSocket connection:",
186
+ err,
187
+ );
188
+ this._cleanupConnection();
189
+ this._scheduleReconnect();
190
+ }
191
+ }
192
+
193
+ private _connectSse(): void {
194
+ if (!this._EventSourceClass) {
195
+ if (typeof process === "undefined" || !process.env?.JEST_WORKER_ID) {
196
+ console.warn(
197
+ "[ControlPlaneClient] EventSource not supported in this environment",
198
+ );
199
+ }
200
+ return;
201
+ }
202
+
203
+ this._state = "connecting";
204
+ const sseUrl = new URL("/api/control/events", this._httpUrl);
205
+ sseUrl.searchParams.set("clientId", this._clientId);
206
+ if (this._token) {
207
+ sseUrl.searchParams.set("token", this._token);
208
+ }
209
+
210
+ try {
211
+ const es = new this._EventSourceClass(sseUrl.toString());
212
+ this._es = es;
213
+
214
+ es.onopen = () => {
215
+ this._state = "connected";
216
+ this._currentReconnectDelay = this._reconnectDelayMs;
217
+ this._sendRegister();
218
+ this._startHeartbeat();
219
+ };
220
+
221
+ if (typeof es.addEventListener === "function") {
222
+ es.addEventListener("command:execute", (event: MessageEvent) => {
223
+ this._handleMessage(event.data);
224
+ });
225
+ }
226
+
227
+ es.onmessage = (event: MessageEvent) => {
228
+ this._handleMessage(event.data);
229
+ };
230
+
231
+ es.onerror = (err: any) => {
232
+ console.warn("[ControlPlaneClient] SSE connection error:", err);
233
+ this._cleanupConnection();
234
+ if (!this._isDestroyed) {
235
+ this._scheduleReconnect();
236
+ }
237
+ };
238
+ } catch (err) {
239
+ console.warn(
240
+ "[ControlPlaneClient] Failed to establish SSE connection:",
241
+ err,
242
+ );
243
+ this._cleanupConnection();
244
+ this._scheduleReconnect();
245
+ }
246
+ }
247
+
248
+ public disconnect(): void {
249
+ this._isDestroyed = true;
250
+ this._cleanupConnection();
251
+ if (this._reconnectTimer) {
252
+ clearTimeout(this._reconnectTimer);
253
+ this._reconnectTimer = null;
254
+ }
255
+ }
256
+
257
+ private _cleanupConnection(): void {
258
+ this._state = "disconnected";
259
+ this._stopHeartbeat();
260
+ if (this._ws) {
261
+ try {
262
+ this._ws.close();
263
+ } catch (_) {}
264
+ this._ws = null;
265
+ }
266
+ if (this._es) {
267
+ try {
268
+ this._es.close();
269
+ } catch (_) {}
270
+ this._es = null;
271
+ }
272
+ }
273
+
274
+ private _scheduleReconnect(): void {
275
+ if (this._reconnectTimer || this._isDestroyed) {
276
+ return;
277
+ }
278
+
279
+ this._reconnectTimer = setTimeout(() => {
280
+ this._reconnectTimer = null;
281
+ if (!this._isDestroyed) {
282
+ this.connect();
283
+ }
284
+ }, this._currentReconnectDelay);
285
+
286
+ this._currentReconnectDelay = Math.min(
287
+ this._currentReconnectDelay * 1.5,
288
+ this._maxReconnectDelayMs,
289
+ );
290
+ }
291
+
292
+ private _startHeartbeat(): void {
293
+ this._stopHeartbeat();
294
+ this._heartbeatTimer = setInterval(() => {
295
+ this._sendHeartbeat();
296
+ }, this._heartbeatIntervalMs);
297
+ }
298
+
299
+ private _stopHeartbeat(): void {
300
+ if (this._heartbeatTimer) {
301
+ clearInterval(this._heartbeatTimer);
302
+ this._heartbeatTimer = null;
303
+ }
304
+ }
305
+
306
+ private _sendRegister(): void {
307
+ const payload: ClientRegisterPayload = {
308
+ clientId: this._clientId,
309
+ deviceLabel: this._deviceLabel,
310
+ capabilities: this._capabilities,
311
+ version: this._version,
312
+ transport: this._transport,
313
+ peerId: this._peerId,
314
+ };
315
+ this._sendMessage({
316
+ id: ulid(),
317
+ type: "client:register",
318
+ payload,
319
+ });
320
+ }
321
+
322
+ private _sendHeartbeat(): void {
323
+ const payload: HeartbeatPayload = {
324
+ clientId: this._clientId,
325
+ timestamp: Date.now(),
326
+ };
327
+ this._sendMessage({
328
+ id: ulid(),
329
+ type: "client:heartbeat",
330
+ payload,
331
+ });
332
+ }
333
+
334
+ private _sendMessage(msg: ControlMessage): void {
335
+ if (this._transport === "websocket") {
336
+ if (
337
+ this._ws &&
338
+ (this._ws.readyState === 1 ||
339
+ this._ws.readyState === (this._WebSocketClass as any)?.OPEN)
340
+ ) {
341
+ this._ws.send(JSON.stringify(msg));
342
+ }
343
+ return;
344
+ }
345
+
346
+ // SSE Mode: send messages to server via HTTP POST /api/control/messages
347
+ const messagesUrl = new URL("/api/control/messages", this._httpUrl);
348
+ const headers: Record<string, string> = {
349
+ "Content-Type": "application/json",
350
+ };
351
+ if (this._token) {
352
+ headers["x-control-token"] = this._token;
353
+ headers["Authorization"] = `Bearer ${this._token}`;
354
+ }
355
+
356
+ const fetchOptions: any = {
357
+ method: "POST",
358
+ headers,
359
+ body: JSON.stringify(msg),
360
+ };
361
+
362
+ const host = messagesUrl.hostname.toLowerCase();
363
+ const isLoopback =
364
+ host === "localhost" ||
365
+ host === "127.0.0.1" ||
366
+ host === "::1" ||
367
+ host === "[::1]";
368
+ const isPrivate = /^(10\.|172\.(1[6-9]|2\d|3[01])\.|192\.168\.)/.test(host);
369
+
370
+ if (isLoopback) {
371
+ fetchOptions.targetAddressSpace = "loopback";
372
+ } else if (isPrivate) {
373
+ fetchOptions.targetAddressSpace = "private";
374
+ }
375
+
376
+ this._fetchFn(messagesUrl.toString(), fetchOptions).catch((err) => {
377
+ console.warn(
378
+ "[ControlPlaneClient] Failed to send message via HTTP POST:",
379
+ err,
380
+ );
381
+ });
382
+ }
383
+
384
+ private async _handleMessage(dataStr: string): Promise<void> {
385
+ if (!dataStr || typeof dataStr !== "string") {
386
+ return;
387
+ }
388
+
389
+ let msg: ControlMessage;
390
+ try {
391
+ msg = JSON.parse(dataStr);
392
+ } catch {
393
+ return;
394
+ }
395
+
396
+ if (msg.type === "command:execute") {
397
+ const payload = msg.payload as CommandExecutePayload;
398
+ const { commandId, action, args } = payload;
399
+
400
+ const handler = this._handlers.get(action);
401
+ if (!handler) {
402
+ this._sendMessage({
403
+ id: ulid(),
404
+ type: "command:result",
405
+ replyTo: msg.id,
406
+ payload: {
407
+ commandId,
408
+ success: false,
409
+ error: `Unknown action: ${action}`,
410
+ } as CommandResultPayload,
411
+ });
412
+ return;
413
+ }
414
+
415
+ try {
416
+ const result = await handler(args);
417
+ this._sendMessage({
418
+ id: ulid(),
419
+ type: "command:result",
420
+ replyTo: msg.id,
421
+ payload: {
422
+ commandId,
423
+ success: true,
424
+ data: result,
425
+ } as CommandResultPayload,
426
+ });
427
+ } catch (err: any) {
428
+ this._sendMessage({
429
+ id: ulid(),
430
+ type: "command:result",
431
+ replyTo: msg.id,
432
+ payload: {
433
+ commandId,
434
+ success: false,
435
+ error: err.message || String(err),
436
+ } as CommandResultPayload,
437
+ });
438
+ }
439
+ }
440
+ }
441
+ }
@@ -699,4 +699,8 @@ export class Orchestrator {
699
699
 
700
700
  await setConfig(db, getProviderApiKeyConfigKey(this.provider), encrypted);
701
701
  }
702
+
703
+ submitMessage(text: string, groupId: string = DEFAULT_GROUP_ID): void {
704
+ this.browserChat.submit(text, groupId);
705
+ }
702
706
  }
@@ -41,6 +41,37 @@ jest.unstable_mockModule("../../../db/groups.js", () => ({
41
41
  .mockResolvedValue(undefined),
42
42
  }));
43
43
 
44
+ jest.unstable_mockModule(
45
+ "../../../subsystems/providers/builtin-ai-tasks.js",
46
+ () => ({
47
+ ensureBuiltinAiPolyfills: jest.fn<any>().mockResolvedValue(undefined),
48
+ summarizeText: jest
49
+ .fn<any>()
50
+ .mockResolvedValue("Mock summary from Task API"),
51
+ writeText: jest.fn<any>().mockResolvedValue(""),
52
+ rewriteText: jest.fn<any>().mockResolvedValue(""),
53
+ detectLanguage: jest.fn<any>().mockResolvedValue([]),
54
+ translateText: jest.fn<any>().mockResolvedValue(""),
55
+ proofreadText: jest.fn<any>().mockResolvedValue(""),
56
+ embedText: jest.fn<any>().mockResolvedValue([]),
57
+ isBuiltinTaskSupported: jest.fn(() => true),
58
+ getPromptApiFallbackModel: jest.fn<any>().mockResolvedValue(""),
59
+ createTaskInstanceWithFallback: jest.fn<any>().mockResolvedValue({}),
60
+ isWebGpuAdapterAvailable: jest.fn<any>().mockResolvedValue(false),
61
+ }),
62
+ );
63
+
64
+ jest.unstable_mockModule(
65
+ "../../../subsystems/providers/prompt-api-provider.js",
66
+ () => ({
67
+ isPromptApiSupported: jest.fn<any>().mockReturnValue(true),
68
+ compactWithPromptApi: jest
69
+ .fn<any>()
70
+ .mockResolvedValue("Mock prompt API summary"),
71
+ invokeWithPromptApi: jest.fn<any>().mockResolvedValue(undefined),
72
+ }),
73
+ );
74
+
44
75
  describe("compactContext", () => {
45
76
  let db: any;
46
77
  let o: Orchestrator;
@@ -113,4 +144,51 @@ describe("compactContext", () => {
113
144
  expect(payload.payload.provider).toBe("transformers_js_local");
114
145
  expect(payload.payload.model).toBe("onnx-community/Llama-3.2-1B-Instruct");
115
146
  });
147
+
148
+ it("handles compactionPref === 'builtin_task_api'", async () => {
149
+ jest.spyOn(o, "getApiKey").mockResolvedValue("key");
150
+ const { getConfig } = await import("../../../db/getConfig.js");
151
+ (getConfig as jest.Mock<any>).mockImplementation(
152
+ (_db: any, key: string) => {
153
+ if (key === "compaction_engine_preference") {
154
+ return Promise.resolve("builtin_task_api");
155
+ }
156
+ return Promise.resolve(null);
157
+ },
158
+ );
159
+
160
+ const { buildConversationMessages } =
161
+ await import("../../../db/buildConversationMessages.js");
162
+ (buildConversationMessages as jest.Mock<any>).mockResolvedValue([
163
+ { role: "user", content: "Hi" },
164
+ { role: "assistant", content: "Hello" },
165
+ ]);
166
+
167
+ o.handleCompactDone = jest.fn<any>().mockResolvedValue(undefined);
168
+
169
+ await compactContext(o, db, "group-1");
170
+
171
+ expect(o.handleCompactDone).toHaveBeenCalledWith(
172
+ db,
173
+ "group-1",
174
+ "Mock summary from Task API",
175
+ );
176
+ });
177
+
178
+ it("handles effectiveProviderId === 'prompt_api'", async () => {
179
+ const { getConfig } = await import("../../../db/getConfig.js");
180
+ (getConfig as jest.Mock<any>).mockResolvedValue(null);
181
+
182
+ o.provider = "prompt_api";
183
+ o.providerConfig = { requiresApiKey: false } as any;
184
+ o.handleCompactDone = jest.fn<any>().mockResolvedValue(undefined);
185
+
186
+ await compactContext(o, db, "group-1");
187
+
188
+ expect(o.handleCompactDone).toHaveBeenCalledWith(
189
+ db,
190
+ "group-1",
191
+ "Mock prompt API summary",
192
+ );
193
+ });
116
194
  });