moi-computer 0.13.1-next.3 → 0.13.1-next.5

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 (665) hide show
  1. package/README.md +1 -1
  2. package/bin/moi.mjs +10 -6
  3. package/dist/{chunk-a865c7x4.js → chunk-0xy5nenk.js} +1 -1
  4. package/dist/chunk-4arsawe0.js +2 -0
  5. package/dist/chunk-5eb7n6xw.js +1 -0
  6. package/dist/chunk-6aq60rm2.js +5 -0
  7. package/dist/chunk-9ffaaaw3.css +1 -0
  8. package/dist/{chunk-xj1pjhng.js → chunk-9vy2z8hd.js} +1 -1
  9. package/dist/{chunk-r95acex1.js → chunk-cb2a4cjk.js} +78 -78
  10. package/dist/{chunk-f44cs6mw.js → chunk-ghyzbqgb.js} +2 -2
  11. package/dist/chunk-j3djs7ta.js +72 -0
  12. package/dist/chunk-v0w55vnq.js +2 -0
  13. package/dist/chunk-yff16m73.js +1 -0
  14. package/dist/dot-2bdkpg3k.png +0 -0
  15. package/dist/duet-3ab8xyzd.png +0 -0
  16. package/dist/grok-bot-yv07qj9f.png +0 -0
  17. package/dist/index.html +1 -1
  18. package/dist/instinct-ypmq6t0w.png +0 -0
  19. package/dist/muse-qr7zwsvf.png +0 -0
  20. package/package.json +39 -40
  21. package/runtime/applets/chunk-bzxakh65.js +2 -0
  22. package/runtime/applets/chunk-qhjskz2m.js +2 -0
  23. package/runtime/applets/collab.js +1 -0
  24. package/runtime/applets/moi.js +1 -0
  25. package/runtime/applets/rpc.js +2 -0
  26. package/runtime/assets/shadcn.css +629 -0
  27. package/runtime/assets/tw-animate.css +1 -0
  28. package/runtime/build-worker-entry.js +2 -0
  29. package/runtime/chunk-30dzwptp.js +2 -0
  30. package/runtime/chunk-4wj1jzhr.js +3 -0
  31. package/runtime/chunk-67h4jd69.js +78 -0
  32. package/runtime/chunk-7c0zbz74.js +3 -0
  33. package/runtime/chunk-8jg7v8y7.js +3 -0
  34. package/runtime/chunk-9dr0dhxj.js +83 -0
  35. package/runtime/chunk-ewc55jga.js +32623 -0
  36. package/runtime/chunk-f56xzjzw.js +26 -0
  37. package/runtime/chunk-fdbkvdht.js +128 -0
  38. package/runtime/chunk-g9saang0.js +3 -0
  39. package/runtime/chunk-ggphq7nk.js +66 -0
  40. package/runtime/chunk-hrtaxw37.js +3 -0
  41. package/runtime/chunk-j0nd7kw0.js +52 -0
  42. package/runtime/chunk-k049dtaq.js +3 -0
  43. package/runtime/chunk-kjp60rqs.js +3 -0
  44. package/runtime/chunk-mjwz158z.js +2 -0
  45. package/runtime/chunk-pt32r350.js +2 -0
  46. package/runtime/chunk-q06m17nb.js +3 -0
  47. package/runtime/chunk-q2t18c1t.js +3 -0
  48. package/runtime/chunk-sdyqhxe1.js +10 -0
  49. package/runtime/chunk-w1fx9tsc.js +3 -0
  50. package/runtime/chunk-zm7k0v1c.js +3 -0
  51. package/runtime/chunk-zwvtkb81.js +139 -0
  52. package/runtime/cli.js +246 -0
  53. package/runtime/functions-worker.js +2 -0
  54. package/runtime/gateway-client.js +2 -0
  55. package/runtime/third-party-notices.txt +6830 -0
  56. package/runtime/worker.js +2 -0
  57. package/runtime/xdg-open +1267 -0
  58. package/bunfig.toml +0 -7
  59. package/client/AGENTS.md +0 -40
  60. package/client/api/app-config.ts +0 -58
  61. package/client/api/http.ts +0 -44
  62. package/client/api/query-client.ts +0 -5
  63. package/client/api/query-options.ts +0 -6
  64. package/client/api/workspace-keys.ts +0 -18
  65. package/client/app/app-provider.tsx +0 -45
  66. package/client/app/app-router.tsx +0 -60
  67. package/client/app/routes/home-route.tsx +0 -27
  68. package/client/app/routes/onboarding-route.tsx +0 -11
  69. package/client/app/routes/settings-route.tsx +0 -10
  70. package/client/app/routes/workspace-registration.tsx +0 -68
  71. package/client/app/routes/workspace-route.tsx +0 -110
  72. package/client/app/shell/sidebar-layout.tsx +0 -252
  73. package/client/assets/claude.svg +0 -3
  74. package/client/assets/favicon.png +0 -0
  75. package/client/assets/floppy-disk.webp +0 -0
  76. package/client/assets/hermes.png +0 -0
  77. package/client/assets/mcp/.gitkeep +0 -0
  78. package/client/assets/mcp/airtable.png +0 -0
  79. package/client/assets/mcp/apollo.png +0 -0
  80. package/client/assets/mcp/asana.png +0 -0
  81. package/client/assets/mcp/atlassian.png +0 -0
  82. package/client/assets/mcp/box.png +0 -0
  83. package/client/assets/mcp/chrome.svg +0 -33
  84. package/client/assets/mcp/clickup.png +0 -0
  85. package/client/assets/mcp/cloudflare.png +0 -0
  86. package/client/assets/mcp/context7.png +0 -0
  87. package/client/assets/mcp/datadog.png +0 -0
  88. package/client/assets/mcp/discord.png +0 -0
  89. package/client/assets/mcp/dropbox.png +0 -0
  90. package/client/assets/mcp/elevenlabs.png +0 -0
  91. package/client/assets/mcp/exa.png +0 -0
  92. package/client/assets/mcp/figma.png +0 -0
  93. package/client/assets/mcp/firecrawl.png +0 -0
  94. package/client/assets/mcp/github.png +0 -0
  95. package/client/assets/mcp/gitlab.png +0 -0
  96. package/client/assets/mcp/gmail.png +0 -0
  97. package/client/assets/mcp/googlecalendar.png +0 -0
  98. package/client/assets/mcp/googledrive.png +0 -0
  99. package/client/assets/mcp/grafana.png +0 -0
  100. package/client/assets/mcp/granola.png +0 -0
  101. package/client/assets/mcp/hubspot.png +0 -0
  102. package/client/assets/mcp/huggingface.png +0 -0
  103. package/client/assets/mcp/intercom.png +0 -0
  104. package/client/assets/mcp/linear.png +0 -0
  105. package/client/assets/mcp/monday.png +0 -0
  106. package/client/assets/mcp/mongodb.png +0 -0
  107. package/client/assets/mcp/neon.png +0 -0
  108. package/client/assets/mcp/notion.png +0 -0
  109. package/client/assets/mcp/paper.png +0 -0
  110. package/client/assets/mcp/paypal.png +0 -0
  111. package/client/assets/mcp/perplexity.png +0 -0
  112. package/client/assets/mcp/postgresql.png +0 -0
  113. package/client/assets/mcp/posthog.png +0 -0
  114. package/client/assets/mcp/puppeteer.png +0 -0
  115. package/client/assets/mcp/railway.png +0 -0
  116. package/client/assets/mcp/redis.png +0 -0
  117. package/client/assets/mcp/salesforce.png +0 -0
  118. package/client/assets/mcp/sentry.png +0 -0
  119. package/client/assets/mcp/shopify.png +0 -0
  120. package/client/assets/mcp/slack.png +0 -0
  121. package/client/assets/mcp/snowflake.png +0 -0
  122. package/client/assets/mcp/stripe.png +0 -0
  123. package/client/assets/mcp/supabase.png +0 -0
  124. package/client/assets/mcp/telegram.png +0 -0
  125. package/client/assets/mcp/twilio.png +0 -0
  126. package/client/assets/mcp/vercel.png +0 -0
  127. package/client/assets/mcp/zapier.png +0 -0
  128. package/client/assets/moi-logo.svg +0 -11
  129. package/client/assets/openai.svg +0 -1
  130. package/client/assets/openclaw.svg +0 -22
  131. package/client/assets.d.ts +0 -14
  132. package/client/components/shared/agent-blobatar.tsx +0 -93
  133. package/client/components/shared/bottom-panel.tsx +0 -65
  134. package/client/components/shared/composer.tsx +0 -125
  135. package/client/components/shared/led-logo.tsx +0 -181
  136. package/client/components/shared/panel-header.tsx +0 -16
  137. package/client/components/shared/reorderable-list.tsx +0 -204
  138. package/client/components/shared/screen-shell.tsx +0 -23
  139. package/client/components/shared/ultrafast-icon.tsx +0 -61
  140. package/client/components/shared/workspace-icon.tsx +0 -83
  141. package/client/components/ui/alert-dialog.tsx +0 -1
  142. package/client/components/ui/button.tsx +0 -1
  143. package/client/components/ui/checkbox.tsx +0 -1
  144. package/client/components/ui/collapsible.tsx +0 -1
  145. package/client/components/ui/dialog.tsx +0 -1
  146. package/client/components/ui/dropdown-menu.tsx +0 -1
  147. package/client/components/ui/hover-card.tsx +0 -1
  148. package/client/components/ui/inline-input.tsx +0 -84
  149. package/client/components/ui/input.tsx +0 -1
  150. package/client/components/ui/popover.tsx +0 -1
  151. package/client/components/ui/resizable.tsx +0 -1
  152. package/client/components/ui/skeleton.tsx +0 -1
  153. package/client/components/ui/slider.tsx +0 -1
  154. package/client/components/ui/spinner.tsx +0 -1
  155. package/client/components/ui/switch.tsx +0 -1
  156. package/client/components/ui/tabs.tsx +0 -1
  157. package/client/components/ui/textarea.tsx +0 -1
  158. package/client/components/ui/toast.tsx +0 -220
  159. package/client/components/ui/tooltip.tsx +0 -1
  160. package/client/dev/index.html +0 -43
  161. package/client/dev/index.ts +0 -15
  162. package/client/externalize-react.ts +0 -41
  163. package/client/features/account/account-menu.tsx +0 -96
  164. package/client/features/account/account-provider.tsx +0 -93
  165. package/client/features/account/account-test-utils.tsx +0 -310
  166. package/client/features/account/api.ts +0 -67
  167. package/client/features/account/profile-actions.ts +0 -29
  168. package/client/features/app-settings/api.ts +0 -33
  169. package/client/features/app-settings/avatar-upload.tsx +0 -62
  170. package/client/features/app-settings/general-settings.tsx +0 -39
  171. package/client/features/app-settings/profile-settings.tsx +0 -105
  172. package/client/features/app-settings/settings-page.tsx +0 -45
  173. package/client/features/app-settings/settings-section.tsx +0 -26
  174. package/client/features/applets/api.ts +0 -38
  175. package/client/features/applets/applet-cache.ts +0 -96
  176. package/client/features/applets/applet-container.tsx +0 -33
  177. package/client/features/applets/applet-log.ts +0 -81
  178. package/client/features/applets/applet-runtime.ts +0 -325
  179. package/client/features/applets/applet-styles.ts +0 -81
  180. package/client/features/applets/applet-thumbnail.ts +0 -294
  181. package/client/features/applets/use-applet.ts +0 -212
  182. package/client/features/applets/widget-error-boundary.tsx +0 -62
  183. package/client/features/applets/widget-shell.tsx +0 -56
  184. package/client/features/chat/applet-chat-intents.ts +0 -173
  185. package/client/features/chat/chat-panel.tsx +0 -326
  186. package/client/features/chat/chat-popup.tsx +0 -175
  187. package/client/features/chat/chat-send.ts +0 -259
  188. package/client/features/chat/chat-store.ts +0 -328
  189. package/client/features/chat/composer/attachments/attachment-chip.tsx +0 -99
  190. package/client/features/chat/composer/attachments/draft-attachments.ts +0 -185
  191. package/client/features/chat/composer/attachments/drawing-attachment-chip.tsx +0 -37
  192. package/client/features/chat/composer/attachments/file-attachment-chip.tsx +0 -22
  193. package/client/features/chat/composer/attachments/text-attachment-chip.tsx +0 -11
  194. package/client/features/chat/composer/attachments/types.ts +0 -25
  195. package/client/features/chat/composer/attachments/uploads.ts +0 -26
  196. package/client/features/chat/composer/banners/composer-banner.tsx +0 -16
  197. package/client/features/chat/composer/banners/error-banner.tsx +0 -36
  198. package/client/features/chat/composer/banners/skill-update-banner.tsx +0 -93
  199. package/client/features/chat/composer/chat-composer.tsx +0 -290
  200. package/client/features/chat/composer/model-order.ts +0 -110
  201. package/client/features/chat/composer/model-picker.tsx +0 -408
  202. package/client/features/chat/composer/use-workspace-composer-state.tsx +0 -69
  203. package/client/features/chat/composer/use-workspace-skill-updates.ts +0 -160
  204. package/client/features/chat/connection/chat-connection.ts +0 -107
  205. package/client/features/chat/connection/chat-frames.ts +0 -165
  206. package/client/features/chat/messages/chat-empty-state.tsx +0 -294
  207. package/client/features/chat/messages/chat-prompt-bubbles.tsx +0 -72
  208. package/client/features/chat/messages/fork-history.ts +0 -14
  209. package/client/features/chat/messages/group-turns.ts +0 -74
  210. package/client/features/chat/messages/interleave-notices.ts +0 -80
  211. package/client/features/chat/messages/markdown-content.tsx +0 -89
  212. package/client/features/chat/messages/preview-turn.ts +0 -37
  213. package/client/features/chat/messages/shimmer-text.tsx +0 -20
  214. package/client/features/chat/messages/tool-group/code-block.tsx +0 -41
  215. package/client/features/chat/messages/tool-group/collapse.tsx +0 -28
  216. package/client/features/chat/messages/tool-group/detect.ts +0 -93
  217. package/client/features/chat/messages/tool-group/fixtures.ts +0 -309
  218. package/client/features/chat/messages/tool-group/format/claude.ts +0 -49
  219. package/client/features/chat/messages/tool-group/format/codex.ts +0 -130
  220. package/client/features/chat/messages/tool-group/format/hermes.ts +0 -69
  221. package/client/features/chat/messages/tool-group/format/index.ts +0 -34
  222. package/client/features/chat/messages/tool-group/format/mcp.ts +0 -68
  223. package/client/features/chat/messages/tool-group/format/openclaw.ts +0 -120
  224. package/client/features/chat/messages/tool-group/format/shared.ts +0 -49
  225. package/client/features/chat/messages/tool-group/format/shell.ts +0 -162
  226. package/client/features/chat/messages/tool-group/index.ts +0 -9
  227. package/client/features/chat/messages/tool-group/read-image-preview.tsx +0 -46
  228. package/client/features/chat/messages/tool-group/subagent-card.tsx +0 -138
  229. package/client/features/chat/messages/tool-group/timeline-row.tsx +0 -159
  230. package/client/features/chat/messages/tool-group/tool-call-group.tsx +0 -279
  231. package/client/features/chat/messages/tool-group/tool-output.tsx +0 -125
  232. package/client/features/chat/messages/turn-view.tsx +0 -270
  233. package/client/features/chat/messages/use-stick-to-bottom.ts +0 -96
  234. package/client/features/chat/messages/user-message-bubble.tsx +0 -63
  235. package/client/features/chat/sessions/api.ts +0 -193
  236. package/client/features/chat/sessions/chat-selector.tsx +0 -399
  237. package/client/features/chat/sessions/session-view.ts +0 -53
  238. package/client/features/chat/sessions/use-selected-session.ts +0 -171
  239. package/client/features/chat/use-chat.ts +0 -229
  240. package/client/features/collab/applet-api.ts +0 -35
  241. package/client/features/collab/components/cursors.tsx +0 -241
  242. package/client/features/collab/components/presence-avatars.tsx +0 -74
  243. package/client/features/collab/components/presence-frame.tsx +0 -122
  244. package/client/features/collab/components/presence-group.tsx +0 -31
  245. package/client/features/collab/components/presence-helpers.ts +0 -50
  246. package/client/features/collab/components/user-avatar-group.tsx +0 -35
  247. package/client/features/collab/components/user-avatar.tsx +0 -65
  248. package/client/features/collab/components/user.tsx +0 -69
  249. package/client/features/collab/host-state.ts +0 -160
  250. package/client/features/collab/index.ts +0 -5
  251. package/client/features/collab/local-user.ts +0 -46
  252. package/client/features/collab/members/api.ts +0 -17
  253. package/client/features/collab/members/hooks.ts +0 -97
  254. package/client/features/collab/members/store.ts +0 -148
  255. package/client/features/collab/members/types.ts +0 -55
  256. package/client/features/collab/presence/client.ts +0 -262
  257. package/client/features/collab/presence/hooks.tsx +0 -160
  258. package/client/features/collab/presence/presence-publisher.ts +0 -30
  259. package/client/features/collab/presence/presence-target.ts +0 -8
  260. package/client/features/collab/presence/provider.tsx +0 -68
  261. package/client/features/collab/presence/store.ts +0 -156
  262. package/client/features/collab/presence/users.ts +0 -87
  263. package/client/features/collab/proxy-user.ts +0 -28
  264. package/client/features/collab/sharing/agent-invite.tsx +0 -30
  265. package/client/features/collab/sharing/workspace-members.tsx +0 -269
  266. package/client/features/collab/sharing/workspace-sharing-menu.tsx +0 -179
  267. package/client/features/collab/testing/component-fixtures.tsx +0 -54
  268. package/client/features/collab/testing/fake-engine.ts +0 -120
  269. package/client/features/connectors/api.ts +0 -25
  270. package/client/features/connectors/icon-mcp.tsx +0 -21
  271. package/client/features/connectors/mcp-icons.ts +0 -183
  272. package/client/features/connectors/mcp-server-cards.tsx +0 -105
  273. package/client/features/connectors/read-connectors.ts +0 -35
  274. package/client/features/demo/demo-dialog.tsx +0 -194
  275. package/client/features/dev/blobatar-shapes-page.tsx +0 -344
  276. package/client/features/dev/chat-states-fixtures.ts +0 -755
  277. package/client/features/dev/chat-states-page.tsx +0 -476
  278. package/client/features/dev/collab/collab-page.tsx +0 -24
  279. package/client/features/dev/collab/collab-playground.tsx +0 -614
  280. package/client/features/dev/collab/local-user-settings.tsx +0 -120
  281. package/client/features/dev/collab/playground-room.ts +0 -33
  282. package/client/features/dev/dev-index-page.tsx +0 -83
  283. package/client/features/dev/dev-routes.tsx +0 -43
  284. package/client/features/dev/harness-debug-page.tsx +0 -607
  285. package/client/features/dev/onboarding-preview-page.tsx +0 -76
  286. package/client/features/dev/texture-lab-page.tsx +0 -149
  287. package/client/features/dev/tool-calls-page.tsx +0 -79
  288. package/client/features/dev/ui-components/ui-component-previews.tsx +0 -855
  289. package/client/features/dev/ui-components/ui-components-page.tsx +0 -60
  290. package/client/features/dev/workspace-setup-mocks.ts +0 -103
  291. package/client/features/dev/workspace-setup-page.tsx +0 -11
  292. package/client/features/dev/workspace-setup-preview.tsx +0 -249
  293. package/client/features/drawings/capture-element.ts +0 -57
  294. package/client/features/drawings/drawing-layer.tsx +0 -49
  295. package/client/features/drawings/drawing-toolbar.tsx +0 -95
  296. package/client/features/drawings/use-chat-annotation.ts +0 -228
  297. package/client/features/drawings/use-drawing-layer.ts +0 -756
  298. package/client/features/drawings/use-view-sketch.ts +0 -154
  299. package/client/features/harness/api.ts +0 -69
  300. package/client/features/harness/device-login-steps.tsx +0 -103
  301. package/client/features/harness/harness-login-panel.tsx +0 -232
  302. package/client/features/harness/harness-presentation.ts +0 -15
  303. package/client/features/harness/harness-selector.tsx +0 -119
  304. package/client/features/harness/use-harness-login.ts +0 -77
  305. package/client/features/home/api.ts +0 -135
  306. package/client/features/home/home-logo.tsx +0 -344
  307. package/client/features/home/home-page.tsx +0 -305
  308. package/client/features/home/shared-workspaces.tsx +0 -70
  309. package/client/features/home/workspace-invitations.tsx +0 -101
  310. package/client/features/home/workspace-preview.tsx +0 -213
  311. package/client/features/identity/host-api.ts +0 -35
  312. package/client/features/identity/store.ts +0 -26
  313. package/client/features/identity/types.ts +0 -41
  314. package/client/features/identity/use-identity.ts +0 -6
  315. package/client/features/onboarding/agent-setup-step.tsx +0 -57
  316. package/client/features/onboarding/api.ts +0 -42
  317. package/client/features/onboarding/onboarding-idea-disk.tsx +0 -129
  318. package/client/features/onboarding/onboarding-page.tsx +0 -33
  319. package/client/features/onboarding/onboarding-screen.tsx +0 -20
  320. package/client/features/onboarding/onboarding-status.tsx +0 -24
  321. package/client/features/onboarding/workspace-setup-step.tsx +0 -239
  322. package/client/features/overview/api.ts +0 -28
  323. package/client/features/overview/default/registry.tsx +0 -34
  324. package/client/features/overview/default/views-widget.tsx +0 -246
  325. package/client/features/overview/grid.ts +0 -77
  326. package/client/features/overview/hidden-panel.tsx +0 -111
  327. package/client/features/overview/overview.tsx +0 -299
  328. package/client/features/overview/use-grid-reconcile.ts +0 -94
  329. package/client/features/overview/widget-canvas.tsx +0 -166
  330. package/client/features/overview/widget-frame.tsx +0 -77
  331. package/client/features/overview/workspace-name.tsx +0 -55
  332. package/client/features/scratchpad/scratch-executor.ts +0 -20
  333. package/client/features/scratchpad/scratch-session.ts +0 -71
  334. package/client/features/scratchpad/scratchpad-controls.tsx +0 -516
  335. package/client/features/scratchpad/scratchpad.tsx +0 -351
  336. package/client/features/scratchpad/use-scratchpad-snapshot.tsx +0 -133
  337. package/client/features/update/api.ts +0 -35
  338. package/client/features/update/update-control.tsx +0 -102
  339. package/client/features/views/api.ts +0 -189
  340. package/client/features/views/pending-view-screen.tsx +0 -303
  341. package/client/features/views/use-view-actions.ts +0 -119
  342. package/client/features/views/use-view-drafts.ts +0 -88
  343. package/client/features/views/view-manager.tsx +0 -293
  344. package/client/features/views/view-presentation.ts +0 -12
  345. package/client/features/views/view-residency.ts +0 -77
  346. package/client/features/views/view-submission.ts +0 -56
  347. package/client/features/workspace/add/api.ts +0 -61
  348. package/client/features/workspace/add/create-workspace-dialog.tsx +0 -230
  349. package/client/features/workspace/add/import-workspace-dialog.tsx +0 -81
  350. package/client/features/workspace/add/use-workspace-import.ts +0 -61
  351. package/client/features/workspace/add/workspace-agent-options.ts +0 -53
  352. package/client/features/workspace/add/workspace-agent-selector.tsx +0 -96
  353. package/client/features/workspace/add/workspace-dialog-content.tsx +0 -22
  354. package/client/features/workspace/api.ts +0 -185
  355. package/client/features/workspace/harness-transition.ts +0 -83
  356. package/client/features/workspace/moi-context.ts +0 -129
  357. package/client/features/workspace/remote.ts +0 -25
  358. package/client/features/workspace/settings/api.ts +0 -112
  359. package/client/features/workspace/settings/connectors-settings.tsx +0 -110
  360. package/client/features/workspace/settings/environment-settings.tsx +0 -149
  361. package/client/features/workspace/settings/general-settings.tsx +0 -180
  362. package/client/features/workspace/settings/icon-picker-options.ts +0 -30
  363. package/client/features/workspace/settings/settings-layout.tsx +0 -53
  364. package/client/features/workspace/settings/use-env-vars.ts +0 -20
  365. package/client/features/workspace/settings/workspace-icon-picker.tsx +0 -318
  366. package/client/features/workspace/settings/workspace-settings-dialog.tsx +0 -65
  367. package/client/features/workspace/setup/workspace-login-state.tsx +0 -56
  368. package/client/features/workspace/setup/workspace-recovery-states.tsx +0 -142
  369. package/client/features/workspace/setup/workspace-setup.tsx +0 -98
  370. package/client/features/workspace/setup/workspace-welcome-state.tsx +0 -81
  371. package/client/features/workspace/tab-resolution.ts +0 -32
  372. package/client/features/workspace/theme-panel.tsx +0 -191
  373. package/client/features/workspace/unavailable-page.tsx +0 -21
  374. package/client/features/workspace/use-fits-split-layout.ts +0 -69
  375. package/client/features/workspace/use-workspace-navigation.ts +0 -265
  376. package/client/features/workspace/workspace-content.tsx +0 -601
  377. package/client/features/workspace/workspace-context.tsx +0 -21
  378. package/client/features/workspace/workspace-frame.tsx +0 -64
  379. package/client/features/workspace/workspace-identity.tsx +0 -40
  380. package/client/features/workspace/workspace-layout-context.tsx +0 -163
  381. package/client/features/workspace/workspace-menu.tsx +0 -67
  382. package/client/features/workspace/workspace-pane.tsx +0 -22
  383. package/client/features/workspace/workspace-pending-screen.tsx +0 -26
  384. package/client/features/workspace/workspace-preferences.ts +0 -91
  385. package/client/features/workspace/workspace-presentation.tsx +0 -35
  386. package/client/features/workspace/workspace-screen.tsx +0 -28
  387. package/client/features/workspace/workspace-split-layout.tsx +0 -116
  388. package/client/features/workspace/workspace-state.ts +0 -195
  389. package/client/features/workspace/workspace-tabs.tsx +0 -233
  390. package/client/features/workspace/workspace-test-utils.ts +0 -23
  391. package/client/global.d.ts +0 -5
  392. package/client/index.css +0 -247
  393. package/client/index.html +0 -81
  394. package/client/index.tsx +0 -45
  395. package/client/lib/agent-availability.ts +0 -14
  396. package/client/lib/browser-tab-id.ts +0 -4
  397. package/client/lib/cn.ts +0 -6
  398. package/client/lib/flags.ts +0 -11
  399. package/client/lib/identity-icon-registry.ts +0 -150
  400. package/client/lib/rate-limit.ts +0 -77
  401. package/client/lib/use-latest-ref.ts +0 -11
  402. package/client/lib/user-display-name.ts +0 -6
  403. package/client/lib/ws-url.ts +0 -10
  404. package/client/main.tsx +0 -43
  405. package/client/runtime/app-context.ts +0 -20
  406. package/client/runtime/hmr-watchdog.ts +0 -39
  407. package/client/runtime/use-workspace-events.ts +0 -70
  408. package/client/runtime/workspace-events.ts +0 -168
  409. package/client/runtime/workspace-theme.ts +0 -175
  410. package/client/store/ui.ts +0 -94
  411. package/client/store/workspace-session.ts +0 -30
  412. package/client/structured-clone-shim.ts +0 -14
  413. package/client/tailwind-config.ts +0 -43
  414. package/dist/chunk-0h4zypgf.js +0 -1
  415. package/dist/chunk-1tksq43z.js +0 -72
  416. package/dist/chunk-6gxf0xr8.js +0 -5
  417. package/dist/chunk-h3qag4a6.js +0 -2
  418. package/dist/chunk-kffcah9w.css +0 -1
  419. package/dist/chunk-q2tpy0h7.js +0 -2
  420. package/dist/chunk-w5h9grdr.js +0 -1
  421. package/lib/applet-selector.ts +0 -24
  422. package/lib/attachment-note.ts +0 -66
  423. package/lib/chat-title.ts +0 -11
  424. package/lib/collab/colors.ts +0 -30
  425. package/lib/collab/protocol.ts +0 -84
  426. package/lib/collab/types.ts +0 -52
  427. package/lib/default-widgets.ts +0 -32
  428. package/lib/format.ts +0 -348
  429. package/lib/harness-instructions.ts +0 -30
  430. package/lib/harness-types.ts +0 -13
  431. package/lib/identity-icons.ts +0 -73
  432. package/lib/ids.ts +0 -39
  433. package/lib/message-attachments.ts +0 -40
  434. package/lib/moi-attachments.ts +0 -204
  435. package/lib/moi-context.ts +0 -305
  436. package/lib/navigation.ts +0 -65
  437. package/lib/onboarding.ts +0 -41
  438. package/lib/scratchpad-skew.ts +0 -64
  439. package/lib/session-drafts.ts +0 -10
  440. package/lib/speed-mode.ts +0 -5
  441. package/lib/system-messages.ts +0 -241
  442. package/lib/themes.ts +0 -241
  443. package/lib/types.ts +0 -779
  444. package/lib/update.ts +0 -2
  445. package/lib/view-build-directives.ts +0 -11
  446. package/lib/workspace-config.ts +0 -48
  447. package/lib/workspace-icon.ts +0 -20
  448. package/lib/workspace-layout.ts +0 -15
  449. package/lib/workspace-name.ts +0 -17
  450. package/lib/workspace-tabs.ts +0 -29
  451. package/server/AGENTS.md +0 -17
  452. package/server/README.md +0 -109
  453. package/server/agent-caller.ts +0 -16
  454. package/server/agent-launcher.ts +0 -27
  455. package/server/api/harnesses.ts +0 -79
  456. package/server/api/index.ts +0 -1332
  457. package/server/api/onboarding.ts +0 -46
  458. package/server/app-config.ts +0 -264
  459. package/server/app-settings.ts +0 -69
  460. package/server/applets/api-base.ts +0 -4
  461. package/server/applets/applet-css.ts +0 -55
  462. package/server/applets/build-applet.ts +0 -475
  463. package/server/applets/build-worker.ts +0 -179
  464. package/server/applets/bundle-queue.ts +0 -19
  465. package/server/applets/config.ts +0 -226
  466. package/server/applets/declarations.ts +0 -45
  467. package/server/applets/dependencies.ts +0 -206
  468. package/server/applets/functions-worker.ts +0 -121
  469. package/server/applets/functions.ts +0 -392
  470. package/server/applets/index.ts +0 -504
  471. package/server/applets/log.ts +0 -149
  472. package/server/applets/runtime/collab.ts +0 -94
  473. package/server/applets/runtime/moi.ts +0 -35
  474. package/server/applets/runtime/rpc.ts +0 -15
  475. package/server/applets/thumbnails.ts +0 -200
  476. package/server/applets/typecheck.ts +0 -100
  477. package/server/applets/ui-components.ts +0 -241
  478. package/server/applets/view-source.ts +0 -73
  479. package/server/applets/views.ts +0 -322
  480. package/server/applets/widgets.ts +0 -180
  481. package/server/cli/applet-selector.ts +0 -19
  482. package/server/cli/args.ts +0 -5
  483. package/server/cli/colors.ts +0 -20
  484. package/server/cli/commands/bundle.ts +0 -119
  485. package/server/cli/commands/call-server-fn.ts +0 -42
  486. package/server/cli/commands/check.ts +0 -53
  487. package/server/cli/commands/config.ts +0 -120
  488. package/server/cli/commands/debug.ts +0 -119
  489. package/server/cli/commands/env.ts +0 -162
  490. package/server/cli/commands/hermes.ts +0 -149
  491. package/server/cli/commands/init.ts +0 -323
  492. package/server/cli/commands/navigate.ts +0 -35
  493. package/server/cli/commands/openclaw.ts +0 -168
  494. package/server/cli/commands/refresh.ts +0 -48
  495. package/server/cli/commands/remote.ts +0 -330
  496. package/server/cli/commands/scratch.ts +0 -496
  497. package/server/cli/commands/service.ts +0 -298
  498. package/server/cli/commands/skill.ts +0 -121
  499. package/server/cli/commands/start.ts +0 -112
  500. package/server/cli/commands/status.ts +0 -80
  501. package/server/cli/commands/tabs.ts +0 -36
  502. package/server/cli/commands/theme.ts +0 -192
  503. package/server/cli/commands/ui-components.ts +0 -15
  504. package/server/cli/commands/update.ts +0 -192
  505. package/server/cli/commands/version.ts +0 -9
  506. package/server/cli/commands/views.ts +0 -87
  507. package/server/cli/control.ts +0 -120
  508. package/server/cli/env.ts +0 -259
  509. package/server/cli/index.ts +0 -175
  510. package/server/cli/pc.ts +0 -20
  511. package/server/cli/provider.ts +0 -25
  512. package/server/cli/remote-command.ts +0 -77
  513. package/server/cli/remote-control.ts +0 -73
  514. package/server/cli/remote-operations.ts +0 -247
  515. package/server/cli/server-version.ts +0 -16
  516. package/server/cli/server.ts +0 -93
  517. package/server/cli/ui-components.ts +0 -294
  518. package/server/cli/ui.ts +0 -52
  519. package/server/cli.ts +0 -3
  520. package/server/collab/cloudflare-access.ts +0 -78
  521. package/server/collab/config.ts +0 -13
  522. package/server/collab/manager.ts +0 -413
  523. package/server/collab/service.ts +0 -136
  524. package/server/collab/skill/index.ts +0 -7
  525. package/server/collab/worker-messages.ts +0 -10
  526. package/server/collab/worker.ts +0 -52
  527. package/server/constants.ts +0 -13
  528. package/server/control-client.ts +0 -124
  529. package/server/control.ts +0 -581
  530. package/server/data-dir.ts +0 -22
  531. package/server/debug.ts +0 -10
  532. package/server/events.ts +0 -24
  533. package/server/harness/README.md +0 -381
  534. package/server/harness/acp/NOTES.md +0 -426
  535. package/server/harness/acp/adapter.ts +0 -206
  536. package/server/harness/acp/archived.ts +0 -88
  537. package/server/harness/acp/client.ts +0 -329
  538. package/server/harness/acp/discovery.ts +0 -127
  539. package/server/harness/acp/model-state.ts +0 -57
  540. package/server/harness/acp/run-durations.ts +0 -68
  541. package/server/harness/acp/session.ts +0 -782
  542. package/server/harness/acp/wire.ts +0 -132
  543. package/server/harness/auth.ts +0 -295
  544. package/server/harness/claude-code/NOTES.md +0 -651
  545. package/server/harness/claude-code/adapter.ts +0 -876
  546. package/server/harness/claude-code/auth.ts +0 -178
  547. package/server/harness/claude-code/cli.ts +0 -42
  548. package/server/harness/claude-code/git-worktree.ts +0 -35
  549. package/server/harness/claude-code/index.ts +0 -171
  550. package/server/harness/claude-code/mcp.ts +0 -152
  551. package/server/harness/claude-code/models.ts +0 -102
  552. package/server/harness/claude-code/permissions.ts +0 -34
  553. package/server/harness/claude-code/run-action.ts +0 -123
  554. package/server/harness/claude-code/session-title.ts +0 -104
  555. package/server/harness/claude-code/session.ts +0 -965
  556. package/server/harness/claude-code/sessions.ts +0 -153
  557. package/server/harness/codex/NOTES.md +0 -259
  558. package/server/harness/codex/adapter.ts +0 -633
  559. package/server/harness/codex/auth.ts +0 -140
  560. package/server/harness/codex/client.ts +0 -439
  561. package/server/harness/codex/connectors.ts +0 -92
  562. package/server/harness/codex/discovery.ts +0 -106
  563. package/server/harness/codex/index.ts +0 -107
  564. package/server/harness/codex/pagination.ts +0 -27
  565. package/server/harness/codex/permissions.ts +0 -80
  566. package/server/harness/codex/probe.ts +0 -183
  567. package/server/harness/codex/run-action.ts +0 -93
  568. package/server/harness/codex/session-title.ts +0 -147
  569. package/server/harness/codex/session.ts +0 -1188
  570. package/server/harness/codex/status.ts +0 -31
  571. package/server/harness/codex/thread-list.ts +0 -78
  572. package/server/harness/codex/transport.ts +0 -191
  573. package/server/harness/command.ts +0 -45
  574. package/server/harness/debug.ts +0 -57
  575. package/server/harness/detect.ts +0 -164
  576. package/server/harness/executable.ts +0 -125
  577. package/server/harness/fork.ts +0 -14
  578. package/server/harness/hermes/NOTES.md +0 -833
  579. package/server/harness/hermes/discovery.ts +0 -175
  580. package/server/harness/hermes/index.ts +0 -167
  581. package/server/harness/hermes/models.ts +0 -99
  582. package/server/harness/install.ts +0 -49
  583. package/server/harness/openclaw/NOTES.md +0 -749
  584. package/server/harness/openclaw/adapter.ts +0 -336
  585. package/server/harness/openclaw/compat.ts +0 -95
  586. package/server/harness/openclaw/cron-view.ts +0 -78
  587. package/server/harness/openclaw/discovery.ts +0 -456
  588. package/server/harness/openclaw/gateway.ts +0 -467
  589. package/server/harness/openclaw/index.ts +0 -125
  590. package/server/harness/openclaw/session.ts +0 -1508
  591. package/server/harness/openclaw/strip.ts +0 -184
  592. package/server/harness/openclaw/thinking.ts +0 -150
  593. package/server/harness/registry.ts +0 -39
  594. package/server/harness/run-action.ts +0 -85
  595. package/server/harness/session-title.ts +0 -59
  596. package/server/harness/shell-path.ts +0 -89
  597. package/server/harness/types.ts +0 -170
  598. package/server/navigation-relay.ts +0 -110
  599. package/server/onboarding/brief.ts +0 -29
  600. package/server/onboarding/ideas.ts +0 -48
  601. package/server/onboarding/jobs.ts +0 -291
  602. package/server/open-browser.ts +0 -7
  603. package/server/operations/commands.ts +0 -46
  604. package/server/operations/files.ts +0 -148
  605. package/server/operations/server.ts +0 -206
  606. package/server/remote/agent.ts +0 -103
  607. package/server/remote/broker-client.ts +0 -76
  608. package/server/remote/broker.ts +0 -81
  609. package/server/remote/client.ts +0 -725
  610. package/server/remote/errors.ts +0 -2
  611. package/server/remote/routes.ts +0 -121
  612. package/server/remote/workspace.ts +0 -34
  613. package/server/scratchpad/assets.ts +0 -258
  614. package/server/scratchpad/document.ts +0 -312
  615. package/server/scratchpad/executor.ts +0 -499
  616. package/server/scratchpad/relay.ts +0 -44
  617. package/server/scratchpad/shape-defaults.ts +0 -82
  618. package/server/server-cwd.ts +0 -23
  619. package/server/service.ts +0 -800
  620. package/server/sessions/archive.ts +0 -23
  621. package/server/sessions/attachment-message.ts +0 -95
  622. package/server/sessions/config.ts +0 -45
  623. package/server/sessions/lifecycle.ts +0 -19
  624. package/server/sessions/pending-views.ts +0 -152
  625. package/server/sessions/selected.ts +0 -113
  626. package/server/sessions/send-message.ts +0 -102
  627. package/server/sessions/store.ts +0 -54
  628. package/server/sessions/view-sessions.ts +0 -192
  629. package/server/skills/locations.ts +0 -82
  630. package/server/skills/lock.ts +0 -29
  631. package/server/skills/template.ts +0 -94
  632. package/server/skills/update.ts +0 -94
  633. package/server/skills/version.ts +0 -129
  634. package/server/skills/workspace.ts +0 -121
  635. package/server/state.ts +0 -40
  636. package/server/static.ts +0 -25
  637. package/server/status.ts +0 -110
  638. package/server/tldraw-package.d.ts +0 -4
  639. package/server/update.ts +0 -429
  640. package/server/uploads.ts +0 -290
  641. package/server/vendor.ts +0 -63
  642. package/server/version.ts +0 -41
  643. package/server/web.ts +0 -340
  644. package/server/workspace-state/file.ts +0 -181
  645. package/server/workspace-state/index.ts +0 -158
  646. package/server/workspace-state/lock.ts +0 -42
  647. package/server/workspace-state/types.ts +0 -16
  648. package/server/workspaces/api.ts +0 -24
  649. package/server/workspaces/change-harness.ts +0 -77
  650. package/server/workspaces/config.ts +0 -41
  651. package/server/workspaces/env-apply.ts +0 -20
  652. package/server/workspaces/env.ts +0 -424
  653. package/server/workspaces/harness-transition.ts +0 -29
  654. package/server/workspaces/icon.ts +0 -13
  655. package/server/workspaces/import.ts +0 -74
  656. package/server/workspaces/init.ts +0 -74
  657. package/server/workspaces/layout.ts +0 -157
  658. package/server/workspaces/preview.ts +0 -72
  659. package/server/workspaces/registry.ts +0 -330
  660. package/server/workspaces/required-env.ts +0 -19
  661. package/server/workspaces/scaffold.ts +0 -189
  662. package/server/workspaces/shared.ts +0 -74
  663. package/server/workspaces/tabs.ts +0 -35
  664. package/server/workspaces/theme.ts +0 -58
  665. package/tsconfig.json +0 -20
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{Lt}from"./chunk-hrtaxw37.js";import{r,m,u,s,T,o,sn}from"./chunk-ggphq7nk.js";import{g,e}from"./chunk-7c0zbz74.js";var Pt=e(function(bt,ge){(function(t){let i={fourOctet:new RegExp("^(0?\\d+|0x[a-f0-9]+)\\.(0?\\d+|0x[a-f0-9]+)\\.(0?\\d+|0x[a-f0-9]+)\\.(0?\\d+|0x[a-f0-9]+)$","i"),threeOctet:new RegExp("^(0?\\d+|0x[a-f0-9]+)\\.(0?\\d+|0x[a-f0-9]+)\\.(0?\\d+|0x[a-f0-9]+)$","i"),twoOctet:new RegExp("^(0?\\d+|0x[a-f0-9]+)\\.(0?\\d+|0x[a-f0-9]+)$","i"),longValue:new RegExp("^(0?\\d+|0x[a-f0-9]+)$","i")},a=new RegExp("^0[0-7]+$","i"),l=new RegExp("^0x[a-f0-9]+$","i"),p="%[0-9a-z]{1,}",f="(?:[0-9a-f]+::?)+",y={zoneIndex:new RegExp("%[0-9a-z]{1,}","i"),native:new RegExp("^(::)?((?:[0-9a-f]+::?)+)?([0-9a-f]+)?(::)?(%[0-9a-z]{1,})?$","i"),deprecatedTransitional:new RegExp("^(?:::)((0?\\d+|0x[a-f0-9]+)\\.(0?\\d+|0x[a-f0-9]+)\\.(0?\\d+|0x[a-f0-9]+)\\.(0?\\d+|0x[a-f0-9]+)(%[0-9a-z]{1,})?)$","i"),transitional:new RegExp("^((?:(?:[0-9a-f]+::?)+)|(?:::)(?:(?:[0-9a-f]+::?)+)?)(0?\\d+|0x[a-f0-9]+)\\.(0?\\d+|0x[a-f0-9]+)\\.(0?\\d+|0x[a-f0-9]+)\\.(0?\\d+|0x[a-f0-9]+)(%[0-9a-z]{1,})?$","i")};function S(c,d){if(c.indexOf("::")!==c.lastIndexOf("::"))return null;let E=0,h=-1,A=(c.match(y.zoneIndex)||[])[0],I,M;if(A)A=A.substring(1),c=c.replace(/%.+$/,"");while((h=c.indexOf(":",h+1))>=0)E++;if(c.substr(0,2)==="::")E--;if(c.substr(-2,2)==="::")E--;if(E>=d)return null;M=d-E,I=":";while(M--)I+="0:";if(c=c.replace("::",I),c[0]===":")c=c.slice(1);if(c[c.length-1]===":")c=c.slice(0,-1);return d=function(){let O=c.split(":"),b=[];for(let N=0;N<O.length;N++)b.push(O[N].length>4?NaN:parseInt(O[N],16));return b}(),{parts:d,zoneId:A}}function v(c,d,E,h){if(c.length!==d.length)throw Error("ipaddr: cannot match CIDR for objects with different lengths");let A=0,I;while(h>0){if(I=E-h,I<0)I=0;if(c[A]>>I!==d[A]>>I)return!1;h-=E,A+=1}return!0}function w(c){if(l.test(c))return parseInt(c,16);if(c[0]==="0"&&!isNaN(parseInt(c[1],10))){if(a.test(c))return parseInt(c,8);throw Error(`ipaddr: cannot parse ${c} as octal`)}return parseInt(c,10)}function R(c,d){while(c.length<d)c=`0${c}`;return c}let _={};if(_.IPv4=function(){function c(d){if(d.length!==4)throw Error("ipaddr: ipv4 octet count should be 4");let E,h;for(E=0;E<d.length;E++)if(h=d[E],!(0<=h&&h<=255))throw Error("ipaddr: ipv4 octet should fit in 8 bits");this.octets=d}return c.prototype.SpecialRanges={unspecified:[[new c([0,0,0,0]),8]],broadcast:[[new c([255,255,255,255]),32]],multicast:[[new c([224,0,0,0]),4]],linkLocal:[[new c([169,254,0,0]),16]],loopback:[[new c([127,0,0,0]),8]],carrierGradeNat:[[new c([100,64,0,0]),10]],private:[[new c([10,0,0,0]),8],[new c([172,16,0,0]),12],[new c([192,168,0,0]),16]],reserved:[[new c([192,0,0,0]),24],[new c([192,0,2,0]),24],[new c([192,88,99,0]),24],[new c([198,18,0,0]),15],[new c([198,51,100,0]),24],[new c([203,0,113,0]),24],[new c([240,0,0,0]),4]],as112:[[new c([192,175,48,0]),24],[new c([192,31,196,0]),24]],amt:[[new c([192,52,193,0]),24]]},c.prototype.kind=function(){return"ipv4"},c.prototype.match=function(d,E){let h;if(E===void 0)h=d,d=h[0],E=h[1];if(d.kind()!=="ipv4")throw Error("ipaddr: cannot match ipv4 address with non-ipv4 one");return v(this.octets,d.octets,8,E)},c.prototype.prefixLengthFromSubnetMask=function(){let d=0,E=!1,h={0:8,128:7,192:6,224:5,240:4,248:3,252:2,254:1,255:0},A,I,M;for(A=3;A>=0;A-=1)if(I=this.octets[A],I in h){if(M=h[I],E&&M!==0)return null;if(M!==8)E=!0;d+=M}else return null;return 32-d},c.prototype.range=function(){return _.subnetMatch(this,this.SpecialRanges)},c.prototype.toByteArray=function(){return this.octets.slice(0)},c.prototype.toIPv4MappedAddress=function(){return _.IPv6.parse(`::ffff:${this.toString()}`)},c.prototype.toNormalizedString=function(){return this.toString()},c.prototype.toString=function(){return this.octets.join(".")},c}(),_.IPv4.broadcastAddressFromCIDR=function(c){try{let d=this.parseCIDR(c),E=d[0].toByteArray(),h=this.subnetMaskFromPrefixLength(d[1]).toByteArray(),A=[],I=0;while(I<4)A.push(parseInt(E[I],10)|parseInt(h[I],10)^255),I++;return new this(A)}catch(d){throw Error("ipaddr: the address does not have IPv4 CIDR format",{cause:d})}},_.IPv4.isIPv4=function(c){return this.parser(c)!==null},_.IPv4.isValid=function(c){try{return new this(this.parser(c)),!0}catch{return!1}},_.IPv4.isValidCIDR=function(c){try{return this.parseCIDR(c),!0}catch{return!1}},_.IPv4.isValidFourPartDecimal=function(c){if(_.IPv4.isValid(c)&&c.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/))return!0;else return!1},_.IPv4.isValidCIDRFourPartDecimal=function(c){let d=c.match(/^(.+)\/(\d+)$/);if(!_.IPv4.isValidCIDR(c)||!d)return!1;return _.IPv4.isValidFourPartDecimal(d[1])},_.IPv4.networkAddressFromCIDR=function(c){let d,E,h,A,I;try{d=this.parseCIDR(c),h=d[0].toByteArray(),I=this.subnetMaskFromPrefixLength(d[1]).toByteArray(),A=[],E=0;while(E<4)A.push(parseInt(h[E],10)&parseInt(I[E],10)),E++;return new this(A)}catch(M){throw Error("ipaddr: the address does not have IPv4 CIDR format",{cause:M})}},_.IPv4.parse=function(c){let d=this.parser(c);if(d===null)throw Error("ipaddr: string is not formatted like an IPv4 Address");return new this(d)},_.IPv4.parseCIDR=function(c){let d;if(d=c.match(/^(.+)\/(\d+)$/)){let E=parseInt(d[2]);if(E>=0&&E<=32){let h=[this.parse(d[1]),E];return Object.defineProperty(h,"toString",{value:function(){return this.join("/")}}),h}}throw Error("ipaddr: string is not formatted like an IPv4 CIDR range")},_.IPv4.parser=function(c){let d,E,h;if(d=c.match(i.fourOctet))return function(){let A=d.slice(1,6),I=[];for(let M=0;M<A.length;M++)E=A[M],I.push(w(E));return I}();else if(d=c.match(i.longValue)){if(h=w(d[1]),h>4294967295||h<0)throw Error("ipaddr: address outside defined range");return function(){let A=[],I;for(I=0;I<=24;I+=8)A.push(h>>I&255);return A}().reverse()}else if(d=c.match(i.twoOctet))return function(){let A=d.slice(1,4),I=[];if(h=w(A[1]),h>16777215||h<0)throw Error("ipaddr: address outside defined range");return I.push(w(A[0])),I.push(h>>16&255),I.push(h>>8&255),I.push(h&255),I}();else if(d=c.match(i.threeOctet))return function(){let A=d.slice(1,5),I=[];if(h=w(A[2]),h>65535||h<0)throw Error("ipaddr: address outside defined range");return I.push(w(A[0])),I.push(w(A[1])),I.push(h>>8&255),I.push(h&255),I}();else return null},_.IPv4.subnetMaskFromPrefixLength=function(c){if(c=parseInt(c),Number.isNaN(c)||c<0||c>32)throw Error("ipaddr: invalid IPv4 prefix length");let d=[0,0,0,0],E=0,h=Math.floor(c/8);while(E<h)d[E]=255,E++;if(h<4)d[h]=Math.pow(2,c%8)-1<<8-c%8;return new this(d)},_.IPv6=function(){function c(d,E){let h,A;if(d.length===16){this.parts=[];for(h=0;h<=14;h+=2)this.parts.push(d[h]<<8|d[h+1])}else if(d.length===8)this.parts=d;else throw Error("ipaddr: ipv6 part count should be 8 or 16");for(h=0;h<this.parts.length;h++)if(A=this.parts[h],!(0<=A&&A<=65535))throw Error("ipaddr: ipv6 part should fit in 16 bits");if(E)this.zoneId=E}return c.prototype.SpecialRanges={unspecified:[new c([0,0,0,0,0,0,0,0]),128],linkLocal:[new c([65152,0,0,0,0,0,0,0]),10],multicast:[new c([65280,0,0,0,0,0,0,0]),8],loopback:[new c([0,0,0,0,0,0,0,1]),128],uniqueLocal:[new c([64512,0,0,0,0,0,0,0]),7],ipv4Mapped:[new c([0,0,0,0,0,65535,0,0]),96],deprecatedSiteLocal:[new c([65216,0,0,0,0,0,0,0]),10],discard:[new c([256,0,0,0,0,0,0,0]),64],rfc6145:[new c([0,0,0,0,65535,0,0,0]),96],rfc6052:[[new c([100,65435,0,0,0,0,0,0]),96],[new c([100,65435,1,0,0,0,0,0]),48]],"6to4":[new c([8194,0,0,0,0,0,0,0]),16],teredo:[new c([8193,0,0,0,0,0,0,0]),32],benchmarking:[new c([8193,2,0,0,0,0,0,0]),48],amt:[new c([8193,3,0,0,0,0,0,0]),32],as112v6:[[new c([8193,4,274,0,0,0,0,0]),48],[new c([9760,79,32768,0,0,0,0,0]),48]],deprecatedOrchid:[new c([8193,16,0,0,0,0,0,0]),28],orchid2:[new c([8193,32,0,0,0,0,0,0]),28],droneRemoteIdProtocolEntityTags:[new c([8193,48,0,0,0,0,0,0]),28],segmentRouting:[new c([24320,0,0,0,0,0,0,0]),16],reserved:[[new c([8193,0,0,0,0,0,0,0]),23],[new c([8193,3512,0,0,0,0,0,0]),32],[new c([16383,0,0,0,0,0,0,0]),20]]},c.prototype.isIPv4MappedAddress=function(){return this.range()==="ipv4Mapped"},c.prototype.kind=function(){return"ipv6"},c.prototype.match=function(d,E){let h;if(E===void 0)h=d,d=h[0],E=h[1];if(d.kind()!=="ipv6")throw Error("ipaddr: cannot match ipv6 address with non-ipv6 one");return v(this.parts,d.parts,16,E)},c.prototype.prefixLengthFromSubnetMask=function(){let d=0,E=!1,h={0:16,32768:15,49152:14,57344:13,61440:12,63488:11,64512:10,65024:9,65280:8,65408:7,65472:6,65504:5,65520:4,65528:3,65532:2,65534:1,65535:0},A,I;for(let M=7;M>=0;M-=1)if(A=this.parts[M],A in h){if(I=h[A],E&&I!==0)return null;if(I!==16)E=!0;d+=I}else return null;return 128-d},c.prototype.range=function(){return _.subnetMatch(this,this.SpecialRanges)},c.prototype.toByteArray=function(){let d,E=[],h=this.parts;for(let A=0;A<h.length;A++)d=h[A],E.push(d>>8),E.push(d&255);return E},c.prototype.toFixedLengthString=function(){let d=function(){let h=[];for(let A=0;A<this.parts.length;A++)h.push(R(this.parts[A].toString(16),4));return h}.call(this).join(":"),E="";if(this.zoneId)E=`%${this.zoneId}`;return d+E},c.prototype.toIPv4Address=function(){if(!this.isIPv4MappedAddress())throw Error("ipaddr: trying to convert a generic ipv6 address to ipv4");let d=this.parts.slice(-2),E=d[0],h=d[1];return new _.IPv4([E>>8,E&255,h>>8,h&255])},c.prototype.toNormalizedString=function(){let d=function(){let h=[];for(let A=0;A<this.parts.length;A++)h.push(this.parts[A].toString(16));return h}.call(this).join(":"),E="";if(this.zoneId)E=`%${this.zoneId}`;return d+E},c.prototype.toRFC5952String=function(){let d=/((^|:)(0(:|$)){2,})/g,E="";if(this.zoneId)E=`%${this.zoneId}`;let h=this.toNormalizedString(),A=h.slice(0,h.length-E.length),I=0,M=-1,O=-1,b;while(b=d.exec(A)){let N=(b[0].match(/0/g)||[]).length;if(N>O)O=N,I=b.index,M=b[0].length}if(M<0)return A+E;return`${A.substring(0,I)}::${A.substring(I+M)}${E}`},c.prototype.toString=function(){return this.toRFC5952String()},c}(),_.IPv6.broadcastAddressFromCIDR=function(c){try{let d=this.parseCIDR(c),E=d[0].toByteArray(),h=this.subnetMaskFromPrefixLength(d[1]).toByteArray(),A=[],I=0;while(I<16)A.push(parseInt(E[I],10)|parseInt(h[I],10)^255),I++;return new this(A)}catch(d){throw Error("ipaddr: the address does not have IPv6 CIDR format",{cause:d})}},_.IPv6.isIPv6=function(c){return this.parser(c)!==null},_.IPv6.isValid=function(c){if(typeof c==="string"&&c.indexOf(":")===-1)return!1;try{let d=this.parser(c);return new this(d.parts,d.zoneId),!0}catch{return!1}},_.IPv6.isValidCIDR=function(c){if(typeof c==="string"&&c.indexOf(":")===-1)return!1;try{return this.parseCIDR(c),!0}catch{return!1}},_.IPv6.networkAddressFromCIDR=function(c){let d,E,h,A,I;try{d=this.parseCIDR(c),h=d[0].toByteArray(),I=this.subnetMaskFromPrefixLength(d[1]).toByteArray(),A=[],E=0;while(E<16)A.push(parseInt(h[E],10)&parseInt(I[E],10)),E++;return new this(A)}catch(M){throw Error("ipaddr: the address does not have IPv6 CIDR format",{cause:M})}},_.IPv6.parse=function(c){let d=this.parser(c);if(d===null)throw Error("ipaddr: string is not formatted like an IPv6 Address");return new this(d.parts,d.zoneId)},_.IPv6.parseCIDR=function(c){let d,E,h;if(E=c.match(/^(.+)\/(\d+)$/)){if(d=parseInt(E[2]),d>=0&&d<=128)return h=[this.parse(E[1]),d],Object.defineProperty(h,"toString",{value:function(){return this.join("/")}}),h}throw Error("ipaddr: string is not formatted like an IPv6 CIDR range")},_.IPv6.parser=function(c){let d,E,h,A,I,M;if(h=c.match(y.deprecatedTransitional))return this.parser(`::ffff:${h[1]}`);if(y.native.test(c))return S(c,8);if(h=c.match(y.transitional)){if(M=h[6]||"",d=h[1],!h[1].endsWith("::"))d=d.slice(0,-1);if(d=S(d+M,6),d&&d.parts){I=[parseInt(h[2]),parseInt(h[3]),parseInt(h[4]),parseInt(h[5])];for(E=0;E<I.length;E++)if(A=I[E],!(0<=A&&A<=255))return null;return d.parts.push(I[0]<<8|I[1]),d.parts.push(I[2]<<8|I[3]),{parts:d.parts,zoneId:d.zoneId}}}return null},_.IPv6.subnetMaskFromPrefixLength=function(c){if(c=parseInt(c),Number.isNaN(c)||c<0||c>128)throw Error("ipaddr: invalid IPv6 prefix length");let d=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],E=0,h=Math.floor(c/8);while(E<h)d[E]=255,E++;if(h<16)d[h]=Math.pow(2,c%8)-1<<8-c%8;return new this(d)},_.fromByteArray=function(c){let d=c.length;if(d===4)return new _.IPv4(c);else if(d===16)return new _.IPv6(c);else throw Error("ipaddr: the binary input is neither an IPv6 nor IPv4 address")},_.isValid=function(c){return _.IPv6.isValid(c)||_.IPv4.isValid(c)},_.isValidCIDR=function(c){return _.IPv6.isValidCIDR(c)||_.IPv4.isValidCIDR(c)},_.parse=function(c){if(_.IPv6.isValid(c))return _.IPv6.parse(c);else if(_.IPv4.isValid(c))return _.IPv4.parse(c);else throw Error("ipaddr: the address has neither IPv6 nor IPv4 format")},_.parseCIDR=function(c){try{return _.IPv6.parseCIDR(c)}catch{try{return _.IPv4.parseCIDR(c)}catch(d){throw Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format",{cause:d})}}},_.process=function(c){let d=this.parse(c);if(d.kind()==="ipv6"&&d.isIPv4MappedAddress())return d.toIPv4Address();else return d},_.subnetMatch=function(c,d,E){let h,A,I,M;if(E===void 0||E===null)E="unicast";for(A in d)if(Object.prototype.hasOwnProperty.call(d,A)){if(I=d[A],I[0]&&!(I[0]instanceof Array))I=[I];for(h=0;h<I.length;h++)if(M=I[h],c.kind()===M[0].kind()&&c.match.apply(c,M))return A}return E},typeof ge<"u"&&ge.exports)ge.exports=_;else t.ipaddr=_})(bt)});function et(t){if(typeof t!=="string")return null;let n=t.trim();return n?n:null}function k(t){return et(t)??void 0}function dn(t){return k(t)?.toLowerCase()}function j(t){return dn(t)??""}function pn(t){if(typeof t==="number")return Number.isSafeInteger(t)?t:void 0;let n=k(t);if(!n||!/^[+-]?\d+$/.test(n))return;let i=Number(n);return Number.isSafeInteger(i)?i:void 0}function tt(t){let n=pn(t);return n!==void 0&&n>0?n:void 0}function nt(t){return t.VITEST==="true"||t.VITEST==="1"||t.VITEST_POOL_ID!==void 0||t.VITEST_WORKER_ID!==void 0||t.NODE_ENV==="test"||t!==process.env&&nt(process.env)}var Re=2147483647,Z=30000;function ve(t){let n=setTimeout(t,Z);return n.unref?.(),n}function we(t){if(t!==null)clearTimeout(t);return null}var Ce=30000;var rt=Z;function D(t,n){let i=n?.minMs??1,a=Math.min(Re,Math.max(0,Number.isFinite(i)?Math.floor(i):1));return Math.min(Re,Math.max(a,Number.isFinite(t)?Math.floor(t):a))}function Me(t,n,i){return D(typeof t==="number"&&Number.isFinite(t)?t:n,i)}function fe(t,n=rt){return Math.max(250,Math.min(Math.max(250,n),t))}function st(t=process.env){let n=t.OPENCLAW_CONNECT_CHALLENGE_TIMEOUT_MS;if(n){let i=tt(n);if(i!==void 0)return D(i)}}function ot(t,n){let i=Oe({env:n?.env,configuredTimeoutMs:n?.configuredTimeoutMs}),a=Math.max(Z,i);if(typeof t==="number"&&Number.isFinite(t))return fe(t,a);let l=st(n?.env);if(l!==void 0)return fe(l,Math.max(a,l));return fe(i,a)}function Oe(t){let n=t?.env??process.env,i=n.OPENCLAW_HANDSHAKE_TIMEOUT_MS||(nt(n)?n.OPENCLAW_TEST_HANDSHAKE_TIMEOUT_MS:void 0);if(i){let l=tt(i);if(l!==void 0)return D(l)}let a=t?.configuredTimeoutMs;if(typeof a==="number"&&Number.isFinite(a)&&a>0)return D(a);return Z}function fn(t){if(typeof t!=="string")return null;let n=t.trim();return n?n:null}function U(t){return fn(t)??void 0}function ee(t){return typeof t==="number"&&Number.isInteger(t)&&t>0?t:void 0}function Ne(t){return typeof t==="number"&&Number.isInteger(t)&&t>=0?t:void 0}function V(t){return t!==null&&typeof t==="object"&&!Array.isArray(t)}function hn(t){if(!Array.isArray(t))return[];return t.flatMap((n)=>{let i=U(n);return i?[i]:[]})}function be(t){let n=hn(t);return n.length>0?n:void 0}var C={AUTH_REQUIRED:"AUTH_REQUIRED",AUTH_UNAUTHORIZED:"AUTH_UNAUTHORIZED",AUTH_TOKEN_MISSING:"AUTH_TOKEN_MISSING",AUTH_TOKEN_MISMATCH:"AUTH_TOKEN_MISMATCH",AUTH_TOKEN_NOT_CONFIGURED:"AUTH_TOKEN_NOT_CONFIGURED",AUTH_PASSWORD_MISSING:"AUTH_PASSWORD_MISSING",AUTH_PASSWORD_MISMATCH:"AUTH_PASSWORD_MISMATCH",AUTH_PASSWORD_NOT_CONFIGURED:"AUTH_PASSWORD_NOT_CONFIGURED",AUTH_BOOTSTRAP_TOKEN_INVALID:"AUTH_BOOTSTRAP_TOKEN_INVALID",AUTH_DEVICE_TOKEN_MISMATCH:"AUTH_DEVICE_TOKEN_MISMATCH",AUTH_SCOPE_MISMATCH:"AUTH_SCOPE_MISMATCH",AUTH_RATE_LIMITED:"AUTH_RATE_LIMITED",AUTH_TAILSCALE_IDENTITY_MISSING:"AUTH_TAILSCALE_IDENTITY_MISSING",AUTH_TAILSCALE_PROXY_MISSING:"AUTH_TAILSCALE_PROXY_MISSING",AUTH_TAILSCALE_WHOIS_FAILED:"AUTH_TAILSCALE_WHOIS_FAILED",AUTH_TAILSCALE_IDENTITY_MISMATCH:"AUTH_TAILSCALE_IDENTITY_MISMATCH",AUTH_IDENTITY_HEADER_REQUIRED:"AUTH_IDENTITY_HEADER_REQUIRED",AUTH_VERIFIED_USER_REQUIRED:"AUTH_VERIFIED_USER_REQUIRED",AUTHENTICATED_PROFILE_UNAVAILABLE:"AUTHENTICATED_PROFILE_UNAVAILABLE",OPERATOR_ACCESS_DENIED:"OPERATOR_ACCESS_DENIED",CONTROL_UI_BUILD_MISMATCH:"CONTROL_UI_BUILD_MISMATCH",CONTROL_UI_ORIGIN_NOT_ALLOWED:"CONTROL_UI_ORIGIN_NOT_ALLOWED",PROTOCOL_MISMATCH:"PROTOCOL_MISMATCH",CONTROL_UI_DEVICE_IDENTITY_REQUIRED:"CONTROL_UI_DEVICE_IDENTITY_REQUIRED",DEVICE_IDENTITY_REQUIRED:"DEVICE_IDENTITY_REQUIRED",DEVICE_AUTH_INVALID:"DEVICE_AUTH_INVALID",DEVICE_AUTH_DEVICE_ID_MISMATCH:"DEVICE_AUTH_DEVICE_ID_MISMATCH",DEVICE_AUTH_SIGNATURE_EXPIRED:"DEVICE_AUTH_SIGNATURE_EXPIRED",DEVICE_AUTH_NONCE_REQUIRED:"DEVICE_AUTH_NONCE_REQUIRED",DEVICE_AUTH_NONCE_MISMATCH:"DEVICE_AUTH_NONCE_MISMATCH",DEVICE_AUTH_SIGNATURE_INVALID:"DEVICE_AUTH_SIGNATURE_INVALID",DEVICE_AUTH_PUBLIC_KEY_INVALID:"DEVICE_AUTH_PUBLIC_KEY_INVALID",PAIRING_REQUIRED:"PAIRING_REQUIRED",PAIRING_REJECTED:"PAIRING_REJECTED",PAIRING_EXPIRED:"PAIRING_EXPIRED",CLIENT_VERSION_MISMATCH:"CLIENT_VERSION_MISMATCH"},En=["retry_with_device_token","update_auth_configuration","update_auth_credentials","wait_then_retry","review_auth_configuration"],yn=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/,Pe={"not-paired":{message:"device pairing required",requirement:"device is not approved yet",remediationHint:"Approve this device from the pending pairing requests.",recoveryTitle:"Gateway pairing approval required."},"role-upgrade":{message:"role upgrade pending approval",requirement:"device is asking for a higher role than currently approved",remediationHint:"Review the requested role upgrade, then approve the pending request.",recoveryTitle:"Gateway role upgrade approval required."},"scope-upgrade":{message:"scope upgrade pending approval",requirement:"device is asking for more scopes than currently approved",remediationHint:"Review the requested scopes, then approve the pending upgrade.",recoveryTitle:"Gateway scope upgrade approval required."},"metadata-upgrade":{message:"device metadata change pending approval",requirement:"device identity changed and must be re-approved",remediationHint:"Review the refreshed device details, then approve the pending request.",recoveryTitle:"Gateway device refresh approval required."}},es=new Map([["token_missing",C.AUTH_TOKEN_MISSING],["token_mismatch",C.AUTH_TOKEN_MISMATCH],["token_missing_config",C.AUTH_TOKEN_NOT_CONFIGURED],["password_missing",C.AUTH_PASSWORD_MISSING],["password_mismatch",C.AUTH_PASSWORD_MISMATCH],["password_missing_config",C.AUTH_PASSWORD_NOT_CONFIGURED],["bootstrap_token_invalid",C.AUTH_BOOTSTRAP_TOKEN_INVALID],["tailscale_user_missing",C.AUTH_TAILSCALE_IDENTITY_MISSING],["tailscale_proxy_missing",C.AUTH_TAILSCALE_PROXY_MISSING],["tailscale_whois_failed",C.AUTH_TAILSCALE_WHOIS_FAILED],["tailscale_user_mismatch",C.AUTH_TAILSCALE_IDENTITY_MISMATCH],["rate_limited",C.AUTH_RATE_LIMITED],["device_token_mismatch",C.AUTH_DEVICE_TOKEN_MISMATCH],["scope_mismatch",C.AUTH_SCOPE_MISMATCH],[void 0,C.AUTH_REQUIRED]]),ts=new Map([["device-id-mismatch",C.DEVICE_AUTH_DEVICE_ID_MISMATCH],["device-signature-stale",C.DEVICE_AUTH_SIGNATURE_EXPIRED],["device-nonce-missing",C.DEVICE_AUTH_NONCE_REQUIRED],["device-nonce-mismatch",C.DEVICE_AUTH_NONCE_MISMATCH],["device-signature",C.DEVICE_AUTH_SIGNATURE_INVALID],["device-public-key",C.DEVICE_AUTH_PUBLIC_KEY_INVALID]]);function q(t){if(!V(t))return null;return U(t.code)??null}function it(t){if(!V(t))return{};return{canRetryWithDeviceToken:typeof t.canRetryWithDeviceToken==="boolean"?t.canRetryWithDeviceToken:void 0,recommendedNextStep:at(t.recommendedNextStep)}}function at(t){let n=U(t)??"";return En.find((i)=>i===n)}function mn(t){let n=U(t)??"";return Object.hasOwn(Pe,n)?n:void 0}function In(t){let n=U(t);return n&&yn.test(n)?n:void 0}function gn(t){return{code:C.PAIRING_REQUIRED,...t.reason?{reason:t.reason}:{},...t.requestId?{requestId:t.requestId}:{},...t.remediationHint?{remediationHint:t.remediationHint}:{},...t.recommendedNextStep?{recommendedNextStep:t.recommendedNextStep}:{},...t.retryable!==void 0?{retryable:t.retryable}:{},...t.pauseReconnect!==void 0?{pauseReconnect:t.pauseReconnect}:{},...t.waitForResolution!==void 0?{waitForResolution:t.waitForResolution}:{},...t.deviceId?{deviceId:t.deviceId}:{},...t.requestedRole?{requestedRole:t.requestedRole}:{},...t.requestedScopes?{requestedScopes:t.requestedScopes}:{},...t.approvedRoles?{approvedRoles:t.approvedRoles}:{},...t.approvedScopes?{approvedScopes:t.approvedScopes}:{}}}function Tn(t,n){return{requestId:In(t.requestId),remediationHint:U(t.remediationHint)??(n?Pe[n].remediationHint:"Approve the pending device request before retrying."),deviceId:U(t.deviceId),requestedRole:U(t.requestedRole),requestedScopes:be(t.requestedScopes),approvedRoles:be(t.approvedRoles),approvedScopes:be(t.approvedScopes)}}function ke(t){if(q(t)!==C.PAIRING_REQUIRED)return null;if(!V(t))return null;let n=mn(t.reason);return gn({...Tn(t,n),reason:n,recommendedNextStep:at(t.recommendedNextStep),retryable:typeof t.retryable==="boolean"?t.retryable:void 0,pauseReconnect:typeof t.pauseReconnect==="boolean"?t.pauseReconnect:void 0,waitForResolution:typeof t.waitForResolution==="boolean"?t.waitForResolution:void 0})}function _n(t){let n=ke(t),i=Pe[n?.reason??"not-paired"].message;return n?.requestId?`${i} (requestId: ${n.requestId})`:i}function ct(t){let n=q(t.details);if(n===C.PAIRING_REQUIRED)return _n(t.details);if(n===C.PROTOCOL_MISMATCH)return An(t.message,t.details);return U(t.message)??"gateway request failed"}function An(t,n){let i=n,a=ee(i.clientMinProtocol),l=ee(i.clientMaxProtocol),p=ee(i.expectedProtocol),f=ee(i.minimumProbeProtocol),y=[];if(a!==void 0&&l!==void 0)y.push(a===l?`Control UI v${a}`:`Control UI v${a}-v${l}`);if(p!==void 0)y.push(`Gateway v${p}`);if(f!==void 0)y.push(`connection check min v${f}`);let S=U(t)??"protocol mismatch";return y.length>0?`${S}: ${y.join(", ")}`:S}function te(t){return typeof t==="string"&&t.length>0}function Sn(t){if(!V(t))return!1;if(!te(t.code)||!te(t.message))return!1;if(t.retryable!==void 0&&typeof t.retryable!=="boolean")return!1;return t.retryAfterMs===void 0||Ne(t.retryAfterMs)!==void 0}function lt(t){if(!V(t)||t.type!=="event"||!te(t.event))return!1;return t.seq===void 0||Ne(t.seq)!==void 0}function ut(t){if(!V(t)||t.type!=="res"||!te(t.id)||typeof t.ok!=="boolean")return!1;return t.error===void 0||Sn(t.error)}var ne=60000;function De(t){return pt(t,"gateway-restarting")}function dt(t){return pt(t,"gateway-suspending")}function pt(t,n){if(!t||typeof t!=="object"||!("details"in t))return!1;let i=t.details;return typeof i==="object"&&i!==null&&"reason"in i&&i.reason===n}function Rn(t){return typeof t==="object"&&t!==null&&t.reason==="startup-sidecars"}function Ue(t){if(!t||typeof t!=="object")return!1;let n=t;return(n.gatewayCode??n.code)==="UNAVAILABLE"&&n.retryable===!0&&Rn(n.details)}function ft(t){if(!Ue(t))return null;let n=t.retryAfterMs;return Math.min(Math.max(Math.floor(typeof n==="number"&&Number.isFinite(n)?n:500),100),2000)}function xe(t){if(typeof t!=="string")return"";return t.trim().replace(/[A-Z]/g,(n)=>String.fromCharCode(n.charCodeAt(0)+32))}function ht(t){let n=t.scopes.join(","),i=t.token??"",a=xe(t.platform),l=xe(t.deviceFamily);return["v3",t.deviceId,t.clientId,t.clientMode,t.role,n,String(t.signedAtMs),i,t.nonce,a,l].join("|")}function qe(t){return t!==null&&typeof t==="object"&&!Array.isArray(t)}function Ee(t){return vn(t)??{}}function Et(t){return qe(t)?t:void 0}function vn(t){return t&&typeof t==="object"?t:void 0}function yt(t){let n=k(t.token),i=k(t.bootstrapToken),a=k(t.deviceToken),l=k(t.password),p=k(t.storedToken),f={storedToken:p,storedScopes:t.storedScopes};if(t.preferBootstrapToken&&i)return{authBootstrapToken:i,signatureToken:i,...f};let y=t.pendingDeviceTokenRetry===!0&&!a&&Boolean(n&&p&&t.trustedDeviceTokenRetry),S=a??(y||!(n||l)&&(!i||p)?p:void 0),v=Boolean(S&&!a&&p)&&S===p,w=n??S,R=!n&&!S&&!l?i:void 0;return{authToken:n,authBootstrapToken:R,authDeviceToken:y?p:void 0,authPassword:l,authApprovalRuntimeToken:k(t.approvalRuntimeToken),authAgentRuntimeIdentityToken:k(t.agentRuntimeIdentityToken),signatureToken:w??R,resolvedDeviceToken:S,usingStoredDeviceToken:v,...f}}function mt(t){let n={token:t.authToken,bootstrapToken:t.authBootstrapToken,deviceToken:t.authDeviceToken??t.resolvedDeviceToken,password:t.authPassword,approvalRuntimeToken:t.authApprovalRuntimeToken,agentRuntimeIdentityToken:t.authAgentRuntimeIdentityToken};return Object.values(n).some(Boolean)?n:void 0}function It(t){return t.requestedScopes??(t.usingStoredDeviceToken&&t.storedScopes?.length?t.storedScopes:[...t.defaultScopes])}function gt(t){if(t.retryBudgetUsed||t.currentDeviceToken||!t.explicitToken||!t.storedToken||!t.trustedEndpoint)return!1;let n=it(t.errorDetails);return t.canRetryWithDeviceTokenHint===!0||n.canRetryWithDeviceToken===!0||n.recommendedNextStep==="retry_with_device_token"||q(t.errorDetails)===C.AUTH_TOKEN_MISMATCH}var Le="model-catalog-snapshot";function Tt(t){let n=t.serverCapabilities.includes(Le)?t.modelCatalog:void 0,i=t.caps?.filter((a)=>a!==Le);if(n===void 0)return{caps:i};return{modelCatalog:n,caps:[...i??[],Le]}}var He=[[[183,183],[12288,12703],[19968,40869],[44032,55215],[65281,65376]],[[4352,4607],[11904,12287],[12704,19967],[40870,40959],[40960,42239],[42752,42759],[43360,43391],[55216,55295],[63744,64255]],[[711,711],[713,715],[729,729],[746,747],[773,773],[803,803],[65040,65103],[65377,65500],[65504,65510]],[[119648,119665]],[[94176,94207],[110576,110591],[110592,110959],[127488,127743],[131072,195103],[196608,210047]]];new RegExp(`[${He.flatMap((t)=>t.map(([n,i])=>`\\u{${n.toString(16)}}-\\u{${i.toString(16)}}`)).join("")}]`,"u");(()=>{let t=Math.max(...He.flatMap((i)=>i.map(([,a])=>a))),n=new Uint8Array(t+1);for(let[i,a]of He.entries())for(let[l,p]of a)n.fill(i+1,l,p+1);return n})();function K(t){return t instanceof Error?t:Error(String(t))}function wn(t){return Array.isArray(t)?t.filter((n)=>typeof n==="string"):[]}var me=2147000000;function Ie(t,n){let i=Error(t,n);return i.name="AbortError",i}async function _t(t,n,i,a={}){let l,p;try{let f=new Promise((S,v)=>{let w=(_)=>{try{S(_())}catch(c){v(c)}};if(l=setTimeout(()=>w(i),n),a.ref===!1)l.unref?.();let R=a.signal;if(R){if(p=()=>w(()=>{if(a.onAbort)return a.onAbort(R);throw Ie("Operation aborted",{cause:R.reason})}),R.addEventListener("abort",p,{once:!0}),R.aborted)p()}}),y;try{y=typeof t==="function"?t():t}catch(S){throw f.catch(()=>{}),S}return await Promise.race([y,f])}finally{if(clearTimeout(l),p)a.signal?.removeEventListener("abort",p)}}function Cn(t,n){let i=Math.min(t.maxMs,t.initialMs*t.factor**Math.max(n-1,0)),a=i*t.jitter*Math.random();return Math.min(t.maxMs,Math.round(i+a))}function At(t){return Number.isFinite(t)&&t>0?Math.min(Math.max(Math.floor(t),1),me):0}async function Mn(t,n,i={}){let a=At(t);if(a===0)return;await new Promise((l,p)=>{let f=()=>n?.removeEventListener("abort",S),y=setTimeout(()=>{f(),l()},a),S=()=>{clearTimeout(y),f(),p(Ie("aborted",{cause:n?.reason??Error("aborted")}))};if(n?.addEventListener("abort",S,{once:!0}),n?.aborted){S();return}if(i.ref===!1)y.unref?.()})}var On=class{constructor(t,n=Number.POSITIVE_INFINITY){this.policy=t,this.maxAttempts=n,this.attempts=0,this.initialMs=t.initialMs}reset(t=this.policy.initialMs){this.cancel(),this.attempts=0,this.initialMs=t,this.nextDelayOverrideMs=void 0}cancel(t=Error("retry cancelled")){this.pendingAbort?.abort(t),this.pendingAbort=void 0}next(t){let n=this.nextDelayOverrideMs;if(this.nextDelayOverrideMs=void 0,n===void 0&&++this.attempts>Math.ceil(this.maxAttempts))return;let i=Math.max(this.attempts,1),a=n??Cn({...this.policy,initialMs:this.initialMs},i);this.cancel();let l=new AbortController;return this.pendingAbort=l,{attempt:i,delayMs:a,signal:t?AbortSignal.any([l.signal,t]):l.signal}}},St={attempts:3,minDelayMs:300,maxDelayMs:30000,jitter:0},Nn=async(t)=>{let n=t;do{let i=Math.min(n,me);await new Promise((a)=>{setTimeout(a,i)}),n-=i}while(n>0)};function ye(t,n,i,a){if(typeof t!=="number"||!Number.isFinite(t))return n;return Math.min(Math.max(t,i??Number.NEGATIVE_INFINITY),a??Number.POSITIVE_INFINITY)}function re(t){return Math.min(Math.max(Math.round(t===Number.POSITIVE_INFINITY?me:Number.isFinite(t)?t:0),0),me)}function bn(t=St,n){let i=Math.max(1,Math.round(ye(n?.attempts,t.attempts))),a=re(ye(n?.minDelayMs,t.minDelayMs,0)),l=Math.max(a,re(ye(n?.maxDelayMs,t.maxDelayMs,0))),p=n?.jitter,f=t.jitter;return{attempts:i,minDelayMs:a,maxDelayMs:l,jitter:p==="full"?p:typeof p==="number"&&Number.isFinite(p)?Math.min(Math.max(p,0),1):f}}function Pn(t,n,i,a){if(n==="full"){if(i==="symmetric")return Math.max(0,Math.round(t*(0.5+a()*0.5)));return Math.max(0,Math.ceil(t*(1+a())))}if(n<=0)return i==="positive"?Math.ceil(t):t;let l=a(),p=t*(1+(i==="positive"?l*n:(l*2-1)*n));return Math.max(0,i==="positive"?Math.ceil(p):Math.round(p))}function kn(t,n="Non-Error thrown"){if(t instanceof Error)return t;if(typeof t==="string")return Error(t);let i=Error(n,{cause:t});if(typeof t==="object"&&t!==null||typeof t==="function")Object.assign(i,t);return i}function Dn(t={}){let n=t.sleep??Nn,i=t.random??Math.random,a=t.createFailure??((l)=>kn(l.at(-1)??Error("Retry failed")));return async function(p,f=3,y=300){let S=[],v=typeof f==="number",w=typeof f==="number"?{attempts:f}:f,R=bn(St,w),{attempts:_,minDelayMs:c}=R,d=R.maxDelayMs>0?R.maxDelayMs:Number.POSITIVE_INFINITY,E=w.retryAfterMaxDelayMs===void 0?d:Math.max(c,re(ye(w.retryAfterMaxDelayMs,d,0))),h=w.random??i,A=w.sleep??n,I=w.shouldRetry??(()=>!0);for(let M=1;M<=_;M+=1)try{return await p()}catch(O){if(S.push(O),M>=_||t.shouldRetry?.(O)===!1||!I(O,M))break;if(v){await n(re(y*2**(M-1)));continue}let b={attempt:M,maxAttempts:_,err:O,label:w.label},N=w.retryAfterMs?.(O),x=typeof N==="number"&&Number.isFinite(N),J=typeof w.delayMs==="function"?w.delayMs(b):w.delayMs,le=J===void 0?void 0:re(J),ue=x?Math.max(N,c):le===void 0?c*2**(M-1):Math.max(le,c),H=x?E:d,F=Math.min(ue,H),de=x&&(N??0)<=H,pe=R.jitter==="full"?!x||de:de;if(F=Pn(F,R.jitter,pe?"positive":"symmetric",h),F=Math.min(Math.max(F,c),H),await w.onRetry?.({...b,delayMs:F}),F>0)await A(F)}throw a(S)}}Dn();var Un=class{constructor(){this.listeners=new Map}add(t){let n=this.listeners.get(t)??{};return this.listeners.set(t,n),()=>{if(this.listeners.get(t)===n)this.listeners.delete(t)}}snapshot(){return[...this.listeners]}isCurrent(t,n){return this.listeners.get(t)===n}},Ln=new WeakSet;var z=class extends Error{constructor(t){super(t.message??"request failed");this.name="GatewayProtocolRequestError",this.code=t.code??"UNAVAILABLE",this.gatewayCode=this.code,this.details=t.details,this.retryable=t.retryable===!0,this.retryAfterMs=t.retryAfterMs}};function xn(t,n){Ln.add(t),Object.defineProperty(t,"responsePayload",{value:n,enumerable:!1,configurable:!0})}var Fe=class extends Error{constructor(t,n=`gateway request timed out after ${t.timeoutMs}ms: ${t.method}`){super(n);this.code="CLIENT_TIMEOUT",this.name="GatewayProtocolRequestTimeoutError",this.method=t.method,this.timeoutMs=t.timeoutMs,this.requestSent=t.requestSent}},Hn=class{constructor(t){this.opts=t,this.pending=new Map,this.requestSequence=0}setSuspensionPhase(t){if(t==="accepting")this.resumeBootstrapRequests();else if(t==="preparing"||t==="draining"||t==="prepared")this.pauseBootstrapRequests(void 0,!0)}pauseBootstrapRequests(t=ne,n=!1){let i=this.opts.nowMs(),a=D(Number.isFinite(t)&&t>0?t:ne),l=this.bootstrapPause??={retryAtMs:i,revision:0,announced:n};if(l.announced||=n,l.revision+=1,l.retryAtMs=Math.max(l.retryAtMs,i+a),clearTimeout(l.timer),l.timer=void 0,l.announced)return;l.timer=setTimeout(()=>{l.timer=void 0,this.drainBootstrapRequests()},D(l.retryAtMs-i)),l.timer.unref?.()}resumeBootstrapRequests(){clearTimeout(this.bootstrapPause?.timer),this.bootstrapPause=void 0,this.drainBootstrapRequests()}drainBootstrapRequests(){for(let t of this.pending.values())if(t.waitingForResume)t.resend?.()}get hasPending(){return this.pending.size>0}get hasUnboundedPending(){for(let t of this.pending.values())if(t.unbounded)return!0;return!1}releaseHeldRequests(t){for(let n of this.pending.values()){if(!t())return;let i=n.afterHello;n.afterHello=void 0,i?.()}}request(t,n,i,a,l=!1){let p;try{this.requestSequence+=1,p=`${this.requestSequence}:${this.opts.createRequestId()}`}catch(S){return Promise.reject(K(S))}let f=a?.timeoutMs===null?void 0:a?.timeoutMs??this.opts.requestTimeoutMs,y=typeof f==="number"&&Number.isFinite(f)?D(f,{minMs:0}):void 0;return new Promise((S,v)=>{let w,R,_=!1,c=!1,d={resolve:(I)=>S(I),reject:v,expectFinal:a?.expectFinal===!0,acceptedNotified:!1,onAccepted:a?.onAccepted,unbounded:y===void 0,method:n,startedAtMs:this.opts.nowMs(),prepareRetry:()=>{if(c=!1,_=!1,a?.signal?.aborted)return A(),!1;return!0}},E=()=>{if(clearTimeout(R),w!==void 0)clearTimeout(w);if(a?.signal?.removeEventListener("abort",A),this.bootstrapPause?.probe?.pending===d)this.bootstrapPause.probe=void 0,this.drainBootstrapRequests()},h=(I)=>{if(this.pending.get(p)!==d)return!1;return this.pending.delete(p),E(),this.finishTiming(p,d,!1,I),!0},A=()=>{if(a?.retainSentResultOnAbort&&c)return;if(!h("CLIENT_ABORTED"))return;v(this.opts.createRequestAbortError?.(n)??Error(`gateway request aborted for ${n}`))};if(a?.signal?.aborted){v(this.opts.createRequestAbortError?.(n)??Error(`gateway request aborted for ${n}`));return}if(d.cleanup=E,y!==void 0)w=setTimeout(()=>{if(!h("CLIENT_TIMEOUT"))return;v(this.opts.createRequestTimeoutError?.(n,y,_)??new Fe({method:n,timeoutMs:y,requestSent:_}))},y),w.unref?.();a?.signal?.addEventListener("abort",A,{once:!0}),this.pending.set(p,d);try{let I=JSON.stringify({type:"req",id:p,method:n,params:i}),M=()=>{if(this.pending.get(p)!==d||a?.signal?.aborted||y!==void 0&&this.opts.nowMs()-d.startedAtMs>=y)return;let O=d.resend?this.bootstrapPause:void 0;if(O&&!O.announced&&!O.timer&&!O.probe)O.probe={pending:d,revision:O.revision};if(d.waitingForResume=Boolean(O&&(O.announced||O.probe?.pending!==d)),d.waitingForResume)return;try{if(c=!0,t.send(I),this.pending.get(p)!==d)return;_=c,this.invoke("sent",()=>a?.onSent?.(p))}catch(b){if(h("CLIENT_SEND_ERROR"))v(K(b))}};if(d.retryStartup=(O)=>{d.resend=M,clearTimeout(R),R=setTimeout(M,Me(O,ne)),R.unref?.()},n==="agent.identity.get"||n==="sessions.subscribe"||n==="sessions.groups.list"||n==="question.list"||n==="sessions.list")d.resend=M;if(l)d.afterHello=M;else M()}catch(I){if(h("CLIENT_SEND_ERROR"))v(K(I))}})}handleResponse(t){let n=this.pending.get(t.id);if(!n)return;let i=t.payload?.status;if(t.ok&&n.expectFinal&&i==="accepted"){if(!n.acceptedNotified)n.acceptedNotified=!0,this.invoke("accepted",()=>n.onAccepted?.(t.payload));return}let a=t.error?.details;if(!t.ok&&Ue(t.error)&&a!==null&&typeof a==="object"&&"method"in a&&a.method===n.method&&!n.acceptedNotified){if(n.prepareRetry()){if(n.retryStartup?.(t.error?.retryAfterMs),this.bootstrapPause?.probe?.pending===n&&this.bootstrapPause.probe.revision===this.bootstrapPause.revision)this.resumeBootstrapRequests()}return}if(!t.ok&&n.resend&&!n.acceptedNotified&&t.error?.code==="UNAVAILABLE"&&t.error.retryable===!0&&(dt(t.error)||De(t.error))){if(!n.prepareRetry())return;if(this.bootstrapPause?.probe?.pending===n)this.bootstrapPause.probe=void 0;this.pauseBootstrapRequests(De(t.error)?Math.ceil(Math.max(ne,t.error.retryAfterMs??0)*(1+Math.random()*0.2)):t.error.retryAfterMs),n.waitingForResume=!0;return}if(this.pending.delete(t.id),t.ok&&this.bootstrapPause?.probe?.pending===n&&this.bootstrapPause.probe.revision===this.bootstrapPause.revision)this.resumeBootstrapRequests();if(n.cleanup?.(),t.ok){this.finishTiming(t.id,n,!0),n.resolve(t.payload);return}this.finishTiming(t.id,n,!1,t.error?.code);let l=this.opts.createRequestError?.(t.error??{})??new z(t.error??{});xn(l,t.payload),n.reject(l)}flush(t){clearTimeout(this.bootstrapPause?.timer),this.bootstrapPause=void 0;let n=this.pending;this.pending=new Map,this.requestSequence=0;for(let[i,a]of n)a.cleanup?.(),this.finishTiming(i,a,!1,"CLIENT_CLOSED"),a.reject(t)}finishTiming(t,n,i,a){let l=this.opts.nowMs();this.invoke("request timing",()=>this.opts.onTiming?.({id:t,method:n.method,ok:i,durationMs:Math.max(0,l-n.startedAtMs),startedAtMs:n.startedAtMs,endedAtMs:l,errorCode:a}))}invoke(t,n){try{n()}catch(i){this.opts.onCallbackError?.(t,i)}}},he=Object.freeze({closeCode:1008,closeReason:"connect failed"}),Rt=class{constructor(t){this.opts=t,this.socket=null,this.listeners=new Un,this.stopped=!0,this.generation=0,this.connectionAbort=null,this.lastSeq=null,this.connectNonce=null,this.serverCapabilities=[],this.connectSent=!1,this.connectRequestSent=!1,this.handshakeTimer=null,this.reconnectSignal=null,this.socketOpened=!1,this.helloReceived=!1,this.readyForRequests=!1,this.connectTiming=null,this.reconnectSupervisor=new On({initialMs:t.reconnect.initialMs,maxMs:t.reconnect.maxMs,factor:t.reconnect.multiplier,jitter:0}),this.requests=new Hn({createRequestId:t.createRequestId,createRequestError:t.createRequestError,createRequestTimeoutError:t.createRequestTimeoutError,createRequestAbortError:t.createRequestAbortError,requestTimeoutMs:t.requestTimeoutMs,nowMs:()=>this.nowMs(),onTiming:t.onRequestTiming,onCallbackError:t.onCallbackError})}get connected(){return this.socket?.isOpen()??!1}get hasPendingRequests(){return this.requests.hasPending}get connecting(){return this.connectSent&&!this.helloReceived}get opening(){return this.socket!==null&&!this.socketOpened}get hasUnboundedPendingRequests(){return this.requests.hasUnboundedPending}start(){if(this.socket||this.reconnectSignal)return;this.stopped=!1,this.reconnectSupervisor.cancel(),this.connect()}stop(){this.stopped=!0,this.connectionAbort?.abort(),this.clearHandshakeTimer(),this.reconnectSignal=null,this.reconnectSupervisor.reset();let t=this.socket;if(t&&this.opts.notifyStoppedClose)this.stoppedSocket={socket:t,context:this.closeContext()};this.socket=null,this.connectFailure=void 0,this.connectTiming=null,this.requests.flush(Error("gateway client stopped")),t?.close()}request(t,n,i){let a=this.socket;if(!a||this.socketOpened&&!a.isOpen())return Promise.reject(Error("gateway not connected"));if(typeof t!=="string"||t.length===0)return Promise.reject(Error("invalid request frame: method must be a non-empty string"));return this.requests.request(a,t,n,i,!this.readyForRequests)}addEventListener(t){return this.listeners.add(t)}closeSocket(t,n){this.connectionAbort?.abort(),this.socket?.close(t,n)}resetReconnectBackoff(t){this.reconnectSignal=null,this.reconnectSupervisor.reset(t)}recordTiming(t,n,i,a){let l=this.nowMs(),p=this.connectTiming;if(!p||p.generation!==n)return;if(p.hasChallenge||=t==="challenge",p.usedFallback||=t==="fallback",this.invoke("connect timing",()=>this.opts.onTiming?.({phase:t,generation:n,durationMs:Math.max(0,l-p.startedAtMs),phaseDurationMs:Math.max(0,l-p.lastAtMs),hasChallenge:p.hasChallenge,usedFallback:p.usedFallback,plan:i,detail:a})),p.lastAtMs=l,t==="hello"||t==="failed")this.connectTiming=null}connect(){if(this.stopped)return;let t=this.generation+1;this.lastSeq=null,this.connectNonce=null,this.connectChallengeTs=void 0,this.serverCapabilities=[],this.connectSent=this.connectRequestSent=!1,this.socketOpened=!1,this.helloReceived=!1,this.readyForRequests=!1,this.connectFailure=void 0;let n;try{n=this.opts.createSocket({open:()=>{if(!this.isActive(n,t))return;if(this.socketOpened=!0,this.recordTiming("socket-open",t),this.connectNonce){this.sendConnect(n,t);return}this.clearHandshakeTimer();let a=Date.now();this.handshakeTimer=setTimeout(()=>{if(this.handshakeTimer=null,!this.isActive(n,t)||this.connectSent||!n.isOpen())return;if(this.opts.handshake.mode==="fallback"){this.recordTiming("fallback",t),this.sendConnect(n,t);return}let l=Date.now()-a,p=Error(this.opts.handshake.timeoutMessage?.(l)??`gateway connect challenge timeout after ${l}ms`);this.opts.onConnectError?.(p),n.close(1008,"connect challenge timeout")},this.opts.handshake.timeoutMs),this.handshakeTimer.unref?.()},message:(a)=>this.handleMessage(n,t,a),close:(a,l)=>{if(this.socket!==n){if(this.stoppedSocket?.socket===n){let y={...this.stoppedSocket.context,code:a,reason:l};this.stoppedSocket=void 0,this.invoke("close",()=>this.opts.onClose?.(y,{retry:!1,notify:!0}))}return}this.socket=null,this.connectionAbort?.abort(),this.clearHandshakeTimer();let p={...this.closeContext(),code:a,reason:l,generation:t};this.connectFailure=void 0;let f=this.opts.resolveClose(p);if(this.requests.flush(f.pendingError??p.connectFailure?.error??Error(`gateway closed (${a}): ${l}`)),this.invoke("close",()=>this.opts.onClose?.(p,f)),f.retry&&!this.stopped&&!this.socket&&!this.reconnectSignal){let y=p.connectFailure?.error,S=y instanceof z&&y.retryable&&y.retryAfterMs!==void 0&&Number.isFinite(y.retryAfterMs)&&y.retryAfterMs>0?y.retryAfterMs:void 0;this.scheduleReconnect(f.reconnectDelayMs??p.connectFailure?.reconnectDelayMs,S)}},error:(a)=>{if(!this.isActive(n,t)||this.connectSent)return;this.connectFailure={error:a},this.opts.onConnectError?.(a)}})}catch(a){let l=K(a);if(this.opts.onSocketFactoryError?.(l),this.opts.onConnectError?.(l),this.opts.rethrowSocketFactoryError?.(l)){if(this.generation>0&&!this.stopped&&!this.socket&&!this.reconnectSignal)this.opts.onReconnectStopped?.(l);throw l}if(this.opts.shouldRetrySocketFactoryError?.(l)&&!this.stopped&&!this.socket&&!this.reconnectSignal)this.scheduleReconnect();else if(this.generation>0&&!this.stopped&&!this.socket&&!this.reconnectSignal)this.opts.onReconnectStopped?.(l);return}this.generation=t,this.connectionAbort=new AbortController,this.socket=n;let i=this.nowMs();this.connectTiming={generation:t,startedAtMs:i,lastAtMs:i,hasChallenge:!1,usedFallback:!1}}sendConnect(t,n){if(!this.isActive(t,n)||!t.isOpen()||this.connectSent)return;this.connectSent=!0,this.clearHandshakeTimer(),this.handshakeTimer=ve(()=>{if(this.isActive(t,n)&&!this.helloReceived)t.close(4000,"connect timeout")});let i;try{i=this.opts.buildConnectPlan({nonce:this.connectNonce,challengeTs:this.connectChallengeTs,serverCapabilities:this.serverCapabilities,generation:n,...this.connectAuthority(t,n)})}catch(a){this.handleConnectPlanError(t,n,a);return}if(i instanceof Promise){i.then((a)=>this.sendConnectPlan(t,n,a)).catch((a)=>this.handleConnectPlanError(t,n,a));return}this.sendConnectPlan(t,n,i)}handleConnectPlanError(t,n,i){if(!this.isConnectCurrent(t,n))return;let a=K(i),l=this.opts.onConnectPlanError?.(a)??he;if(this.opts.onConnectError?.(l.error??a),l.stop)this.stopped=!0;t.close(l.closeCode,l.closeReason)}sendConnectPlan(t,n,i){if(!this.isConnectCurrent(t,n))return;let a={...this.connectAuthority(t,n),generation:n,nonce:this.connectNonce,challengeTs:this.connectChallengeTs,plan:i};this.recordTiming("connect-plan-ready",n,i),this.requests.request(t,"connect",this.opts.buildConnectParams(i),{onSent:()=>{this.connectRequestSent=!0,this.recordTiming("request-sent",n,i)}}).then((l)=>{if(!this.isConnectCurrent(t,n))return;this.helloReceived=!0,this.requests.setSuspensionPhase(l.snapshot?.suspension?.phase),this.clearHandshakeTimer(),this.connectFailure=void 0,this.reconnectSupervisor.reset(),this.recordTiming("hello",n,i);let p=()=>{if(!this.isConnectCurrent(t,n))return;if(this.invoke("hello",()=>this.opts.onHello?.(l)),!this.isConnectCurrent(t,n))return;if(this.requests.releaseHeldRequests(()=>this.isConnectCurrent(t,n)),this.isConnectCurrent(t,n))this.readyForRequests=!0},f=this.opts.onConnectHello?.(l,a);if(f instanceof Promise)return f.then(p);return p()}).catch((l)=>{if(!this.isActive(t,n))return;let p=l instanceof z?l:new z({message:String(l)});this.connectFailure={error:p};let f=this.opts.onConnectFailure?.(p,a)??he,y=(S)=>{if(!this.isActive(t,n))return;if(this.connectFailure={error:p,reconnectDelayMs:S.reconnectDelayMs},S.keepOpen){this.clearHandshakeTimer();return}if(S.stop)this.stopped=!0;this.connectionAbort?.abort(),t.close(S.closeCode,S.closeReason)};if(f instanceof Promise)return f.then(y);return y(f)}).catch((l)=>{if(!this.isConnectCurrent(t,n))return;this.opts.onConnectError?.(K(l)),this.closeSocket(he.closeCode,he.closeReason)})}handleMessage(t,n,i){if(!this.isActive(t,n)||this.connectionAbort?.signal.aborted)return;let a;try{a=JSON.parse(i)}catch(l){this.opts.onParseError?.(l);return}if(lt(a)){if(this.opts.onActivity?.(),a.event==="connect.challenge"){let p=a.payload,f=typeof p?.nonce==="string"?p.nonce.trim():"";if(!f){if(this.opts.handshake.mode==="require-challenge"){let S=Error("gateway connect challenge missing nonce");this.opts.onConnectError?.(S),t.close(1008,"connect challenge missing nonce")}return}this.connectNonce=f,this.serverCapabilities=wn(p?.capabilities);let y=p?.ts;this.connectChallengeTs=typeof y==="number"&&Number.isSafeInteger(y)&&y>=0?y:null,this.recordTiming("challenge",n),this.sendConnect(t,n);return}let l=a.seq;if(l!==void 0){if(this.lastSeq!==null&&l>this.lastSeq+1){let p=this.lastSeq+1,f=Ee(a.payload).state;if(a.event==="chat"&&(f==="final"||f==="error"||f==="aborted"))this.dispatchEvent(t,n,a);if(!this.isActive(t,n)||this.connectionAbort?.signal.aborted)return;if(this.invoke("gap",()=>this.opts.onGap?.({expected:p,received:l})),this.isActive(t,n)&&!this.connectionAbort?.signal.aborted)this.closeSocket(4000,"event sequence gap");return}this.lastSeq=l}this.dispatchEvent(t,n,a);return}if(!ut(a))return;this.opts.onActivity?.(),this.requests.handleResponse(a)}dispatchEvent(t,n,i){let a=this.listeners.snapshot();if(i.event==="gateway.suspension")this.requests.setSuspensionPhase(Ee(i.payload).phase);else if(i.event==="shutdown"&&typeof Ee(i.payload).restartExpectedMs==="number")this.requests.setSuspensionPhase("draining");this.invoke("event",()=>this.opts.onEvent?.(i));for(let[l,p]of a){if(!this.isActive(t,n)||this.connectionAbort?.signal.aborted)return;if(this.listeners.isCurrent(l,p))this.invoke("event listener",()=>l(i))}}scheduleReconnect(t,n=0){if(t!==void 0)this.reconnectSupervisor.nextDelayOverrideMs=t;let i=this.reconnectSupervisor.next();if(!i)return;this.reconnectSignal=i.signal;let a=t;if(a===void 0){let l=Math.max(i.delayMs,n),p=Math.max(this.opts.reconnect.maxMs,Math.min(Number.MAX_VALUE,n*1.2)),f=Math.max(n,Math.min(l,p/1.2)),y=Math.min(l*1.2,p);a=Math.ceil(f+Math.random()*(y-f))}a=At(a),Mn(a,i.signal).then(()=>{if(this.reconnectSignal!==i.signal)return;this.reconnectSignal=null,this.invoke("reconnect",()=>this.connect())},()=>{if(this.reconnectSignal===i.signal)this.reconnectSignal=null}),this.invoke("reconnect scheduled",()=>this.opts.onReconnectScheduled?.(a,i.signal))}closeContext(){return{generation:this.generation,socketOpened:this.socketOpened,helloReceived:this.helloReceived,connectRequestSent:this.connectRequestSent,connectFailure:this.connectFailure}}isConnectCurrent(t,n){return this.isActive(t,n)&&t.isOpen()&&!this.connectionAbort?.signal.aborted}connectAuthority(t,n){let i=this.connectionAbort?.signal;if(!i)throw Error("gateway connection authority is unavailable");return{signal:i,assertCurrent:()=>{if(i.throwIfAborted(),!this.isConnectCurrent(t,n))throw Error("gateway connection retired")}}}isActive(t,n){return!this.stopped&&this.socket===t&&this.generation===n}nowMs(){return this.opts.nowMs?.()??Date.now()}clearHandshakeTimer(){this.handshakeTimer=we(this.handshakeTimer)}invoke(t,n){try{n()}catch(i){this.opts.onCallbackError?.(t,i)}}},qn=new Set([C.AUTH_TOKEN_MISSING,C.AUTH_BOOTSTRAP_TOKEN_INVALID,C.AUTH_PASSWORD_MISSING,C.AUTH_PASSWORD_MISMATCH,C.AUTH_RATE_LIMITED,C.AUTH_DEVICE_TOKEN_MISMATCH,C.AUTH_SCOPE_MISMATCH,C.AUTH_IDENTITY_HEADER_REQUIRED,C.AUTH_VERIFIED_USER_REQUIRED,C.CONTROL_UI_BUILD_MISMATCH,C.PAIRING_REQUIRED,C.PAIRING_REJECTED,C.PAIRING_EXPIRED,C.CONTROL_UI_DEVICE_IDENTITY_REQUIRED,C.DEVICE_IDENTITY_REQUIRED]);function vt(t){let n=q(t.details);if(!n)return!1;let i=ke(t.details);if(n===C.PAIRING_REQUIRED&&(i?.pauseReconnect===!1||i?.recommendedNextStep==="wait_then_retry"))return!1;if(n===C.AUTH_TOKEN_MISMATCH)return t.tokenMismatchIsTerminal===!0&&!t.deviceTokenRetryPending;if(n===C.AUTH_IDENTITY_HEADER_REQUIRED)return!t.deviceTokenRetryPending;return qn.has(n)||t.protocolMismatchIsTerminal===!0&&n===C.PROTOCOL_MISMATCH||t.clientVersionMismatchIsTerminal===!0&&n===C.CLIENT_VERSION_MISMATCH}import{Buffer as wt}from"buffer";function Ct(t,n="utf8"){if(Array.isArray(t))return wt.concat(t).toString(n);return t instanceof ArrayBuffer?wt.from(t).toString(n):t.toString(n)}import{createRequire as Fn}from"module";var Mt={WEBCHAT_UI:"webchat-ui",CONTROL_UI:"openclaw-control-ui",BROWSER_COPILOT:"openclaw-browser-copilot",TUI:"openclaw-tui",WEBCHAT:"webchat",CLI:"cli",GATEWAY_CLIENT:"gateway-client",MACOS_APP:"openclaw-macos",LINUX_APP:"openclaw-linux",IOS_APP:"openclaw-ios",WATCHOS_APP:"openclaw-watchos",ANDROID_APP:"openclaw-android",NODE_HOST:"node-host",WORKER:"openclaw-worker",TEST:"test",FINGERPRINT:"fingerprint",PROBE:"openclaw-probe"},se=Mt,G={WEBCHAT:"webchat",CLI:"cli",UI:"ui",BACKEND:"backend",NODE:"node",WORKER:"worker",PROBE:"probe",TEST:"test"};var vs=new Map(Object.values(Mt).map((t)=>[t,t])),ws=new Map(Object.values(G).map((t)=>[t,t]));var W=4,Ot=4,P=3,Nt=3;var oe=g(Pt(),1);import{randomUUID as Gn}from"crypto";import{isIP as Wn}from"net";import{TLSSocket as $n,checkServerIdentity as Bn}from"tls";import _e from"path";function Vn(t){try{return JSON.parse(t)}catch{return}}function Kn(t){return/^[\t\n\r ]*\{/.test(t)?Et(Vn(t)):void 0}var jn=new Set(["token","key","api_key","apikey","secret","access_token","auth_token","password","pass","passwd","auth","jwt","session","id_token","code","client_secret","app_secret","hook_token","refresh_token","signature","x_amz_signature","x_amz_security_token","private_key","credential","authorization","sig","x_api_key","x_access_token","x_auth_token"]),kt=/[\p{C}\p{Z}\u115F\u1160\u3164\uFFA0+]/gu,zn=/(?:^|_)token(?:_[a-f0-9]{16,})?$/u,Yn=/\/bot\d{6,}(?::|%3[aA])[A-Za-z0-9_-]{20,}(?=\/|$)/giu,X=8,Qn=/(?:^|[^a-z\d+.-])[a-z][a-z\d+.-]{0,31}:/iu,Xn=/\b(?:https?|wss?|ftp):[\\/]{0,2}[^\\/?#\s]*/giu,Jn=/\b(?:https?|wss?|ftp):[\\/]{0,2}[^\s]*@[^\\/?#\s]*/giu,Zn=/[\\/]{2,}[^\\/?#\s]*/gu;function Ft(t){return t.replace(Yn,"/bot***")}function er(t){let n=t.replace(kt,"");for(let i=0;i<=X;i+=1){let a;try{a=decodeURIComponent(n).replace(kt,"")}catch{break}if(a===n)return{value:j(n).replaceAll("-","_"),unresolvedEncoding:!1};n=a}return{value:j(n).replaceAll("-","_"),unresolvedEncoding:n.includes("%")}}function Q(t){if(Qn.test(t))return!0;let n=t.search(/\/\/|\\\\/u);if(n>=0&&t.includes("@",n+2))return!0;let i=t.search(/[?&]/u);if(i>=0&&t.includes("=",i+1))return!0;let a=t.indexOf("#");if(a>=0&&t.includes("=",a+1))return!0;return/%[\da-f]{2}/iu.test(t)}function Ve(t){let n=er(t);return n.unresolvedEncoding||jn.has(n.value)||zn.test(n.value)}function tr(t){try{let n=new URL(t),i=!1,a=Ft(n.pathname);if(a!==n.pathname)n.pathname=a,i=!0;if(n.username||n.password)n.username=n.username?"***":"",n.password=n.password?"***":"",i=!0;for(let l of Array.from(n.searchParams.keys()))if(Ve(l))n.searchParams.set(l,"***"),i=!0;return i?n.toString():t}catch{return t}}function $e(t,n){let i=new URLSearchParams(t),a=[],l=new Set,p=!1;for(let[f,y]of i){if(Ve(f)){if(p=!0,!l.has(f))l.add(f),a.push([f,"***"]);continue}let S=Be(f,n+1),v=Be(y,n+1);if(S!==f||v!==y)p=!0;a.push([S,v])}if(!p)return t;return new URLSearchParams(a).toString()}function Te(t){return Ft(Gt(t).replace(/([?&])([^=&]+)=([^&]*)/g,(n,i,a)=>Ve(a)?`${i}${a}=***`:n))}function Dt(t,n){let i=t.slice(n),a=i.lastIndexOf("@");if(a<0)return t;return`${t.slice(0,n)}***:***@${i.slice(a+1)}`}function Ge(t,n){let i=n;while(t[i]==="/"||t[i]==="\\")i+=1;return i}function Gt(t){return t.replace(Xn,(n)=>Dt(n,Ge(n,n.indexOf(":")+1))).replace(Jn,(n)=>{let i=Ge(n,n.indexOf(":")+1),a=n.lastIndexOf("@"),l=n.slice(i).search(/[\\/?#]/u);if(a<0||l<0)return n;let p=i+l;if(p>=a)return n;let f=n.indexOf(":",i);if(f<0||f>p)return n;let y=n.slice(i,p),S=n.slice(f+1,p);if(/^\d+$/u.test(S)||/^\[[^\]]+\](?::\d+)?$/u.test(y))return n;return`${n.slice(0,i)}***:***@${n.slice(a+1)}`}).replace(Zn,(n)=>Dt(n,Ge(n,0)))}function Ke(t){for(let n of t.matchAll(/(?:\b(?:https?|wss?|ftp):[\\/]{0,2}|[\\/]{2,})/giu)){let i=t.slice((n.index??0)+n[0].length),a=i.search(/(?<!\*\*\*:\*\*\*)@/u),l=i.search(/[\\/?#]/u),p=i.slice(l+1,a);if(a>=0&&(l<0||a<=l||i[l]==="/"&&(p.includes(":")||/^[^/?#\s]+\.[^/?#\s]+(?:[/?#]|$)/u.test(i.slice(a+1)))))return!0}return!1}function nr(t,n){let i=t.indexOf("#");if(i<0)return t;let a=t.slice(i+1),l=je(a,n+1);return l===a?t:`${t.slice(0,i+1)}${l}`}function je(t,n){if(!t)return t;if(n>X&&Q(t))return"***";let i=$t(t,n);if(i.parsedWholeUrl)return Te(i.value);let a=t.search(/[?&]/u),l=t.indexOf("=");if(l>=0&&(a<0||l<a))return $e(t,n);let p=t.indexOf("?");if(p>=0){let v=$e(t.slice(p+1),n);return`${Bt(Te(t.slice(0,p+1)),n+1)}${v}`}let f=Te(t);if(!Q(f))return f;let y;try{y=decodeURIComponent(f)}catch{return"***"}if(y===f)return f;let S=je(y,n+1);return S===y?f:encodeURIComponent(S)}function Wt(t,n){if(!Q(t))return t;if(n>X)return"***";let i;try{i=decodeURIComponent(t)}catch{return"***"}if(i===t)return t;let a=Ae(i,n);if(a.value!==i||Ke(i))return a.value!==i?a.value:"***";if(a.parsedWholeUrl)return t;let l=Wt(i,n+1);return l===i?t:l}function $t(t,n){try{let i=tr(t),a=new URL(i);if(n>X)return{value:"***",parsedWholeUrl:!0};let l=i!==t,p=Gt(Wt(a.pathname,n+1));if(p!==a.pathname){let v=a.pathname;if(a.pathname=p,a.pathname===v)return{value:i,parsedWholeUrl:!1};l=!0}let f=$e(a.search.slice(1),n);if(f!==a.search.slice(1))a.search=f,l=!0;let y=a.hash.slice(1),S=je(y,n+1);if(S!==y)a.hash=S,l=!0;return{value:l?a.toString():t,parsedWholeUrl:!0}}catch{return{value:t,parsedWholeUrl:!1}}}function Ae(t,n){let i=$t(t,n);if(i.parsedWholeUrl)return i;return{value:Bt(nr(Te(i.value),n),n+1),parsedWholeUrl:!1}}function Bt(t,n){if(!Q(t))return t;if(n>X)return"***";let i;try{i=decodeURIComponent(t)}catch{return"***"}if(i===t)return t;let a=Ae(i,n+1);if(a.value!==i||a.parsedWholeUrl)return a.value===i?t:a.value;return Ke(i)?"***":t}function Be(t,n){if(!Q(t))return t;if(n>X)return"***";let i=Ae(t,n);if(i.value!==t)return i.value;if(Ke(t))return"***";if(i.parsedWholeUrl)return t;let a;try{a=decodeURIComponent(t)}catch{return"***"}if(a===t||!Q(a))return t;let l=Be(a,n+1);return l===a?t:encodeURIComponent(l)}function rr(t){return Ae(t,0).value}oe.default.IPv4.parse("198.18.0.0");function Vt(t){return t.kind()==="ipv6"}function Kt(t){return Vt(t)&&t.isIPv4MappedAddress()?t.toIPv4Address():t}function sr(t){let n=k(t);if(!n)return;return n.startsWith("[")&&n.endsWith("]")?n.slice(1,-1):n}function ze(t){let n=sr(t);if(!n)return;return oe.default.IPv4.isValidFourPartDecimal(n)||oe.default.IPv6.isValid(n)?oe.default.parse(n):void 0}function or(t){return ir(t)?.toString()}function ir(t){let n=ze(t);if(!n)return;let i=Kt(n);if(Vt(i)&&i.zoneId)i.zoneId=i.zoneId.toLowerCase();return i}function ar(t){let n=ze(t);if(!n)return!1;return Kt(n).range()==="loopback"}function Ut(t){let n=t instanceof Error?t.message:String(t);return n==="gateway client stopped"||n==="Error: gateway client stopped"}function L(t){return String(t).replace(/\/\/([^@/?#\s]+)@/g,"//***:***@").replace(/(Authorization:\s*Bearer\s+)[^\s]+/giu,"$1***").replace(/([?&])([^=&\s]+)=([^&#\s"'<>)]*)/g,(n,i,a)=>/(?:token|password|secret|key|auth|credential)/iu.test(a)?`${i}${a}=***`:n)}var cr=/^[a-fA-F0-9]{64}$/u,lr=/^(?:[a-fA-F0-9]{2}:){31}[a-fA-F0-9]{2}$/u;function ie(t){let n=(t??"").trim().replace(/^sha256:/iu,"");if(cr.test(n))return n.toLowerCase();return lr.test(n)?n.replaceAll(":","").toLowerCase():""}function jt(t){if(!t)return null;let n=t.toLowerCase().trim(),i=n.replace(/\.+$/,"");if(i==="localhost")return{isLocalhost:!0,unbracketedHost:i};return{isLocalhost:!1,unbracketedHost:n.startsWith("[")&&n.endsWith("]")?n.slice(1,-1):n}}function zt(t){let n=or(t);return n?ze(n):void 0}var ur=class{constructor(t){this.storage=t,this.operations=new Set}load(t){let n=()=>(t.signal?.throwIfAborted(),t.assertCurrent?.(),this.track(this.storage.loadDeviceAuthToken(t)));return this.operations.size>0?this.settle().then(n):n()}store(t,n,i){let a=(p)=>{let f=K(p),y=!1;try{y=i(f)}catch{}if(!y)this.unreportedPersistenceFailure??=f;throw f};t.signal?.throwIfAborted(),t.assertCurrent?.();let l=this.storage.storeDeviceAuthToken(t);return l instanceof Promise?this.track(l.then(n).catch(a)):n()}clear(t,n,i){let a=()=>{if(!i())return;let l=[n.token,n.receiptToken].filter((S)=>typeof S==="string"),p=[...new Set(l)];if(n.token===void 0&&p.length===0)p.push(void 0);let f=(S)=>{t.signal?.throwIfAborted(),t.assertCurrent?.();let v=this.storage.clearDeviceAuthToken({...t,...S===void 0?{}:{expectedToken:S}});return v instanceof Promise?v.then(()=>{}):void 0},y;for(let S of p)y=y?y.then(()=>f(S)):f(S);return y};return this.track(n.persistence?n.persistence.then(a,a):a())}async settle(){await Promise.allSettled(this.operations)}async drain(){await this.settle();let t=this.unreportedPersistenceFailure;if(this.unreportedPersistenceFailure=void 0,t)throw t}track(t){if(!(t instanceof Promise))return t;return this.operations.add(t),t.then(()=>this.operations.delete(t),()=>this.operations.delete(t)),t}},dr=2048,pr=1000;async function fr(t){return await new Promise((n)=>{let i=[],a=0,l=!1,p=()=>{if(l)return;l=!0,clearTimeout(S),t.off("data",y),t.off("end",p),t.off("error",p),t.off("aborted",p),n(Buffer.concat(i,a).toString("utf8").replace(/\s+/gu," ").trim())},f=()=>{p(),t.destroy()},y=(v)=>{let w=Buffer.isBuffer(v)?v:Buffer.from(v),R=dr-a;if(R>0){let _=w.subarray(0,R);i.push(_),a+=_.byteLength}if(w.byteLength>=R)f()},S=setTimeout(f,pr);S.unref?.(),t.on("data",y),t.once("end",p),t.once("error",p),t.once("aborted",p)})}function hr(t,n,i){let a=t.platform??n;if(!i)return{platform:a,deviceFamily:t.deviceFamily,modelIdentifier:t.modelIdentifier};return{platform:a==="macos"?"darwin":a==="windows"?"win32":a}}function We(t){if(t.role!=="node"||t.mode!==G.NODE||t.clientName!==se.NODE_HOST)return!1;return(t.minProtocol??P)===P&&(t.maxProtocol??W)===W}var B=class extends z{constructor(t){super({...t,message:ct({message:t.message,details:t.details})});this.name="GatewayClientRequestError"}},Er=class extends Fe{constructor(t){super(t,`gateway request timeout for ${t.method}`);this.name="GatewayClientRequestTimeoutError"}},yr=Symbol("gateway.connectAssemblyError");function mr(t){return Object.defineProperty(t,yr,{configurable:!0,value:!0}),t}function Ir(t){return t instanceof URL?t:URL.parse(t)}function gr(t){return Ir(t)?.protocol==="wss:"}var Tr=new Set(["loopback","private","linkLocal","carrierGradeNat"]),_r=new Set(["loopback","linkLocal","uniqueLocal","deprecatedSiteLocal"]);function Ar(t){return(t.kind()==="ipv4"?Tr:_r).has(t.range())}function Sr(t){let n=jt(t);return Boolean(n&&(n.isLocalhost||ar(n.unbracketedHost)))}function Rr(t){let n=jt(t);if(!n)return!1;if(n.isLocalhost)return!0;let i=zt(n.unbracketedHost);return Boolean(i&&Ar(i))}function vr(t){if(Rr(t))return!0;let n=t.toLowerCase().trim().replace(/\.+$/,"");return n.endsWith(".local")||n.endsWith(".ts.net")}function wr(t,n){let i=URL.parse(t);if(!i)return!1;let a=i.protocol==="https:"?"wss:":i.protocol==="http:"?"ws:":i.protocol;if(a==="wss:")return!0;if(a!=="ws:")return!1;if(vr(i.hostname))return!0;if(n?.allowPrivateWs===!0)return zt(i.hostname.startsWith("[")&&i.hostname.endsWith("]")?i.hostname.slice(1,-1):i.hostname)===void 0;return!1}var Y=class extends Error{},xt=class extends Error{};function Cr(t){let n=gr(t.url);if(t.tlsFingerprint&&!n)throw new Y("gateway tls fingerprint requires wss:// gateway url");let i=(t.env??process.env).OPENCLAW_ALLOW_INSECURE_PRIVATE_WS==="1";if(!wr(t.url,{allowPrivateWs:i}))throw new Y(`SECURITY ERROR: Cannot connect to "${URL.parse(t.url)?.hostname||t.url}" over plaintext ws://. Both credentials and chat data would be exposed to network interception. Use wss:// for remote URLs. Safe defaults: keep gateway.bind=loopback and connect via SSH tunnel (ssh -N -L 18789:127.0.0.1:18789 user@gateway-host), or use Tailscale Serve/Funnel. `+(i?"":"Break-glass (trusted private networks only): set OPENCLAW_ALLOW_INSECURE_PRIVATE_WS=1. ")+"Run `openclaw doctor --fix` for guidance.");let a=t.normalizeTlsFingerprint??ie,l=t.tlsFingerprint?ie(t.tlsFingerprint):void 0;if(t.tlsFingerprint&&!l)throw new Y("gateway tls fingerprint must be a SHA-256 fingerprint");let p={...t.options};if(n&&t.tlsServerName){let f=t.tlsServerName;p.servername=Wn(f)?"":f,p.checkServerIdentity=(y,S)=>Bn(f,S)}if(n&&l)Mr(p,l,a);return{options:p}}function Mr(t,n,i=ie){t.rejectUnauthorized=!1;let a={...t.headers},l=Object.entries(a).filter(([p])=>p.toLowerCase()==="expect");for(let[p]of l)delete a[p];t.headers=a,t.finishRequest=(p)=>{p.once("socket",(f)=>{if(!(f instanceof $n)){p.destroy(new xt("gateway tls fingerprint unavailable"));return}let y=()=>{if(p.destroyed)return;let S=ie(f.getPeerCertificate()?.fingerprint256),v=S?i(S):"";if(!v||v!==i(n)){p.destroy(new xt(v?"gateway tls fingerprint mismatch":"gateway tls fingerprint unavailable"));return}for(let[w,R]of l)if(R!==void 0)p.setHeader(w,R);p.end()};if(f.secureConnecting)f.once("secureConnect",y),p.once("close",()=>f.off("secureConnect",y));else y()})}}var Se=Fn(import.meta.url),Ye=_e.dirname(Se.resolve("ws/package.json")),Ht=Se(_e.join(Ye,"lib/websocket.js"));Se(_e.join(Ye,"lib/websocket-server.js"));Se(_e.join(Ye,"lib/stream.js"));var Or={loadOrCreateDeviceIdentity:()=>{return},signDevicePayload:()=>{throw Error("GatewayClient device signature dependency is not configured")},publicKeyRawBase64UrlFromPem:()=>{throw Error("GatewayClient public key dependency is not configured")},loadDeviceAuthToken:()=>null,storeDeviceAuthToken:()=>{},clearDeviceAuthToken:()=>{},beforeConnect:()=>{},registerGatewayLoopbackBypass:()=>{return},logDebug:()=>{},logError:()=>{},redactForLog:(t)=>t,normalizeTlsFingerprint:ie};function Nr(t){return Object.fromEntries(Object.entries(Or).map(([n,i])=>[n,t?.[n]??i]))}var br="ws://127.0.0.1:18789",Pr="0.0.0",qt=class extends Y{},kr=250,Dr=1000,Ur=1,Yt=class{constructor(t){this.ws=null,this.stopped=!1,this.useLegacyNodeProtocolEnvelope=!1,this.nodeProtocolTransitionPending=!1,this.pendingDeviceTokenRetry=!1,this.deviceTokenRetryBudgetUsed=!1,this.approvalRuntimeTokenCompatibilityDisabled=!1,this.approvalRuntimeTokenRetryBudgetUsed=!1,this.lastTick=null,this.tickIntervalMs=30000,this.tickTimer=null,this.pendingStop=null,this.transportValidated=!1,this.suppressedTransientPreHelloCleanCloses=0,this.deps=Nr(t.hostDeps),this.deviceAuth=new ur(this.deps),this.opts={...t,deviceIdentity:t.deviceIdentity===null?void 0:t.deviceIdentity??this.deps.loadOrCreateDeviceIdentity()},this.requestTimeoutMs=typeof t.requestTimeoutMs==="number"&&Number.isFinite(t.requestTimeoutMs)?t.requestTimeoutMs:Ce;let n=ot(this.opts.connectChallengeTimeoutMs,{env:this.opts.env,configuredTimeoutMs:this.opts.preauthHandshakeTimeoutMs});this.protocol=new Rt({createSocket:(i)=>this.createSocket(i),createRequestId:Gn,createRequestError:(i)=>new B(i),createRequestTimeoutError:(i,a,l)=>new Er({method:i,timeoutMs:a,requestSent:l}),createRequestAbortError:(i)=>Ie(`gateway request aborted for ${i}`),buildConnectPlan:({nonce:i,challengeTs:a,serverCapabilities:l,generation:p,...f})=>{if(!i)throw Error("gateway connect challenge missing nonce");if(this.opts.deviceIdentity&&a==null)throw Error("gateway connect challenge timestamp invalid");let y=this.opts.role??"operator",S=(w)=>{f.assertCurrent();let R=a??Date.now(),_=yt({token:this.opts.token,bootstrapToken:this.opts.bootstrapToken,preferBootstrapToken:this.opts.preferBootstrapToken,deviceToken:this.opts.deviceToken,password:this.opts.password,approvalRuntimeToken:this.approvalRuntimeTokenCompatibilityDisabled?void 0:this.opts.approvalRuntimeToken,agentRuntimeIdentityToken:this.opts.agentRuntimeIdentityToken,storedToken:w?.token,storedScopes:w?.scopes,pendingDeviceTokenRetry:this.pendingDeviceTokenRetry,trustedDeviceTokenRetry:this.isTrustedDeviceRetryEndpoint()}),{authDeviceToken:c,authApprovalRuntimeToken:d,authAgentRuntimeIdentityToken:E,signatureToken:h,resolvedDeviceToken:A,storedToken:I,storedScopes:M,usingStoredDeviceToken:O}=_;if(this.pendingDeviceTokenRetry&&c)this.pendingDeviceTokenRetry=!1;let b=mt(_),N=It({requestedScopes:this.opts.scopes,usingStoredDeviceToken:O,storedScopes:M,defaultScopes:["operator.admin"]}),x=this.opts.mode??G.BACKEND,J=this.opts.clientName??se.GATEWAY_CLIENT,le=y==="node"&&x===G.NODE&&J===se.NODE_HOST,ue=We(this.opts),H=le&&(this.useLegacyNodeProtocolEnvelope||this.opts.maxProtocol===P&&(this.opts.minProtocol??P)<=P),F=H?P:ue?W:this.opts.minProtocol??(x===G.PROBE?Nt:y==="node"&&x===G.NODE?P:Ot),de=H?P:ue?W:this.opts.maxProtocol??W,{platform:pe,deviceFamily:Xe,modelIdentifier:cn}=hr(this.opts,process.platform,H),Je={minProtocol:F,maxProtocol:de,client:{id:J,displayName:this.opts.clientDisplayName,version:this.opts.clientVersion??Pr,buildId:this.opts.clientBuildId,platform:pe,deviceFamily:Xe,modelIdentifier:cn,mode:x,instanceId:this.opts.instanceId},...Tt({caps:Array.isArray(this.opts.caps)?this.opts.caps:[],modelCatalog:H?void 0:this.opts.modelCatalog,serverCapabilities:l}),commands:Array.isArray(this.opts.commands)?this.opts.commands:void 0,computerUse:H?void 0:this.opts.computerUse,workerRuns:H?void 0:this.opts.workerRuns,permissions:this.opts.permissions&&typeof this.opts.permissions==="object"?this.opts.permissions:void 0,pathEnv:this.opts.pathEnv,auth:b,role:y,scopes:N,device:void 0};if(this.opts.deviceIdentity){let ln=ht({deviceId:this.opts.deviceIdentity.deviceId,clientId:this.opts.clientName??se.GATEWAY_CLIENT,clientMode:x,role:y,scopes:N,signedAtMs:R,token:h??null,nonce:i,platform:pe,deviceFamily:Xe}),un=this.deps.signDevicePayload(this.opts.deviceIdentity.privateKeyPem,ln);Je.device={id:this.opts.deviceIdentity.deviceId,publicKey:this.deps.publicKeyRawBase64UrlFromPem(this.opts.deviceIdentity.publicKeyPem),signature:un,signedAt:R,nonce:i}}let Ze={params:Je,authApprovalRuntimeToken:d,authAgentRuntimeIdentityToken:E,resolvedDeviceToken:A,storedScopes:M,storedToken:I,usingStoredDeviceToken:O};return this.connectionStoredToken={generation:p,token:Ze.storedToken??null},Ze},v=this.opts.deviceIdentity?this.deviceAuth.load({deviceId:this.opts.deviceIdentity.deviceId,role:y,env:this.opts.env,...f}):null;return v instanceof Promise?v.then(S):S(v)},buildConnectParams:(i)=>i.params,onConnectPlanError:(i)=>{this.stopped=!0;let a=mr(i),l=`gateway connect failed: ${L(i)}`;if(this.opts.mode===G.PROBE||Ut(i))this.logDebug(l);else this.logError(l);return{closeCode:1008,closeReason:"connect failed",stop:!0,error:a}},onConnectHello:(i,a)=>{let l=a.plan;a.assertCurrent();let p=this.opts.role??"operator",f=i.auth,y=this.connectionStoredToken,S=()=>{if(f?.deviceToken&&(f.role??p)===p&&y)y.token=f.deviceToken;if(this.opts.preferBootstrapToken)this.opts.token=void 0,this.opts.bootstrapToken=void 0,this.opts.password=void 0,this.opts.preferBootstrapToken=!1},v=void 0;if(f?.deviceToken&&this.opts.deviceIdentity){let R=f.role??p,_=R===p&&f.deviceToken===l.storedToken?l.storedScopes??f.scopes??[]:f.scopes??[];if(R===p&&y)y.receiptToken=f.deviceToken;if(v=this.deviceAuth.store({deviceId:this.opts.deviceIdentity.deviceId,role:R,token:f.deviceToken,scopes:_,env:this.opts.env,...R===p?{expectedToken:l.storedToken??null}:{}},S,(c)=>{l.persistenceFailed=!0;let d=this.notifyConnectError(c);return this.logError(`gateway device token persistence failed: ${L(c)}`),d}),y&&v instanceof Promise)y.persistence=v}else S();let w=()=>{if(a.signal.aborted||!this.protocol.connected)return;a.assertCurrent();let R=this.useLegacyNodeProtocolEnvelope&&We(this.opts)&&i.protocol>P;if(R)this.useLegacyNodeProtocolEnvelope=!1;if(this.nodeProtocolTransitionPending=!1,this.pendingDeviceTokenRetry=!1,this.deviceTokenRetryBudgetUsed=!1,this.suppressedTransientPreHelloCleanCloses=0,this.tickIntervalMs=typeof i.policy?.tickIntervalMs==="number"?i.policy.tickIntervalMs:30000,R){this.protocol.resetReconnectBackoff(250),this.protocol.closeSocket(1012,"gateway protocol upgraded");return}this.lastTick=Date.now(),this.startTickWatch()};return v instanceof Promise?v.then(w):w()},onHello:(i)=>{this.opts.onHelloOk?.(i)},onConnectFailure:(i,a)=>{let l=a.plan;if(l.persistenceFailed)return{closeCode:1008,closeReason:"connect failed"};let p=i instanceof B?q(i.details):null,f=this.opts.deviceIdentity&&l.usingStoredDeviceToken&&p===C.AUTH_DEVICE_TOKEN_MISMATCH?this.clearDeviceToken(this.opts.deviceIdentity.deviceId,{token:l.storedToken}):void 0,y=this.resolveConnectRequestFailure(i,l);return f instanceof Promise?f.then(()=>y):y},resolveClose:(i)=>this.resolveClose(i),onClose:(i,a)=>{if(clearInterval(this.tickTimer??void 0),this.tickTimer=null,a.notify)this.opts.onClose?.(i.code,i.reason,this.closeInfo(i))},notifyStoppedClose:!0,onConnectError:(i)=>this.notifyConnectError(i),onReconnectStopped:(i)=>this.notifyReconnectPaused({code:1008,reason:i.message,detailCode:null}),onParseError:(i)=>this.logDebug(`gateway client parse error: ${L(i)}`),onEvent:(i)=>this.opts.onEvent?.(i),onGap:(i)=>this.opts.onGap?.(i),onRequestTiming:(i)=>this.opts.onRequestTiming?.(i),onActivity:()=>{this.lastTick=Date.now()},onCallbackError:(i,a)=>this.logDebug(`gateway client ${i==="hello"?"hello-ok":i==="gap"?"event":i} handler error: ${L(a)}`),handshake:{mode:"require-challenge",timeoutMs:n,timeoutMessage:(i)=>`gateway connect challenge timeout (waited ${i}ms, limit ${n}ms)`},reconnect:{initialMs:1000,multiplier:2,maxMs:30000},requestTimeoutMs:this.requestTimeoutMs,shouldRetrySocketFactoryError:(i)=>!(i instanceof Y)&&!(i instanceof SyntaxError)&&!(i instanceof TypeError)&&!(i instanceof RangeError),rethrowSocketFactoryError:(i)=>i instanceof qt})}get connected(){return!this.stopped&&this.protocol.connected}getConnectionMetadata(){return{clientName:this.opts.clientName,hasDeviceIdentity:Boolean(this.opts.deviceIdentity),mode:this.opts.mode,preauthHandshakeTimeoutMs:this.opts.preauthHandshakeTimeoutMs}}updateNodeManifest(t){if(this.opts={...this.opts,caps:[...t.caps],commands:[...t.commands],computerUse:t.computerUse===void 0?void 0:structuredClone(t.computerUse),workerRuns:t.workerRuns?structuredClone(t.workerRuns):void 0},!this.stopped)this.protocol.closeSocket(1012,"node manifest changed")}start(){if(this.stopped)return;this.protocol.start()}createSocket(t){let n=this.opts.url??br,i=this.opts.edgeAuthHeaders,a=i&&Object.keys(i).length>0?i:void 0;if(a&&new URL(n).protocol!=="wss:")throw new Y("edge auth headers require a wss:// Gateway URL");let l=Oe({env:this.opts.env,configuredTimeoutMs:this.opts.preauthHandshakeTimeoutMs}),p=Cr({url:n,tlsFingerprint:this.opts.tlsFingerprint,tlsServerName:this.opts.tlsServerName,env:this.opts.env,normalizeTlsFingerprint:this.deps.normalizeTlsFingerprint,options:{maxPayload:26214400,handshakeTimeout:l,...this.opts.origin?{origin:this.opts.origin}:{},...a?{followRedirects:!1,headers:a}:{}}});this.deps.beforeConnect();let f,y;try{try{y=this.deps.registerGatewayLoopbackBypass(n),this.opts.assertConnectionCurrent?.()}catch(v){throw new qt(v instanceof Error?v.message:String(v))}f=new Ht(n,p.options),f.binaryType="nodebuffer"}finally{y?.()}this.ws=f,this.transportValidated=!1;let S;return f.on("open",()=>{this.transportValidated=!0,t.open()}),f.on("message",(v)=>t.message(Ct(v))),f.on("close",(v,w)=>{let R=w.toString();if(this.ws===f)this.ws=null;this.resolvePendingStop(f),t.close(v,R)}),f.on("unexpected-response",(v,w)=>{fr(w).then((R)=>{let _=w.statusCode,c=Kn(R)?.error,d=qe(c)?c:void 0,E=w.headers.location,h=E?rr(Array.isArray(E)?E[0]??"":E):void 0;S=new B({code:"UNAVAILABLE",message:`gateway rejected websocket upgrade (HTTP ${_??"unknown"})${R?`: ${R}`:""}`,retryable:!0,details:{reason:"websocket-upgrade-rejected",..._===void 0?{}:{httpStatus:_},...h?{location:h}:{},...typeof d?.type==="string"?{gatewayErrorType:d.type,...typeof d.message==="string"?{gatewayErrorMessage:d.message}:{}}:{}}}),t.error(S),v.destroy(),f.close()})}),f.on("error",(v)=>{if(S)return;if(v.message==="Opening handshake has timed out")Object.assign(v,{code:"ETIMEDOUT"});this.logDebug(`gateway client error: ${L(v)}`),t.error(v instanceof Error?v:Error(String(v)))}),{isOpen:()=>f.readyState===Ht.OPEN,send:(v)=>{this.opts.assertConnectionCurrent?.(),f.send(v)},close:(v,w)=>f.close(v,w)}}stop(){this.beginStop()}async stopAndWait(t){let n=this.beginStop(),i=t?.timeoutMs===void 0?Dr:D(t.timeoutMs);try{await _t(Promise.resolve(n),i,()=>{throw Error(`gateway client stop timed out after ${i}ms`)},{ref:!1})}finally{await this.deviceAuth.drain()}}beginStop(){if(this.stopped=!0,this.pendingDeviceTokenRetry=!1,this.deviceTokenRetryBudgetUsed=!1,clearInterval(this.tickTimer??void 0),this.tickTimer=null,this.pendingStop)return this.pendingStop.promise;let t=this.ws;if(this.ws=null,t){let n=()=>{},i={ws:t,promise:new Promise((l)=>{n=l}),resolve:n};this.pendingStop=i;let a=setTimeout(()=>{try{t.terminate()}finally{this.resolvePendingStop(t)}},kr);if(a.unref?.(),i.terminateTimer=a,this.protocol.connecting){let l=Error("gateway client stopped");this.notifyConnectError(l),this.logDebug(`gateway connect failed: ${L(l)}`)}return this.protocol.stop(),i.promise}return this.protocol.stop(),null}resolvePendingStop(t){if(this.pendingStop?.ws!==t)return;let{resolve:n,terminateTimer:i}=this.pendingStop;if(i)clearTimeout(i);this.pendingStop=null,n()}logDebug(t){this.deps.logDebug(this.deps.redactForLog(t))}logError(t){this.deps.logError(this.deps.redactForLog(t))}shouldRetryWithAlternateNodeProtocol(t){if(!We(this.opts)||!(t instanceof B))return!1;let n=q(t.details);return t.details?.expectedProtocol===(this.useLegacyNodeProtocolEnvelope?W:P)&&(n===C.PROTOCOL_MISMATCH||j(t.message).includes("protocol mismatch"))}resolveConnectRequestFailure(t,n){if(this.shouldRetryWithAlternateNodeProtocol(t)){let p=!this.nodeProtocolTransitionPending;if(this.useLegacyNodeProtocolEnvelope=!this.useLegacyNodeProtocolEnvelope,this.nodeProtocolTransitionPending=!0,p)this.protocol.resetReconnectBackoff(250);return this.logDebug(this.useLegacyNodeProtocolEnvelope?`gateway rejected protocol v${W}; retrying node host with protocol v${P}`:`gateway rejected protocol v${P}; retrying node host with protocol v${W}`),{closeCode:1008,closeReason:"connect retry"}}this.nodeProtocolTransitionPending=!1;let i=t instanceof B?q(t.details):null;if(gt({retryBudgetUsed:this.deviceTokenRetryBudgetUsed,currentDeviceToken:n.resolvedDeviceToken,explicitToken:this.opts.token?.trim()||void 0,storedToken:n.storedToken,trustedEndpoint:this.isTrustedDeviceRetryEndpoint(),errorDetails:t instanceof B?t.details:void 0}))this.pendingDeviceTokenRetry=!0,this.deviceTokenRetryBudgetUsed=!0,this.protocol.resetReconnectBackoff(250);let a=ft(t);if(a!==null)return this.logDebug(`gateway connect failed: ${L(t)}`),{closeCode:1013,closeReason:"gateway starting",reconnectDelayMs:a};if(n.authAgentRuntimeIdentityToken&&this.isUnsupportedConnectAuthField(t,"agentruntimeidentitytoken")){let p=Error("gateway rejected required agent runtime identity auth field; refusing to retry without it");return this.stopped=!0,this.notifyConnectError(p),this.logError(`gateway connect failed: ${p.message}`),{closeCode:1008,closeReason:"connect failed",stop:!0}}if(!this.approvalRuntimeTokenRetryBudgetUsed&&n.authApprovalRuntimeToken&&this.isUnsupportedConnectAuthField(t,"approvalruntimetoken"))return this.approvalRuntimeTokenCompatibilityDisabled=!0,this.approvalRuntimeTokenRetryBudgetUsed=!0,this.protocol.resetReconnectBackoff(250),this.logDebug("gateway rejected approval runtime auth field; retrying without it"),{closeCode:1008,closeReason:"connect retry"};this.notifyConnectError(t);let l=`gateway connect failed: ${L(t)}`;if(this.opts.mode===G.PROBE||Ut(t)||i===C.AUTH_RATE_LIMITED)this.logDebug(l);else this.logError(l);return{closeCode:1008,closeReason:"connect failed"}}resolveClose(t){let n=this.closeInfo(t),i=t.connectFailure?.error instanceof B?q(t.connectFailure.error.details):null,a=t.connectFailure?.error instanceof B?t.connectFailure.error.details:void 0;if(t.code===1013&&t.connectFailure?.reconnectDelayMs!==void 0)return{retry:!0,notify:this.opts.notifyOnStartupRetry===!0,reconnectDelayMs:t.connectFailure.reconnectDelayMs};if(n.transientPreHelloCleanClose&&this.suppressedTransientPreHelloCleanCloses<Ur)return this.suppressedTransientPreHelloCleanCloses+=1,{retry:!0,notify:!0,pendingError:Error("gateway transient pre-hello clean close")};if(n.transientPreHelloCleanClose||t.connectRequestSent&&!t.helloReceived&&!t.connectFailure){let l=Error(`gateway closed (${t.code}): ${t.reason}`);this.notifyConnectError(l),this.logError(`gateway connect failed: ${L(l)}`)}if(this.clearStaleDeviceTokenForClose(t),vt({details:a,deviceTokenRetryPending:this.pendingDeviceTokenRetry,tokenMismatchIsTerminal:!0,protocolMismatchIsTerminal:!this.nodeProtocolTransitionPending,clientVersionMismatchIsTerminal:!0}))return this.notifyReconnectPaused({code:t.code,reason:t.reason,detailCode:i}),{retry:!1,notify:!0};return{retry:!0,notify:!0,reconnectDelayMs:t.connectFailure?.reconnectDelayMs}}closeInfo(t){return{phase:t.helloReceived?"post-hello":"pre-hello",socketOpened:t.socketOpened,transportValidated:this.transportValidated,connectRequestSent:t.connectRequestSent,transientPreHelloCleanClose:!t.helloReceived&&t.code===1000&&t.reason==="",...t.connectFailure?.error?{connectError:t.connectFailure.error}:{}}}clearStaleDeviceTokenForClose(t){let{code:n,reason:i,generation:a}=t;if(n!==1008||!j(i).includes("device token mismatch")||!this.opts.deviceIdentity)return;let l=this.connectionStoredToken?.generation===a?this.connectionStoredToken:{token:void 0};this.clearDeviceToken(this.opts.deviceIdentity.deviceId,l,()=>!this.opts.token&&!this.opts.password)}clearDeviceToken(t,n,i=()=>!0){let a=(p)=>{this.logDebug(`failed clearing stale device-auth token for device ${t}: ${String(p)}`)},l=()=>this.logDebug(`cleared stale device-auth token for device ${t}`);try{let p=this.deviceAuth.clear({deviceId:t,role:this.opts.role??"operator",env:this.opts.env,assertCurrent:()=>{if(this.stopped)throw Error("gateway client stopped")}},n,i);return p instanceof Promise?p.then(l,a):l()}catch(p){a(p)}}notifyConnectError(t){if(!this.opts.onConnectError)return!1;try{return this.opts.onConnectError(t),!0}catch(n){return this.logDebug(`gateway client connect error handler error: ${L(n)}`),!1}}notifyReconnectPaused(t){try{this.opts.onReconnectPaused?.(t)}catch(n){this.logDebug(`gateway client reconnect paused handler error: ${L(n)}`)}}isUnsupportedConnectAuthField(t,n){if(!(t instanceof B)||t.gatewayCode!=="INVALID_REQUEST")return!1;let i=j(t.message);return i.includes("invalid connect params")&&i.includes(n)}isTrustedDeviceRetryEndpoint(){let t=this.opts.url??"ws://127.0.0.1:18789";try{let n=new URL(t),i=n.protocol==="https:"?"wss:":n.protocol==="http:"?"ws:":n.protocol;if(Sr(n.hostname))return!0;return i==="wss:"&&Boolean(this.opts.tlsFingerprint?.trim())}catch{return!1}}startTickWatch(){clearInterval(this.tickTimer??void 0);let t=this.opts.tickWatchMinIntervalMs,n=typeof t==="number"&&Number.isFinite(t)?Math.max(1,Math.min(30000,t)):1000,i=D(Math.max(this.tickIntervalMs,n));this.tickTimer=setInterval(()=>{if(this.stopped)return;if(!this.lastTick)return;if(this.protocol.hasPendingRequests&&!this.protocol.hasUnboundedPendingRequests)return;let a=Date.now()-this.lastTick,l=this.opts.tickWatchTimeoutMs;if(a>(typeof l==="number"&&Number.isFinite(l)?Math.max(1,l):this.tickIntervalMs*2))this.protocol.closeSocket(4000,"tick timeout")},i)}async request(t,n,i){let a=i?.expectFinal===!0,l=i?.timeoutMs===null?null:typeof i?.timeoutMs==="number"&&Number.isFinite(i.timeoutMs)?i.timeoutMs:a?null:this.requestTimeoutMs;return this.protocol.request(t,n,{...i,expectFinal:a,timeoutMs:l})}};var on=g(sn(),1);import{createHash as Xt,createPrivateKey as Lr,createPublicKey as Jt,generateKeyPairSync as xr,sign as Zt,verify as Hr}from"crypto";import{existsSync as ae,linkSync as qr,mkdirSync as en,readFileSync as tn,renameSync as Fr,unlinkSync as nn,writeFileSync as rn}from"fs";import{homedir as Gr}from"os";import{join as ce,resolve as Wr}from"path";var $r=s({version:o(1),deviceId:r(),publicKeyPem:r(),privateKeyPem:r()}),Br=s({version:o(1),deviceId:r(),tokens:T(r(),s({token:r(),role:r(),scopes:u(r()),updatedAtMs:m()}))});function Qe(t){let n=Jt(t);if(n.asymmetricKeyType!=="ed25519")throw Error("Expected an Ed25519 device key");return Buffer.from(n.export({format:"jwk"}).x,"base64url")}function Qt(t){let n=JSON.parse(tn(t,"utf8")),i=s({deviceId:r(),publicKey:r(),privateKey:r()}).safeParse(n),a=i.success?{deviceId:i.data.deviceId,publicKeyPem:Jt({key:{kty:"OKP",crv:"Ed25519",x:i.data.publicKey},format:"jwk"}).export({type:"spki",format:"pem"}).toString(),privateKeyPem:Lr({key:{kty:"OKP",crv:"Ed25519",x:i.data.publicKey,d:i.data.privateKey},format:"jwk"}).export({type:"pkcs8",format:"pem"}).toString()}:$r.parse(n),l=Buffer.from("openclaw-device-identity-self-check");if(!Hr(null,l,a.publicKeyPem,Zt(null,l,a.privateKeyPem)))throw Error("OpenClaw device keys do not match");return{...a,deviceId:Xt("sha256").update(Qe(a.publicKeyPem)).digest("hex")}}function Vr(t){let n=ce(t,"device.json");if(ae(n))return Qt(n);en(t,{recursive:!0,mode:448});let{publicKey:i,privateKey:a}=xr("ed25519"),l=i.export({type:"spki",format:"pem"}).toString(),p={version:1,deviceId:Xt("sha256").update(Qe(l)).digest("hex"),publicKeyPem:l,privateKeyPem:a.export({type:"pkcs8",format:"pem"}).toString(),createdAtMs:Date.now()},f=`${n}.${crypto.randomUUID()}.tmp`;rn(f,JSON.stringify(p),{mode:384,flag:"wx"});try{qr(f,n)}catch(y){if(y.code!=="EEXIST")throw y}finally{nn(f)}return Qt(n)}function an(t=process.env){let n=t.HOME?.trim()||t.USERPROFILE?.trim()||Gr(),i=(R,_)=>Wr(R.replace(/^~(?=$|[\\/])/,_)),a=i(t.OPENCLAW_HOME?.trim()||n,n),l=t.OPENCLAW_STATE_DIR?.trim(),p=ce(a,".openclaw"),f=ce(a,".clawdbot"),y=ce(l?i(l,a):!ae(p)&&ae(f)?f:p,"identity"),S=ce(y,"device-auth.json");function v(R){if(!ae(S))return{version:1,deviceId:R,tokens:{}};let _=Br.parse(JSON.parse(tn(S,"utf8")));return _.deviceId===R?_:{version:1,deviceId:R,tokens:{}}}async function w(R,_){let c=()=>{R.signal?.throwIfAborted(),R.assertCurrent?.()};c(),en(y,{recursive:!0,mode:448});let d,E=await on.lock(S,{realpath:!1,retries:{retries:20,minTimeout:10,maxTimeout:100},onCompromised:(h)=>{d=h}});try{if(c(),d)throw d;let h=v(R.deviceId),A=h.tokens[R.role]?.token;if(R.expectedToken!==void 0&&(A??null)!==R.expectedToken)return;_(h.tokens);let I=`${S}.${crypto.randomUUID()}.tmp`;try{rn(I,JSON.stringify(h),{mode:384,flag:"wx"}),c(),Fr(I,S)}finally{if(ae(I))nn(I)}}finally{if(!d)await E()}}return{loadOrCreateDeviceIdentity:()=>Vr(y),signDevicePayload:(R,_)=>Zt(null,Buffer.from(_),R).toString("base64url"),publicKeyRawBase64UrlFromPem:(R)=>Qe(R).toString("base64url"),loadDeviceAuthToken:(R)=>(R.signal?.throwIfAborted(),R.assertCurrent?.(),v(R.deviceId).tokens[R.role]??null),storeDeviceAuthToken:(R)=>w(R,(_)=>{_[R.role]={token:R.token,role:R.role,scopes:R.scopes,updatedAtMs:Date.now()}}),clearDeviceAuthToken:(R)=>w(R,(_)=>{delete _[R.role]})}}class Kr extends Yt{constructor(t){super({clientVersion:Lt.devDependencies["@openclaw/gateway-client"],...t,hostDeps:{...an(t.env),...t.hostDeps}})}}export{Kr as GatewayClient};